Recipe 1.5 Assigning Priorities to Broadcast Receivers

Android Versions
Level 1 and above
Permissions
None
Source Code to Download at Wrox.com
UsingBroadcastReceiver.zip

When you send a broadcast using the sendBroadcast() method, all the broadcast receivers that match the specified action are called in random fashion. What if you want to assign a particular order to the broadcast receivers so that some broadcast receivers will be called before others? To do that, you need to assign a priority to the broadcast receivers.

Solution

To programmatically assign a priority to a broadcast receiver, use the setPriority() method:

public class MainActivity extends Activity {
    MyBroadcastReceiver myReceiver;
    IntentFilter intentFilter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myReceiver = new MyBroadcastReceiver();
        intentFilter = new IntentFilter("MY_SPECIFIC_ACTION");
    }

    @Override
    public void onResume() {
        super.onResume();
        intentFilter.setPriority(10);
        registerReceiver(myReceiver, intentFilter);
    }    

The setPriority() method takes a priority value between 0 (default) and 1,000. The larger the number, the higher priority it has, and hence broadcast receivers with a higher priority are called before those with lower priority. If more than one broadcast receiver has the same priority, they are called randomly. The preceding code snippet sets the priority to 10.

To set the priority of ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.