2015-10-13 95 views
0

在文檔的谷歌雲消息,谷歌說,「不要叫這種方法在主線程,而是使用擴展IntentService服務」爲什麼我應該使用IntentService獲取Google雲消息傳遞令牌?

以前,當我使用gcm.register(現deprecated) ,我把我的代碼放在aSyncTask中。

private void getRegId(final ArrayList<String> studentIds){ 
     new AsyncTask<Void, Void, String>() { 
      @Override 
      protected String doInBackground(Void... params) { 
       String RegID; 
       try { 
        if (gcm == null) { 
         gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); 
        } 
        RegID = gcm.register(getVal("GCMProject")); 
       } catch (IOException ex) { 
        RegID = "," + ex.getMessage(); 
       } 
       return RegID; 
      } 

      @Override 
      protected void onPostExecute(final String RegID) { 
       String action = "SaveGCMRegID"; 
       if (RegID.charAt(0) == ',') { //Error Message 
        action = "GCM Reg Error"; 
       } else { 
        KVDB.StoreValue("GCMRegID", RegID); 
       } 
      } 
     }.execute(null, null, null); 
    } 

IntentService代替了什麼?我明白不會在主線程中等待響應,但是一個SyncTask應該做到這一點,對吧? (我相信這個問題與Is there any reason to continue using IntentService for handling GCM messages?不同,後者側重於使主線脫離工作)

回答

2

IntentService代替了什麼?

它使您的工作更有可能在Android終止您的過程之前完成。

我知道不等待主線程的響應,但aSyncTask應該做的伎倆,對不對?

AsyncTask或規則Thread將取消主應用程序線程的工作。但是,GCM消息以「廣播」形式到達Intent。一旦onReceive()返回,除非您恰好從UI的角度來看前景,否則您的進程有資格被終止以釋放系統RAM。如果您的流程中沒有正在運行的組件,您可能會很快終止,也許會在幾毫秒內終止。使用IntentService是您的應用程序告訴Android "I'm walkin' here!",因此Android不太可能終止您的流程。然而,只要onHandleIntent()返回,IntentService本身就會停止,因此一旦您的工作完成,Android可以安全地擺脫您的過程。

相關問題