我们都知道,在Android中,耗时的操作不能再主线程中执行,需要另开线程。比如,在一个Activity中,需要读取数据,就需要开辟一个子线程来处理。这样做会有一个问题,如果该任务还没有执行完,Activity已经被销毁了,那么该进程也就销毁了,大部分情况下不需要做特殊处理,但有时候我们希望即使Activity销毁后,该任务仍能继续处理,这时就需要使用后台服务了--service了。Service也是运行在主线程中,所有在Service中耗时的操作也必须在子线程中完成。在这里,我们所说的Service在运行在主线程中,并不一定与Activity是同一个主线程,该怎么理解呢?如果是本地服务,那么Service和Activity就在同一个进程的主线程中了,如果是远程服务,那么Service和Activity不在同一个进程,但是Service运行在其所在进程的主线程中,所以也是不能做耗时操作的。
源码分析
我们直接使用service来处理耗时操作需要自己管理service的生命周期、子线程创建管理,当然我们完全可以自己处理的,不过Android系统已经为我们想到了,提供了IntentService来解决这样的问题。
示例代码
实现IntentService的子类,
public class DownloadService extends IntentService {
private final static String TAG = "DownloadService";
public DownloadService() {
super("DownloadService...");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "onHandleIntent...");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy...");
}
}
主要两点:
1、构造函数
2、实现onHandleIntent方法,睡眠3秒,模拟耗时操作,这个方法执行在子线程中(后面分析),可以做耗时操作
在Activity启动服务
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DownloadService.class);
startService(intent);
startService(intent);
startService(intent);
}
}
IntentService的启动方式跟一般的Service是一样的,在这里我们启动了三次,观察其执行过程。
10-18 11:46:26.915 16245-16270/com.windy.intentservicedemo D/DownloadService: onHandleIntent...
10-18 11:46:29.916 16245-16270/com.windy.intentservicedemo D/DownloadService: onHandleIntent...
10-18 11:46:32.916 16245-16270/com.windy.intentservicedemo D/DownloadService: onHandleIntent...
10-18 11:46:32.917 16245-16245/com.windy.intentservicedemo D/DownloadService: onDestroy...
可以看到,每隔3秒执行一次onHandleIntent,最后自行销毁。
好了,IntentService的使用非常简单,很好的简化了开发过程,下面在从源码的角度来看。
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
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);
}
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public IntentService(String name) {
super();
mName = name;
}
/**
* Sets intent redelivery preferences. Usually called from the constructor
* with your preferred semantics.
*
* <p>If enabled is true,
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_REDELIVER_INTENT}, so if this process dies before
* {@link #onHandleIntent(Intent)} returns, the process will be restarted
* and the intent redelivered. If multiple Intents have been sent, only
* the most recent one is guaranteed to be redelivered.
*
* <p>If enabled is false (the default),
* {@link #onStartCommand(Intent, int, int)} will return
* {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
* dies along with it.
*/
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@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);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
}
很显然,IntentService是service的一个子类,重写了service方法,我们就按照service的执行过程来看。
1、初始化了HandlerThread(此处不再详述),指定了线程名,从这点可以看出并不会开辟多个子线程(当然也可以指定线程)。
2、使用HandlerThread的消息队列Looper来初始化ServiceHandler,ServiceHandler是Handler的子类,实现handleMessage方法。
3、每次启动service都会执行onStartCommand方法,发送消息到ServiceHandler中处理。
4、handleMessage中执行onHandleIntent方法,执行完之后销毁服务,回调onDestroy。
整个过程还是很清晰的,这么做的好处:
任务的执行都在子线程中进行的,不需要我们开辟线程,并且每次只执行一个线程,执行完一个再执行另一个;执行完之后会自动销毁服务,做到需要时启动,减少了系统不必要的开支。
任务的执行都在子线程中进行的,不需要我们开辟线程,并且每次只执行一个线程,执行完一个再执行另一个;执行完之后会自动销毁服务,做到需要时启动,减少了系统不必要的开支。