sending message from IntentService to Activity

前端 未结 2 503
日久生厌
日久生厌 2021-01-01 08:12

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 h

2条回答
  •  鱼传尺愫
    2021-01-01 08:36

    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.

提交回复
热议问题