Search code examples
androidsmsbroadcastreceiver

What happens when/if onReceive override called from several apps?


For instance some example here, a phone running 2 or more apps, calling onReceive(). Has android some kind of task order to run all thouse @Overrides by ordered sequence? Probably yes, then in which order, app importance?

App1 & App2:

App1:

  private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);
  }
};

App2:

  private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    String message = intent.getStringExtra("message");
    deleteMessageFromInbox(message); // or just something that can conflict other Instance
  }
};

Solution

  • You can define the order that intents are handled using the android:priority attribute of BroadcastReceivers. When an intent can be handled by multiple receivers, Android generates an ordered list (based on the priority of each receiver) and delivers the intent sequentially.

    So in your case, when you register the receivers (via registerReceiver(BroadcastReceiver receiver, IntentFilter filter), all you have to do is assign a higher priority (via a call to setPriority(int priority)) to the intent filter in App1 than to the filter in App2 to make sure that App1 receives the intent before App2.

    There is also an old article in the Android developers blog that gives you examples about how to implement this mechanism efficiently.