1、Service
1)两种启动方式及其生命周期
2)bindService(Intent service, ServiceConnection conn, int flags)
执行onBind方法,返回IBinder类型,用于IPC(进程间通信)。实现ServiceConnection接口,即可获取onBind方法返回的IBinder。
Binder类实现了IBinder接口,如果接收到Binder类型的返回值,调用transact(int code, Parcel data, Parcel reply, int flags), 即可执行回调函数onTransact(int code, Parcel data, Parcel reply, int flags),通过传递Parcel类型的数据实现了进程间通信。
3)IntentService
a)Service需要新起线程执行任务
Caution: A services runs in the same process as the applicationin which it is declared and in the main thread of that application, by default. So, if your serviceperforms intensive or blocking operations while the user interacts with an activity from the sameapplication, the service will slow down activity performance. To avoid impacting applicationperformance, you should start a new thread inside the service.
所以IntentService中,使用了HandlerThread(继承了Thread),另起一个新的线程来执行我们的任务
当Service第一次被启动时,会执行onCreate方法,也就是说当Service第一次运行时,处理任务的线程也就开始执行了。
注:同时用当前线程的Looper来初始化Handler。
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
b)HandlerThread的run()方法
线程开始执行后,调用Looper.prepare()初始化当前线程中的Looper mLooper,并且调用Looper.loop()持续分发消息。
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
注:同时可以实现void onLooperPrepared() 方法
/**
* Call back method that can be explicitly over ridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
为什么这样设计呢?接着往下看。
在Service创建后再调用startService时只会执行onStart,也就是说每个IntentService只有一个线程来处理任务。就是通过不断的发送消息到消息队列,然后交由Handler来处理
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
可以通过实现抽象方法abstract void onHandleIntent(Intent intent),来完成我们的任务
注:按照前面的生命周期,当使用bindService启动IntentService时,只执行onBind方法,而IntentService并没有实现该方法。