Android中IntentService源码分析及其使用

在Android中,Activity不能直接进行耗时操作,一般可启动子线程来完成耗时操作,但这样做有个缺点,一旦Activity不再可见,Activity所在的进程成为后台进程,而内存不足时后台进程可能会被系统杀死。一般情况下,服务进程的优先级高于后台进程。因此,我们可以启动一个Service,并在Service中创建子线程执行耗时操作。

Android帮我们提供了一个类来解决这个问题,IntentService类是Service的子类,用来处理异步请求。客户端可以通过startService(Intent)方法传递请求给IntentService。IntentService在onCreate()函数中通过HandlerThread单独开启一个线程来处理所有Intent请求对象(通过startService的方式发送过来的)所对应的任务,这样以免事务处理阻塞主线程。执行完一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,则自动停止Service;否则执行下一个Intent请求所对应的任务。HandlerThread的原理及使用可参考上一篇文章--《HandlerThread源码分析及使用》。

IntentService类的源码在frameworks\base\core\java\android\app\IntentService.java中

源码:

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)}.
     */
    protected abstract void onHandleIntent(Intent intent);
}

IntentService在处理事务时,采用的Handler方式,创建一个名叫ServiceHandler的内部Handler,并把它直接绑定到HandlerThread所对应的子线程。 ServiceHandler把处理一个intent所对应的事务都封装到叫做onHandleIntent()的虚函数;因此我们需要直接实现虚函数onHandleIntent(),再在里面根据Intent的不同进行不同的事务处理就可以了。


首先来看onCreat()方法,在其中创建了一个HandlerThread线程,并利用ServiceHandler来处理消息,具体原理可以查看《HandlerThread源码分析及使用》一文。


接着再看ServiceHandler类的定义,其中handleMessage()中调用onHandleIntent()来具体处理消息,处理完成后调用stopSelf(msg.arg1)来停止服务,msg.arg1是什么呢?通过onStart()中发现msg.arg1=startId。这里,我们解释一下stopSelf(startId)的含义:

如果你的Service同时处理多个对onStartCommand()的请求,那么你不应在处理完一个请求之后就停止Service,因为你可能已经又收到了新的启动请求(在第个完成后停止将会结束掉第二个).要避免这个问题,可以使用stopSelf(int)来保证你的停止请求对应于你最近的开始请求.也就是,当你调用stopSelf(int)时,你传递开始请求的ID(传递给onStartCommand()startId)service,如果service在你调用stopSelf(int)之前收到一了个新的开始请求,发现ID不同,于是service将不会停止。


onHandleIntent()方法是一个抽象方法,IntentService子类中必须实现该方法,并根据Intent的不同进行不同的事务处理。


onstartCommand()方法调用onStart()来发送消息,并根据mRedelivery值来决定返回状态,此处具体返回值的含义可查Android文档,不详述。因此,IntentService是一个只能通过Context.startService(Intent)启动并处理异步请求的Service。


onDestroy()方法中直接调用looper.quit()结束HandlerThread线程。


onBind()方法直接返回null,因此,IntentService没有必要使用bindService()的方式绑定来绑定该服务


使用时你只需要继承IntentService和重写其中的onHandleIntent(Intent)方法接收一个Intent对象,在适当的时候会停止自己(一般在工作完成的时候)。所有请求的处理都在一个工作线程中完成,它们会交替执行(但不会阻塞主线程的执行),一次只能执行一个请求。

下面举例说明IntentService的使用:

package com.example.androidtest;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class MyIntentService extends IntentService {

	private String TAG = "MyIntentService";

	public MyIntentService() {
		super("MyIntentService");
		Log.i(TAG, this + " is constructed");
	}

	@Override
	protected void onHandleIntent(Intent arg0) {
		int id = arg0.getIntExtra("id", -1);
		Log.i(TAG, "begin onHandleIntent() in " + this + " id=" + id);
		try {
			Thread.sleep(10 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Log.i(TAG, "end onHandleIntent() in " + this + " id=" + id);
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, this + " is destroy");
		super.onDestroy();
	}
}

启动MyIntentServic的代码片段:

        Intent intent = new Intent(this, MyIntentService.class);
	intent.putExtra("id", 1);
	startService(intent);
	intent.putExtra("id", 2);
	startService(intent);
	intent.putExtra("id", 3);
	startService(intent);

别忘了在AndroidManifest.xml文件中注册该Service:

<service android:name="com.example.androidtest.MyIntentService"></service>

运行结果:

05-04 20:59:07.470: I/MyIntentService(857): com.example.androidtest.MyIntentService@b3dd4248 is constructed
05-04 20:59:07.490: I/MyIntentService(857): begin onHandleIntent() in com.example.androidtest.MyIntentService@b3dd4248 id=1
05-04 20:59:17.500: I/MyIntentService(857): end onHandleIntent() in com.example.androidtest.MyIntentService@b3dd4248 id=1
05-04 20:59:17.500: I/MyIntentService(857): begin onHandleIntent() in com.example.androidtest.MyIntentService@b3dd4248 id=2
05-04 20:59:27.570: I/MyIntentService(857): end onHandleIntent() in com.example.androidtest.MyIntentService@b3dd4248 id=2
05-04 20:59:27.570: I/MyIntentService(857): begin onHandleIntent() in com.example.androidtest.MyIntentService@b3dd4248 id=3
05-04 20:59:37.650: I/MyIntentService(857): end onHandleIntent() in com.example.androidtest.MyIntentService@b3dd4248 id=3
05-04 20:59:37.670: I/MyIntentService(857): com.example.androidtest.MyIntentService@b3dd4248 is destroy


通过log信息可以看到任务的执行是顺序(串行)执行的。


注意:IntentService的子类的构造方法一定是参数为空的构造方法,然后再在其中调用super("name")这种形式的构造方法。因为Service的实例化是系统来完成的,而且系统是用参数为空的构造方法来实例化Service的。


猜你喜欢

转载自blog.csdn.net/wangsf1112/article/details/51317176