Service是Android四大组件与Activity最为相似的组件,他们的区别在于Service没有可视化界面,而且Service是一直在后台运行的,不能跑到前台的,今天和大家分享下Service的生命周期和基本使用
目录
一:创建Service
1.创建MyService继承于Service
public class MyService extends Service {
public static final String TAG = "MyService";
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate() executed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
2.AndroidManifest.xm注册
<service android:name=".MyService"/>
二:启动和停止Service
1.开启
Intent intent = new Intent(this, MyService.class);
startService(intent);
2.停止
Intent intent = new Intent(this, MyService.class);
stopService(intent);
3.绑定服务
Intent intent = new Intent(this, MyService.class);
conn = new MyConn();
//绑定服务,
// 第一个参数是intent对象,表面开启的服务。
// 第二个参数是绑定服务的监听器
// 第三个参数一般为BIND_AUTO_CREATE常量,表示自动创建bind
bindService(intent, conn, BIND_AUTO_CREATE);
4.解绑服务
unbindService(conn);// 解除绑定,断开连接
5,传值
Intent intent = new Intent(this, MyService.class);
intent.putExtra("key", true);
intent.putExtra("key2", "123");
startService(intent);
4.接收
在这里插入代码片
三:生命周期
onCreate():
首次创建服务时,系统将调用此方法。如果服务已在运行,则不会调用此方法,该方法只调用一次。
onStartCommand():
当另一个组件通过调用startService()请求启动服务时,系统将调用此方法
onDestroy():
当服务不再使用且将被销毁时,系统将调用此方法
onBind():
当另一个组件通过调用bindService()与服务绑定时,系统将调用此方法
onUnbind():
当另一个组件通过调用unbindService()与服务解绑时,系统将调用此方法
onRebind():
当旧的组件与服务解绑后,另一个新的组件与服务绑定,onUnbind()返回true时,系统将调用此方法
四:普通服务和绑定式服务区别
1.普通服务
Service会经历 onCreate --> onStart
stopService的时候直接onDestroy
如果bai是 调用者 直接退出而du没有调用stopService的话,Service会一zhi直在后台运行。
下次调用者再起来仍然dao可以stopService。
2.绑定式服务
Service只会运行onCreate, 这个时候 调用者和Service绑定在一起
调用者退出了,Srevice就会调用onUnbind–>onDestroyed
所谓绑定在一起就共存亡了。