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的工作線程只有一個,因此所有傳進來的任務都是按順序執行




 獨學而無友,則孤陋而寡聞!分享知識,交流技術,碰撞思想。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章