「这是我参与11月更文挑战的第23天,活动详情查看:2021最后一次更文挑战」
简介
Service是安卓的四大组件之一,就是服务的意思,通常他用与在后台为我们执行一些耗时,或长时间执行得到一些操作。
Service的创建
Service的创建和Activity类似,也是通过Intent来实现的。下面是一个简单的例子。
public class MyService extends Service {
private static final String TAG = "Service";
private DownloadBinder mBinder = new DownloadBinder();
public class DownloadBinder extends Binder {
public void startDownload() {
Log.d(TAG, "startDownload: ");
}
public int getProgress() {
Log.d(TAG, "getProgress: ");
return 0;
}
}
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return mBinder;
}
//服务创建时被调用
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
}
//服务启动时被调用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
return super.onStartCommand(intent, flags, startId);
}
//服务被关闭时调用
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}
首先创建也个MyService类继承Service,然后重写它的onCreate,onStartCommand,onDestroy方法等。
除此之外还需要在manifest文件中对这个服务进行注册。
<service
android:name=".service.MyService"
android:enabled="true"
android:exported="true" />
在这里边设置了两个属性
- enabled:是指该服务是否能够被实例化。
- exported:用于指示该服务是否能够被其他应用程序组件调用或跟它交互。有效阻止其他应用启动您的服务,即使服务提供了intent过滤器,本属性依然生效。
启动和停止服务
主要是两个方法startService和stopService。使用的方式:
Intent intent = new Intent(this, MyService.class);
//启动服务
startService(intent);
//关闭服务
stopService(intent);
通过startService,Service会经历。onCreate-->onStart,当stopService回直接onDestroy。如果调用者直接退出没有调用stopService的话,这个服务会一直在后台运行,当下次调用者在起来的时候仍然可以stopService
绑定和解绑服务
//活动与服务之间的进程通信
//活动绑定时调用
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
//服务连接时调用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
//服务被意外销毁时会被调用
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("123", "onServiceDisconnected: 1");
}
};
Intent intent = new Intent(this, MyService.class);
//绑定服务
bindService(intent, connection, BIND_AUTO_CREATE);
//解绑服务
unbindService(connection);
通过bindService,Service只会去运行onCreate,这个时候Service和调用者是绑定在一起的,如果调用者退出了Srevice就会调用onUnbind-->onDestroyed,绑定其实就是共存亡吧。