sending message from IntentService to Activity

2019-02-07 15:15发布

问题:

I have an activity and an intentService in the same application. The service must keep running after the activity ends so I do not want to bind. I have been googling for hours and can't find a single good example of how to do this. I'm able to start the service and pass extras to it but now the service has to use Messenger to send data back to the activity.

I read that this process basically involves... Calling Message.obtain() to get an empty Message object Populating that object with whatever data is needed Calling send() on the Messenger, supplying the message as a parameter

But I can't find any code examples on how to do this.

several posts refer to a messengerService example in the SDK sample APIDemos, which I have, but I can't find anything there. thanks, Gary

回答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



回答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...

   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 + " ";
        }
    };
};

The above code consists of my debug stuff. The service sends the message to the activity as so...

                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);
            }               

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.