源码解析IntentService的好处

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

文章摘自:[IntentService]Android源码分析——IntentService的好处 - 亭子happy的个人页面 - OSCHINA - 中文开源技术交流社区

源码:

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,
     * {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  #onStartCommand(Intent, int, int)} will return
     * {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  Service#START_REDELIVER_INTENT}, so if this process dies before
     * {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  #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),
     * {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  #onStartCommand(Intent, int, int)} will return
     * {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  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 {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * <A href="http://my.oschina.net/u/244147" rel=nofollow target=_blank>@see</A>  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. 
     * <A href="http://my.oschina.net/u/244147" rel=nofollow target=_blank>@see</A>  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 {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A>  #stopSelf}.
     *
     * @param intent The value passed to {<A href="http://my.oschina.net/link1212" rel=nofollow target=_blank>@link</A> 
     *               android.content.Context#startService(Intent)}.
     */
    protected abstract void onHandleIntent(Intent intent);
}

它是将发来的Intent放到一个新线程中去处理的。对于异步的startService请求,IntentService的这个新线程会处理完第一个,再处理第二个。

这样的设计和Service有关。

先来说说Service,它有两点要说明:

1、Service不是一个进程,它和应用程序在同一个进程中;

2、Service也不是一个线程,它运行在应用程序的主线程中。

因此,一般用Service时有耗时的操作,都会将这些操作放到新启的线程中。这样的话,需要自己在Service中创建线程,而IntentService就帮我们做了这项工作。

因为大部分Service的操作都需要另启线程,也就是说大部分Service都可以用IntentService来代替。这就是IntentService的作用。


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值