How to have Android Service communicate with Activity

前端 未结 13 1878
说谎
说谎 2020-11-22 02:54

I\'m writing my first Android application and trying to get my head around communication between services and activities. I have a Service that will run in the background an

相关标签:
13条回答
  • 2020-11-22 03:43

    Using a Messenger is another simple way to communicate between a Service and an Activity.

    In the Activity, create a Handler with a corresponding Messenger. This will handle messages from your Service.

    class ResponseHandler extends Handler {
        @Override public void handleMessage(Message message) {
                Toast.makeText(this, "message from service",
                        Toast.LENGTH_SHORT).show();
        }
    }
    Messenger messenger = new Messenger(new ResponseHandler());
    

    The Messenger can be passed to the service by attaching it to a Message:

    Message message = Message.obtain(null, MyService.ADD_RESPONSE_HANDLER);
    message.replyTo = messenger;
    try {
        myService.send(message);
    catch (RemoteException e) {
        e.printStackTrace();
    }
    

    A full example can be found in the API demos: MessengerService and MessengerServiceActivity. Refer to the full example for how MyService works.

    0 讨论(0)
提交回复
热议问题