一.Service能不能执行耗时操作?
Service是Android四大组件之一,是运行在后台的服务,可用来执行不需要在前台展示的动作,如播放音乐等;有些人可能会认为,
Service竟然是在后台运行的那不就可以用来执行耗时操作了,这样也不会影响前台页面,其实不行,因为Service也是运行在主线程,
所以Service是不能用来执行耗时操作的。
二.Service中开启线程
既然Service不能执行耗时操作,那么如果我们需要在Service中执行耗时操作要怎么办呢? 那肯定是开启子线程来处理:
例如:
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
这样确实可以,但是Android中提供了一个封装好子线程的Service给我们使用,使用起来更加简单,那就是IntentService。
三.IntentService的使用:
1.IntentService简介:
IntentService是继承Service的抽象类,在IntentService中有一个工作线程来处理耗时操作。
2.IntentService源码
我们先来看下IntentService的源码:
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
IntentService继承Service
@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);
}
我们看到IntentService的onCreate方法中利用HandlerThread创建了一个循环的工作线程,然后将工作线程中的Looper对象作为参数来创建ServiceHandler消息执行者。
3.IntentService的使用:
public class TestService extends IntentService {
public TestService() {
super("TestService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//执行耗时操作
}
}
可以看到IntentService的使用非常简单。