我不明白为什么不调用onreceive方法。我在网上跟踪了所有的例子,并且在这个网站上浏览了很多类似的问题。有什么想法吗?我错过什么了吗?

public class MainActivity extends Activity {

    public BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d("Receiver", "Receiving message");

            String action = intent.getAction();
            String message;

            if (action.equals(BUTTON_ACTION)) {

                message = intent.getStringExtra("BUTTON");
                Log.d("R", message);

            }
        }

    };

    String BUTTON_ACTION = "button";

    @Override
    protected void onResume() {
        super.onResume();

        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,
                new IntentFilter(BUTTON_ACTION));

    }

    @Override
    protected void onPause() {

        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);

    }

在这一点上,我得到日志时,按钮被按下。但在我的接收器中从未达到onreceive方法。
    public void button1(View view) {

        Log.d("sender", "Broadcasting message");

        Intent broadcastIntent = new Intent();

        broadcastIntent.setAction(BUTTON_ACTION).addCategory("Button Press")
                .putExtra("BUTTON", "Button 1 has been pressed.").addFlags(Intent.));

        LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);

    }

}

最佳答案

看起来您正在使用类别集发送广播意图,但您的BroadcastReceiver未设置为处理类别。如果从广播意图中删除类别(或将其添加到IntentFilter),则可能会为您修复该类别。
从文档中:
请注意,与操作不同,没有类别的intentfilter将只与没有任何类别的intent匹配。
http://developer.android.com/reference/android/content/IntentFilter.html

关于android - BroadcastReceiver onReceive()无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17682990/

10-12 00:27