二. 实现Service
实现服务有两种方式,继承service或者IntentService。后者是前者的子类。前者包含上一章节中Service的几个重要的方法,用于普通的服务。后者可以自己开一个工作线程,串行的处理多个请求。
2.1继承Service
继承Service就可以实现对请求多线程的处理,前面介绍了Service的生命周期,可以按照生命周期实现方法,就不放示例了。
2.2继承IntentService
大多数服务不需要同时处理多个请求,继承IntentService是最好的选择。
IntentService处理流程:
1.创建按默认的一个worker线程处理传递给onStartCommand()所有的intent,在非UI线程中工作。
2.创建一个工作队列依次传递一个intent到你实现的onHandleIntent()方法,避免了多线程。
3.在所有启动请求被处理后自动关闭服务,不需要调用stopSelf()
4.默认提供onBind()的实现,并返回null
5.默认提供onStartCommand()的实现,实现发送intent到工作队列再到你的onHandleIntent()方法实现。
这些都加入到IntentService中了,你需要做的就是实现构造方法和onHandleIntent(),如下:
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
}}