Android 如何从服务向活动发送消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11259453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to send message from service to activity
提问by Vitaly Menchikovsky
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:
我构建了一个创建服务的 AsyncTask,现在我想从服务发送到 AsyncTask 消息。我在 AsyncTask 上的代码是:
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.
我需要添加什么?请给我一个可以完成工作的代码。多谢。
回答by Lalit Poptani
One way is using ResultReceiver
. Here is my complete blog post which I had recently posted with an Example.
一种方法是使用ResultReceiver
. 这是我最近发布的带有示例的完整博客文章。
回答by ρяσ?ρ?я K
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:
要从服务向 Activity 发送消息或任何数据,您需要注册自定义广播接收器。请参阅这些从服务向 Activity 发送数据的教程:
Communication between service and activity – Part 1