How to send a message from a service to action

I am creating AsyncTask that create a service, and now I want to send a message from the service to an AsyncTask message. my code in AsyncTask:

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

I hope that he will process the message from the service, correct mine if I am mistaken.

and from the service tried to do it

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

but my errors cannot find the character in the 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 job. Many thanks.

+6
source share
2 answers

In one case, a ResultReceiver used. Here is my complete blog post I recently posted with an example.

How to update Activity from Service using ResultReceiver

+6
source

To send a message or any data from a service to Activity, you need to register a Custom Broadcast Receiver . Check out these tutorials to send data from a service to an Activity:

The Relationship Between Service and Activity - Part 1

User Intentions and Broadcasting Using Receivers

+4
source

Source: https://habr.com/ru/post/919312/


All Articles