[英]send message not reaching the handler in activity
I am having the service and activity. 我正在提供服务和活动。 inside service i am sending the message.
内部服务,我正在发送消息。 I am trying to catch it inside the main activity.
我正在尝试在主要活动中抓住它。 But message is not reaching the handler in activity.
但是消息没有到达活动中的处理程序。
Please see the code below. 请参见下面的代码。
Service: 服务:
Handler handler = new Handler(Looper.getMainLooper());
handler.sendEmptyMessage(112345);
MainActivity: 主要活动:
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this, "handled message successfully", Toast.LENGTH_SHORT).show();
if ( msg.what == 1234 ) {
Toast.makeText(MainActivity.this, "handled message successfully", Toast.LENGTH_SHORT).show();
}
}
};
Can anyone tell me why it is not reaching the handler in the activity. 谁能告诉我为什么它没有到达活动中的处理程序。 As far as i know
我所知道的
All messages you are sending using Handler.sendMessageXXX
will be handled by the same Handler
object. 您使用
Handler.sendMessageXXX
发送的所有消息都将由相同的Handler
对象Handler
。 So you have to pass the Handler
from Activity
to Service
. 因此,您必须将
Handler
从Activity
传递到Service
。 It can be done using Messenger
class. 可以使用
Messenger
类来完成。
Activity: 活动:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(MyActivity.this, "handleMessage " + msg.what, Toast.LENGTH_SHORT).show();
}
};
final Intent intent = new Intent(this, MyService.class);
final Messenger messenger = new Messenger(handler);
intent.putExtra("messenger", messenger);
startService(intent);
}
}
Service: 服务:
public class MyService extends IntentService {
public MyService() {
super("");
}
@Override
protected void onHandleIntent(Intent intent) {
final Messenger messenger = (Messenger) intent.getParcelableExtra("messenger");
final Message message = Message.obtain(null, 1234);
try {
messenger.send(message);
} catch (RemoteException exception) {
exception.printStackTrace();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.