[Android] IntentService使用詳解和執行個體介紹

來源:互聯網
上載者:User

標籤:

IntentService定義

  IntentService繼承與Service,用來處理非同步請求。用戶端可以通過startService(Intent)方法傳遞請求給IntentService。IntentService在onCreate()函數中通過HandlerThread單獨開啟一個線程來依次處理所有Intent請求對象所對應的任務。 
  
  這樣以免交易處理阻塞主線程(ANR)。執行完所一個Intent請求對象所對應的工作之後,如果沒有新的Intent請求達到,則**自動停止**Service;否則執行下一個Intent請求所對應的任務。 
  
  IntentService在處理事務時,還是採用的Handler方式,建立一個名叫ServiceHandler的內部Handler,並把它直接綁定到HandlerThread所對應的子線程。 ServiceHandler把處理一個intent所對應的事務都封裝到叫做onHandleIntent的虛函數;因此我們直接實現虛函數onHandleIntent,再在裡面根據Intent的不同進行不同的交易處理就可以了。
另外,IntentService預設實現了Onbind()方法,傳回值為null。

使用IntentService需要實現的兩個方法:
  

  • 建構函式 

      IntentService的建構函式一定是參數為空白的建構函式,然後再在其中調用super(“name”)這種形式的建構函式。因為Service的執行個體化是系統來完成的,而且系統是用參數為空白的建構函式來執行個體化Service的

  • 實現虛函數onHandleIntent

      在裡面根據Intent的不同進行不同的交易處理。 
      
    好處:處理非同步請求的時候可以減少寫代碼的工作量,比較輕鬆地實現項目的需求。

IntentService與Service的區別

  Service不是獨立的進程,也不是獨立的線程,它是依賴於應用程式的主線程的,不建議在Service中編寫耗時的邏輯和操作,否則會引起ANR。

  IntentService 它建立了一個獨立的背景工作執行緒來處理所有的通過onStartCommand()傳遞給服務的intents(把intent插入到工作隊列中)。通過工作隊列把intent逐個發送給onHandleIntent()。 
  
  不需要主動調用stopSelft()來結束服務。因為,在所有的intent被處理完後,系統會自動關閉服務。

   預設實現的onBind()返回null。

IntentService執行個體介紹

  首先是myIntentService.java

public class myIntentService extends IntentService {    //------------------必須實現-----------------------------    public myIntentService() {        super("myIntentService");        // 注意建構函式參數為空白,這個字串就是worker thread的名字    }    @Override    protected void onHandleIntent(Intent intent) {        //根據Intent的不同進行不同的交易處理         String taskName = intent.getExtras().getString("taskName");          switch (taskName) {        case "task1":            Log.i("myIntentService", "do task1");            break;        case "task2":            Log.i("myIntentService", "do task2");            break;        default:            break;        }           }  //--------------------用於列印生命週期--------------------       @Override  public void onCreate() {        Log.i("myIntentService", "onCreate");    super.onCreate();}    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.i("myIntentService", "onStartCommand");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        Log.i("myIntentService", "onDestroy");        super.onDestroy();    }}

然後記得在Manifest.xml中註冊服務

 <service android:name=".myIntentService">            <intent-filter >                  <action android:name="cn.scu.finch"/>              </intent-filter>             </service>

最後在Activity中開啟服務

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        // TODO Auto-generated method stub        super.onCreate(savedInstanceState);        //同一服務只會開啟一個worker thread,在onHandleIntent函數裡依次處理intent請求。        Intent i = new Intent("cn.scu.finch");          Bundle bundle = new Bundle();          bundle.putString("taskName", "task1");          i.putExtras(bundle);          startService(i);          Intent i2 = new Intent("cn.scu.finch");          Bundle bundle2 = new Bundle();          bundle2.putString("taskName", "task2");          i2.putExtras(bundle2);          startService(i2);         startService(i);  //多次啟動    }}

運行結果:

 

  IntentService在onCreate()函數中通過HandlerThread單獨開啟一個線程來依次處理所有Intent請求對象所對應的任務。 
  
  通過onStartCommand()傳遞給服務intent被依次插入到工作隊列中。工作隊列又把intent逐個發送給onHandleIntent()。

注意:
它只有一個背景工作執行緒,名字就是建構函式的那個字串,也就是“myIntentService”,我們知道多次開啟service,只會調用一次onCreate方法(建立一個背景工作執行緒),多次onStartCommand方法(用於傳入intent通過工作隊列再發給onHandleIntent函數做處理)。

[Android] IntentService使用詳解和執行個體介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.