码迷,mamicode.com
首页 > 其他好文 > 详细

anroid-理解IntentService方式开启一个服务

时间:2015-08-03 11:40:49      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

从网上摘录了对IntentService总结较完整的结论:

IntentService特征 

  • 1、会创建独立的worker线程来处理所有的Intent请求  

  • 2、会创建独立的worker线程来处理onHandleIntent()方法实现的代码,无需处理多线程问题  

    3、所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service  

    4、为Service的onBind()提供默认实现,返回null  

  • 5、为Service的onStartCommand提供默认实现,将请求Intent添加到队列中 

下面,我将要结合源代码对以上5个特点进行阐述:

  • 1、会创建独立的worker线

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);
}

在之前,我们先看一下HanderThread到底是什么?

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);
    }
}

从上面的定义,我们可以看出,ServiceHandler是一个私有的内部类,而且是继承了Handler,正是因为它继承了Handler,才有了我们所说的,它可以创建独立的worker线程,实际上的worker线程就是这个继承了Handler的内部类线程。并且在onCreate方法中对其进行了初始化。

during processing, and to have a static startService(Context, Intent) method that would launch the service & hand off a wakelock.

在onCreate方法中,有如上的注释,结合刚才的解释,大概的意思是说,只要你调用了startService方法,就可以开启一个服务,并且该服务会创建一个独立的线程,具体干什么?下面将逐步进行说明。

2、会创建独立的worker线程来处理onHandleIntent()方法实现的代码,无需处理多线程问题

我们还是从service的生命周期回调函数来深入展开分析。

下一步,将进入onStartCommand周期函数中。首先开一下代码实现:

public int onStartCommand(Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}

在此会调用onStart方法:

public void onStart(Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
}

在onStart方法中,我们很清楚的发现,实际上,执行过该方法之后,所产生的效果是,调用时所传入的Intent,通过消息队列,传入到了ServiceHandler类中的 handleMessage(Message message)中

@Override
public void handleMessage(Message msg) {
    onHandleIntent((Intent)msg.obj);
    stopSelf(msg.arg1);
}

通过该方法的实现,我们可以看出,其会执行onHandleIntent方法,其方法是一个抽象方法,需要用户去实现,所以,用户在使用该模式创建一个Service时,必须要重写onHandleIntent方法。当该方法执行结束会,调用了stopSelf()方法,其会传入的服务的ID,来自动的关闭该服务,所以,不需要用户去手动的关闭一个服务,只要onHandleIntent方法执行结束,就会自动调用停止该服务。

  • 3、所有请求处理完成后,IntentService会自动停止,无需调用stopSelf()方法停止Service  

  • 2中已做解释

    4、为Service的onBind()提供默认实现,返回null  

  • public IBinder onBind(Intent intent) {
        return null;
    }
  • 5、为Service的onStartCommand提供默认实现,将请求Intent添加到队列中

2中已做解释


anroid-理解IntentService方式开启一个服务

标签:

原文地址:http://my.oschina.net/ccqy66/blog/487005

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!