发送短信未达到活性处理程序 [英] send message not reaching the handler in activity

查看:152
本文介绍了发送短信未达到活性处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有服务和活动。内部服务我发送消息。
我试图抓住它的主要活动中。但消息没有到达处理程序的活动。

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.

请参阅下面的code。

Please see the code below.

服务:

Handler handler = new Handler(Looper.getMainLooper());
    handler.sendEmptyMessage(112345);

MainActivity:

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

推荐答案

所有你正在使用 Handler.sendMessageXXX 发送消息将由相同的处理程序对象。所以,你必须在处理程序活动传递给服务 。它可以使用使者类来完成。

All messages you are sending using Handler.sendMessageXXX will be handled by the same Handler object. So you have to pass the Handler from Activity to Service. It can be done using Messenger class.

活动:

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);
    }
}

服务:

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();
        }
    }
}

这篇关于发送短信未达到活性处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆