2012-10-11 109 views
1

我在同一個應用程序中有一個活動和一個intentService。活動結束後,服務必須繼續運行,所以我不想綁定。我一直在Google上搜索幾個小時,找不到一個如何做到這一點的好例子。我能夠啓動該服務並將額外的內容傳遞給它,但現在該服務必須使用Messenger將數據發回活動。將消息從IntentService發送到活動

我讀這個過程主要涉及... 調用Message.obtain()來得到一個空的消息對象 填充與任何數據需要 調用send()上的Messenger對象,提供的消息作爲參數

但我找不到任何代碼示例如何做到這一點。

幾個帖子引用SDK示例APIDemos中的一個messengerService示例,我有,但是我找不到任何東西。 謝謝,加里

回答

1

爲了記錄我我會回答我自己的問題,因爲它可能對其他人有用... (我使用常規服務,而不是IntentService,因爲它需要保持活動狀態)

對於從服務接收消息的活動,它必須將Handler實例化爲...

private Handler handler = new Handler() 
{ 
    public void handleMessage(Message message) 
    { 
     Object path = message.obj; 

     if (message.arg1 == 5 && path != null) 
     { 
      String myString = (String) message.obj; 
      Gson gson = new Gson(); 
      MapPlot mapleg = gson.fromJson(myString, MapPlot.class); 
      String astr = "debug"; 
      astr = astr + " "; 
     } 
    }; 
}; 

上面的代碼由我的調試東西組成。該服務將消息發送到活動,因爲...

   MapPlot mapleg = new MapPlot(); 
      mapleg.fromPoint = LastGeoPoint; 
      mapleg.toPoint = nextGeoPoint;    
      Gson gson = new Gson(); 
      String jsonString = gson.toJson(mapleg); //convert the mapleg class to a json string 
      debugString = jsonString; 

      //send the string to the activity 
      Messenger messenger = (Messenger) extras.get("MESSENGER"); 
      Message msg = Message.obtain(); //this gets an empty message object 

      msg.arg1 = 5; 
      msg.obj = jsonString; 
      try 
      { 
       messenger.send(msg); 
      } 
      catch (android.os.RemoteException e1) 
      { 
       Log.w(getClass().getName(), "Exception sending message", e1); 
      }    

我剛剛選擇了數字5作爲消息標識符。在這種情況下,我將一個複雜的類傳遞給json字符串,然後在活動中重新構建它。

+1

這是什麼附加功能? –

+0

方法的問題在於,如果活動重新創建,您將失去接收響應的能力。廣播接收方式更好。有些人會建議你可以使處理程序靜態。我會說不,因爲那麼當用戶真正關閉活動時,您仍然會收到消息。 – user210504

3

你必須使用廣播。 可以發出的廣播結束的意圖service.also您需要註冊您的IntentFilter您的活動中(要接收數據)

這可能是幫助你後消息:http://www.mysamplecode.com/2011/10/android-intentservice-example-using.html

+0

有許多消息來源表示,可以使用「Messenger」將數據從IntentService發送到活動。他們只是不顯示如何。所以我認爲你錯了廣播是唯一的方法。 –

+0

@DeanBlakely使用Messenger非常簡單,並且有很多示例。需要記住的是,在重新創建活動時它不起作用。 – user210504

相關問題