一、Service
(1)service介绍
service是一个没有界面,可以长期运行在后台的应用程序(没有界面的activity);Service和其他组件(activity,broadcast,contentprovider)一样,运行在主线程,当在主线程中做耗时操作,大于5秒,就会ANR,所以在service中做耗时操作,应开启工作线程;因此不能用它来做耗时的操作,每个进程service类的实例只能有一个。
如何判断service是否在主线程(判断looper)
public class DemoService extends Service {
@Override
public void onCreate() {
super.onCreate();
//判断是否同一个looper
Log.e("DemoService",Looper.getMainLooper()==Looper.myLooper()?"true":"false");
//判断是否同一个thread
Log.e("DemoService",Thread.currentThread().getName());
}
(2)service和thread的区别
- 进程是资源分配的单元,服务进程,thread是程序执行的最小单元,它是分配CPU的基本单位。
- thread和service的声明周期不一样。
- service和thread有点相似,都是在后台运行。Android应用程序启动会开启一个进程,当把全部界面关闭时,如果运行的是service,这个进程就是服务进程,如果运行的是thread,运行在空进程中,很容易被销毁。
(3)service的生命周期
- startService() stopService()方式
Intent intent=new Intent(this, DemoService.class);
startService(intent);
startService(intent); //多次启动服务
stopService(intent);
onCreate()
onStartCommand()
onStartCommand()
onDestroy()
注:oncreate方法只会执行一次;onStartCommand可以执行多次;开启的service的activity可以被销毁,如果service没有调用stopService那么它还存在。
- bindService() unBindService()方式
Intent intent = new Intent(this, DemoService.class);
MainServiceConnection connection = new MainServiceConnection();
bindService(intent, connection, BIND_AUTO_CREATE);
unbindService(connection);
onCreate()
onBind()
onUnbind()
onDestroy()
注:oncreate方式只会执行一次;onBind也只会执行一次;如果activity没有调用unBIndservice方法就被销毁,那么service会报错。
- 混合方式
Intent intent=new Intent(this, DemoService.class);
startService(intent); //两种方式可以调换位置
MainServiceConnection connection = new MainServiceConnection();
bindService(intent, connection, BIND_AUTO_CREATE);
unbindService(connection);
stopService(intent);
onCreate()
onStartCommand()
onBind()
onUnbind()
onDestroy()
//注
//1、两种方式可以调换位置
//2、当调用unBindService,服务只会调用onUnbind方法,不会调用onDestory方法,只有调用了onStop方法
时,服务才会调用onDestory
3、启动服务的优先级比绑定服务高,所以联合方式,最后都成了启动服务
(4)service与activity的交互
1、定义中介类,中间类需集成Binder类,或实现IBinder接口
public class ServiceIBinder extends Binder{
public void callMethod(){
}
}
2、Service类的onbind方法返回中间类的对象
public class DemoService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.e("aaa","onCreate()");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e("aaa","onBind()");
return new ServiceIBinder();
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("aaa","onUnbind()");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.e("aaa","onDestroy()");
super.onDestroy();
}
}
3、创建连接类,这个类得实现ServiceConnection接口
public class MainServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinder = (ServiceIBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
4、启动服务
Intent intent=new Intent(this, DemoService.class);
MainServiceConnection connection = new MainServiceConnection();
bindService(intent, connection, BIND_AUTO_CREATE);
5、以上是在activity中调用service的服务,service调用activity方式如下
(1)使用EventBus(推荐)
(2)接口回调
//第一步
private ISercvice mISercvice;
public class ServiceIBinder extends Binder {
public void callMethod(){
}
//提供方法,添加activity的引用
public void setISercvice(DemoService.ISercvice iSercvice) {
mISercvice = iSercvice;
}
}
//定义接口,需要activity实现这个接口与
public interface ISercvice {
void setDataChange();
}
第二步
public class ASfConnect implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder=(ServiceIBinder)service;
binder.setISercvice(MainActivity.this); //设置
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
二、IntentService
service是运行在主线程中的,所以不能进行耗时操作,如果要进行耗时操作,只能开辟工作线程。而官方就提供了一个类IntentService,IntentService是继承Service类,定义了一个handler的实现类ServiceHandler。
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
在onCreate方法中,进行了初始化serviceHandler,looper来自HandlerThread,HandlerThread是一个专门处理异步线程。
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
当调用者调用startService方法时,调用了onStartCommand方法,而onStartCommand方法内部调用了onStart()方法,
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
在onStart方法中,发送了一个消息,现在看接受消息的ServiceHandler,在handlerMessage方法中,调用onHandlerIntent方法,这是个抽象方法,由子类实现,任务执行完毕后,会自己调用stopSelf方法来停止service。
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
另外,onDestory方法,停止轮训
@Override
public void onDestroy() {
mServiceLooper.quit();
}
注:
(1)同一个IntentService只会新建一个线程,多次调用服务,可以看出工作线程时一个队列,对一个任务完成之后才会执行一 下 项操作
(2)不同的IntentService都会新建一个线程,线程之间是独立的(公用资源需要考虑线程同步的问题)