Sending Message From Intentservice To Activity
Solution 1:
You have to use Broadcast for this. You can sent broadcast message after finish the intent service.also you need to register your intentfilter inside your activity(where you want to receive the data)
This may be help you : http://www.mysamplecode.com/2011/10/android-intentservice-example-using.html
Solution 2:
For the record I'll answer my own question as it might be useful to others... (I'm using a regular Service, not an IntentService as it needs to stay active)
For the activity to receive messages from the service, it has to instantiate a Handler as so...
privateHandlerhandler=newHandler()
{
publicvoidhandleMessage(Message message)
{
Objectpath= message.obj;
if (message.arg1 == 5 && path != null)
{
StringmyString= (String) message.obj;
Gsongson=newGson();
MapPlotmapleg= gson.fromJson(myString, MapPlot.class);
Stringastr="debug";
astr = astr + " ";
}
};
};
The above code consists of my debug stuff. The service sends the message to the activity as so...
MapPlotmapleg=newMapPlot();
mapleg.fromPoint = LastGeoPoint;
mapleg.toPoint = nextGeoPoint;
Gsongson=newGson();
StringjsonString= gson.toJson(mapleg); //convert the mapleg class to a json string
debugString = jsonString;
//send the string to the activityMessengermessenger= (Messenger) extras.get("MESSENGER");
Messagemsg= 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);
}
I just picked the number 5, for now, as the message identifier. In this case I'm passing a complex class in a json string and then reconstrucing it in the activity.
Post a Comment for "Sending Message From Intentservice To Activity"