3

I have a BroadcastReceiver inside an Activity to change some views (when it's visible) from a service. I can't make it static(and declare it in manifest) because I access views from activity inside onReceive(), so I register/unregister it inside my Activity's onResume() & onPause().

  public class MyActivity extends Activity {

    private BroadcastReceiver mReceiver;


    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction("action1");
        filter.addAction("action2");

        mReceiver = new CustomReceiver();
        registerReceiver(mReceiver, filter);
    }

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

        if (mReceiver != null)
            unregisterReceiver(mReceiver);
    }

    //some code

    class MyBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //NEVER GET HERE
        }
    }

}

I send explicit intents (a must in Android O) to this receiver from a service like so:

        Intent intent = new Intent(appContext, MyActivity.MyBroadcast.class);
        intent.setAction("action1");
        sendBroadcast(intent);

What is wrong with my implementation?

---SOLUTION---

As Mike M. commented we can use implicit intents to fire BroadcastReceiver even in Andorid O if they're registered using Context.registerReceiver()

Apps can use Context.registerReceiver() at runtime to register a receiver for any broadcast, whether implicit or explicit.

So it will be:

Intent intent = new Intent("action1");
sendBroadcast(intent);
Choletski
  • 7,074
  • 6
  • 43
  • 64
  • 2
    You're creating an explicit `Intent`, which won't work with a dynamically registered Receiver instance. Create it with just the action `String`: `Intent intent = new Intent("action1");`. Also, `LocalBroadcastManager` might be preferable here. – Mike M. Feb 22 '18 at 10:27
  • @MikeM. In Android O we must use only explicit intents. – Choletski Feb 22 '18 at 10:30
  • 2
    Not for dynamically registered Receivers. I think you're thinking of the manifest-registered Receiver restrictions. Third bullet point here: https://developer.android.com/about/versions/oreo/background.html#broadcasts. – Mike M. Feb 22 '18 at 10:33
  • @MikeM. yeah, that's it. Thank you! – Choletski Feb 22 '18 at 11:17

0 Answers0