[英]sending message from IntentService to Activity
我在同一個應用程序中有一個activity和一個intentService。 活動結束后服務必須繼續運行,所以我不想綁定。 我一直在谷歌搜索幾個小時,找不到一個如何做到這一點的好例子。 我能夠啟動服務並將附加內容傳遞給它,但現在該服務必須使用Messenger將數據發送回活動。
我讀到這個過程基本上涉及...調用Message.obtain()來獲取一個空的Message對象用所需的任何數據填充該對象在Messenger上調用send(),將消息作為參數提供
但我找不到任何有關如何執行此操作的代碼示例。
幾個帖子引用了SDK樣本APIDemos中的一個messengerService示例,我有,但我找不到任何東西。 謝謝,加里
你必須使用廣播。 完成意向服務后,您可以發送廣播消息。此外,您需要在活動中注冊您的intentfilter(您希望在哪里接收數據)
這可能會對您有所幫助: http : //www.mysamplecode.com/2011/10/android-intentservice-example-using.html
為了記錄,我將回答我自己的問題,因為它可能對其他人有用...(我使用常規服務,而不是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字符串中傳遞一個復雜的類,然后在活動中重新構建它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.