概念:
1、startService(Intent)通过这种方式开启的服务,执行的生命周期方法:
第一次调用startService的时候:onCreate→onStartCommand
再次调用startService的时候:只执行onStartCommand
2、想停止用startService开启的服务要使用stopService(Intent),stopService执行之后,Service会走onDestroy()方法,执行之后Service销毁,再次调用stopService没有反应
3、如果在Activity中通过startService方法开启一个服务,当Activity退出的时候Service不会销毁,依然在后台运行,只有手动调用stopService或者在应用管理器中关闭Service,服务才会销毁
4、通过startService可以提高应用的优先级
在MainActivity中代码*************
···
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v){
//使用显示意图开启service服务
Intent service = new Intent();
//通过方法开启服务
startService(service);
}
public void stop(View v){
Intent intent = new Intent();
}
【两种服务(StartService|两种服务(StartService 和bindService)】}
···
在创建一个类 MyService 继承Sercive
-----------------代码如下-----------
···
public class MyService extends Service{
@Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "onBind");
return null;
}
@Override
public void onCreate() {
Log.e("TAG", "onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e("TAG", "onDestroy");
super.onDestroy();
}
}
···
xml.---------------
···
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
···
BindService--------------------------
1、开启服务时生命周期比较:
bindService onCreate→onBind(只会执行一次)
startService onCreate→onStartCommand(调用一次startService执行一次)
2、startService开启的服务跟Activity没有关系,bindService开启的服务,跟Activity之间不求同生,但求同死,Activity退出的时候必须通过unbindService关闭服务
3、startService结束的时候stopService可以调用多次,只有第一次调用的时候有效,bindService结束的时候unbindService只能调用一次,调用多次应用会抛异常
4、bindService的时候传入的第二个参数是ServiceConnection,只有当onBind方法返回不为空的时候才会调用onServiceConnected
布局中*****************
···