how to send message from service to activity

2019-04-26 23:59发布

I build an AsyncTask that create a service and now I want to sent from service to AsyncTask message. my code on the AsyncTask is:

  class ResponseHandler extends Handler {
  public void handleMessage(Message message) {
       // Toast.makeText(this, "message from service",Toast.LENGTH_SHORT).show();
 }

hope that it will handle the message from service correct my if I wrong.

and from service tried to do this

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

but my errors are cannot find symbol in lines:

 MyService.ADD_RESPONSE_HANDLER
  message.replyTo = messenger;
  try {
  myService.send(message);

What do I need to add? Please give me a code that will do the work. thanks a lot.

2条回答
家丑人穷心不美
2楼-- · 2019-04-27 00:18

One way is using ResultReceiver. Here is my complete blog post which I had recently posted with an Example.

How to update Activity from Service using ResultReceiver

查看更多
手持菜刀,她持情操
3楼-- · 2019-04-27 00:28

For sending a message or any data from service to Activity you will need to Register an Custom Broadcast receiver.see these tutorials for sending data from service to Activity:

Communication between service and activity – Part 1

Custom Intents and Broadcasting with Receivers

查看更多
登录 后发表回答