天天看點

Service子類IntentService特性運用

/*
*Service服務:與Activity最相似;都繼承了Context;有自己的生命周期;也可作為可執行的程式.
*差別是運作在背景,不會有界面.
* 使用中如果需要使用者互動應該用Activity;否則應該選用Service.
* 生命周期方法5個:onCreate() onBind() onStartCommand() onUnbind() onDestroy()
* onCreate() Service第一次執行個體化回調
* onBind() 該方法傳回IBinder對象,用于應用程式與Service通信;必須重官吏的方法,通常繼承Binder()子類來實作自己的IBinder對象.
* onStartCommand()當調用startService()方法啟動Service時會回調方法.
* onUnbind()Service上的用戶端都斷開連接配接時回調
* onDestroy()Service被關閉時回調.
*
*同樣使用Service需要繼承基類或其子類 IntentService
* 使用步驟2
*   1 定義繼承Service的子類,重寫其周期方法 onBind()為必須重寫的方法.
*   2 在AndroidManifest.xml中配置<service name:> 四大元件須顯式配置.
*
*   Android5.0開始,要求須顯式Intent啟動Service.
*   啟動關閉(配套使用的)Service startService()    stopService() 這樣啟動的Service與啟動它的用戶端沒有什麼聯系.
*                               bindService()   unBindService()這樣啟動的Service與用戶端綁定在一起了,當
*                               通路者退出,Service與退出.
*
*  當bindService(ServiceConnection)方法啟動, onBinder()方法傳回的IBinder對象會給到 ServiceConnection對象onServiceConnected()方法
*
*  當用戶端連接配接到Service,onServiceConnected()被回調;異常中止回調onServiceDisconnected();(正常unBindService()不會回調)
*
*生命周期分2種:用戶端調用startService()方法-->onCreate()回調-->onStartCommand()回調-->調用stopService()-->onDestroy()回調.
* 用戶端調用bindService()方法-->onCreate()回調-->onBind()回調-->unBindService()-->onUnBind()回調-->onDestroy()回調
*
* Service有2缺陷: 與所在的應用為同一程序;不是單獨的線程,不能進行耗時任務.
*
* IntentService:繼承了Service, 5個優點:
*   1 用隊列的形式來處理Intent.
*   2 單獨的線程處理onHandlerIntent()方法
*   3 當Intent處理完成,自動停止.
*   4 重寫了onBind()方法 onStartCommand()方法
*   5 使用IntentService隻需要實作OnHandlerIntent()方法即可...(由于會單獨線程,無須擔心阻塞線程或ANR)
*
* */

package com.example.tyxiong.myapplication;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;


class MyService extends IntentService {


    public MyService() {
        super("MyService");//指定該線路線線程的線線程名...
    }

    @Override
    protected void onHandleIntent(Intent intent) {//該方法不會阻塞UI線程,也不會ANR, 單獨的線程.
        long time = System.currentTimeMillis() + 10 * 1000;
        while (time > System.currentTimeMillis()) {
            synchronized (this) {
                try {
                    wait(time - System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
        Log.w("xxx", "耗時任務完成");//Intent隊列任務執行完成會自動停止,無須調用stopService()方法來停止Service
    }
}