Pergunta

I don't understand why the onReceive method is never called. I've followed all the examples online, and I've looked through many similar questions on this site. Any ideas? Have I missed something?

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

    }

At this point, I get the log when the button is pressed. But the onReceive method is never reached in my receiver.

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

    }

}
Foi útil?

Solução

Looks like you're sending the broadcast intent with a category set, but your BroadcastReceiver isn't set up to handle a category. If you remove the category from the broadcast intent (or add it to the IntentFilter), that may fix it for you.

From the docs:

Note that unlike the action, an IntentFilter with no categories will only match an Intent that does not have any categories.

(http://developer.android.com/reference/android/content/IntentFilter.html)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top