为了记录我我会回答我自己的问题,因为它可能对其他人有用... (我使用常规服务,而不是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字符串,然后在活动中重新构建它。
这是什么附加功能? –
方法的问题在于,如果活动重新创建,您将失去接收响应的能力。广播接收方式更好。有些人会建议你可以使处理程序静态。我会说不,因为那么当用户真正关闭活动时,您仍然会收到消息。 – user210504