直接上代码,IntentService是一个抽象类,首先创建一个它的子类:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
SystemClock.sleep(3000);
String stringExtra = intent.getStringExtra("key");
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:MM:ss");
String time = format.format(new Date(System.currentTimeMillis()));
Log.e("wcc", "onHandleIntent _ " + stringExtra + ", time is " + time);
}
@Override
public void onCreate() {
super.onCreate();
Log.e("wcc", "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.e("wcc", "onStart");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("wcc", "onDestroy");
}
}
接下来是启动服务的代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, MyIntentService.class);
intent.putExtra("key", "value1");
startService(intent);
intent.putExtra("key", "value2");
startService(intent);
}
}
启动了两次服务,每次存储在extra中的值都不一样。在onHandleIntent方法中执行耗时操作,并在各个生命周期方法中打印log。
打印log如下:
启动两次服务,onStart调用两次,onHandleIntent方法被调用两次且间隔3秒,最后onDestroy也被调用。为了解释上面这一现象,下面开始从源码角度分析IntentService工作原理。
public class HandlerThread extends Thread {
//...code
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
//...code
public Looper getLooper() {
if (!isAlive()) {
return null;
}
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
//...code
}
第8行,初始化Looper对象,并使用ThreadLocal存储该子线程的Looper。
@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);
}
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
第8行,创建HandlerThread对象,它是一个开启了消息循环的子线程。
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);
}
}
第3行,调用Handler中Looper为参数的构造函数;
protected abstract void onHandleIntent(Intent intent);
onHandleIntent是一个抽象方法,需要我们自己重写该方法,并将耗时操作放在里面。