Service和IntentService 源码分析和总结


转载请注明出处:http://blog.csdn.net/onlybeyond99/article/details/50611275   挨踢人one
service
    Android 四大组建之一,存放一些需要长时间存活的对象,但并不是耗时操作,一般Service也是在主线程中。耗时的操作应该用AntentService。
    Service绑定的和非绑定的
   

Activity给非绑定的Service传值:在onStartCommand()中可以获得相应的Intent,Intent的可以用传参数
Activity给绑定的Service传值,在onbind()中可以获得相应的Intent,Intent的可以用于传参数
service给activity传值Handler或者EventBus都行。

Service销毁:当Service于所有的Activity都没有关系时才能被销毁。

IntentService
 可以简单的理解成执行耗时操作的Service


执行过程 oncreate的创建工作线程,获取线程Looper,创建ServiceHandler
.这是实现工作线程和子线程交互的关键。如果Service被启动过就不会在调用onCreate()
@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);
}


每回startService后都会调用onStartCommand()方法。
public int onStartCommand(Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery START_REDELIVER_INTENT START_NOT_STICKY;
}

然后在onStart()方法中回调用onCreate()方法中创建的ServiceHandler,发送消息并传递Intent,
加入消息队列。收到消息后,执行onHandlerIntent()
@Override
public void onStart(Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
}

注意一般IntentService的工作线程只有一个,因此所有传进来的任务都是按顺序执行




 独学而无友,则孤陋而寡闻!分享知识,交流技术,碰撞思想。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章