1.服务是什么:服务是Android四大组件之一,是实现android程序后台运行的解决方案,适合执行不需要交互并且长期运行的任务。
2.开启一个服务,和启动activity是很像的。
Intent startService=new Intent(ServiceActivity.this, MyService.class);
startService(startService);
关闭一个服务
Intent stopService=new Intent(ServiceActivity.this, MyService.class);
stopService(stopService);
3.为了能够让activity和service关联,android提供了另一种开启服务的方式Bind。
自定义一个匿名Binder类,用来承载供activity调用的service中的业务逻辑。
private DownloadBinder mBinder=new DownloadBinder();
public class DownloadBinder extends Binder{
public void startDownload(){
Log.d("csc","myService 中startDownload被执行了");
}
public void getProgress(){
Log.d("csc","myService 中getProgress被执行了");
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
创建绑定服务必需的ServiceConnection对象,以便获取service中的方法
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyService.DownloadBinder binder=(MyService.DownloadBinder)service;
binder.startDownload();
binder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
绑定服务
Intent bindService=new Intent(ServiceActivity.this, MyService.class);
bindService(bindService,connection,BIND_AUTO_CREATE);
解绑服务
unbindService(connection);
4.服务的生命周期,
使用startService启动时:onCreate->onStart,使用stopService时onDestroy,服务只能被创建一次,之后再创建都只调用onStartCommand方法,不再调用onCreate。
使用bindService启动时:onCreate->onBind,使用unBindService时onDestroy,服务只能被绑定一次,之后在绑定就不会有反应了,也只能被解绑一次,再次解绑会奔溃。
5.服务一般会在onStartCommand中创建子线程,然后子线程任务结束以后调用stopself来停止服务。
6.android提供了IntentService来处理耗时操作,耗时操作都放到onHandleIntent中进行,并在子线程完成之后自动销毁service。
public class MyIntentService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*调用父类的有参构造函数
*/
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("csc","当前线程ID为"+Thread.currentThread().getId());
}
@Override
public void onDestroy() {
Log.d("csc","myIntentService被销毁了");
}
}
网友评论