IntentService

IntentService是Service的子類,和 Service 不同的是 IntentService 自帶一個子線程,該子線程支持消息消息循環,Service 中的所有耗時任務都可以放到該子線程中來完成。該子線程使用的 HandlerThread 類型,是一個帶 Looper 的可以關聯 handler 的線程。IntentService 自帶的 handler 是 ServiceHandler。在 Service 的 onCreate 中創建的該 thread,在 Service 的 onDestroy 中通過 looper 的 quit 方法結束線程。

1.IntentService特徵

有獨立的 worker 線程來處理 Intent 請求,默認 handler 會調用onHandleIntent() 方法來處理;
所有請求處理完成後,IntentService會自動停止,無需調用stopSelf()方法停止Service;
爲Service的onBind()提供默認實現,返回null;
爲Service的onStartCommand提供默認實現,將請求Intent封裝成了消息,讓 ServiceHandler 調用 onHandlerIntent 方法在子線程中來處理;

2.使用步驟

1.繼承IntentService類,並重寫onHandleIntent()方法

MyIntentService.java

public class MyIntentService extends IntentService {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("----onCreate---");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // IntentService會使用單獨的線程來執行該方法的代碼
        // 該方法內執行耗時任務,比如下載文件,此處只是讓線程等待20秒
        long endTime = System.currentTimeMillis() + 20 * 1000;
        System.out.println("onStart");
        while (System.currentTimeMillis() < endTime) {
            synchronized (this) {
                try {
                    wait(endTime - System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("----耗時任務執行完成---");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("----onDestroy---");
    }
}

2.通過 startService 調用 Service 功能

MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.intentService:
                Intent intent = new Intent(this, MyIntentService.class);
                startService(intent);
                break;
            case R.id.service:

                break;
            default:
                break;
        }
    }

}

3.在 AndroidManifest.xml 中註冊 Service

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章