Click here to Skip to main content
13,199,026 members (44,248 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

2.5K views
2 bookmarked
Posted 9 Oct 2017

Android - Programmatically Register System Broadcast Receiver at Runtime

, 9 Oct 2017
Rate this:
Please Sign up or sign in to vote.
How to programmatically register system broadcast receiver at runtime in Android

The Problem - Registering Connectivity Change When Targeting API 24+

Not all Android Broadcasts are created equally and you can't create them in the manifest in all cases. There are some you must configure at runtime because of changes Google made to apps targeting N (API 24).

From the documentation: Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare their broadcast receiver in the manifest.

The Solution

The docs are not as clear how to handle this, so here is the code to allow your app to still receive connectivity change broadcasts after targeting N or later:

public void onCreate() {
    ...
    //Change 'YourConnectionChangedBroadcastReceiver' 
    //to the class defined to handle the broadcast in your app
    registerReceiver(new YourConnectionChangedBroadcastReceiver(), 
    new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ...
}

I'd also recommend removing the declaration from AndroidManifest.xml as if you leave it in there, it will actually create multiple instances of your broadcast receiver.

<receiver android:name="YourConnectionChangedBroadcastReceiver">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

Registering it programmatically unlocks the receiver for use by your app (including those for CONNECTIVITY_ACTION in your manifest), and that's all there is to it. You can save the registered receiver instance and unregister it when no longer needed, however, this is not necessary if it lasts the entire lifetime of your application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Right Handed Monkey
Chief Technology Officer WorxForUs
United States United States
I am a programmer who posts rambling on about java, Android, PHP, or whatever I am motivated to type on my charcoal colored Kinesis Freestyle2 keyboard. Please send +1's, shared links, warm thoughts of encouragement, or emasculating flames of internet fury to my blog. Thanks for reading!

righthandedmonkey.com

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171020.1 | Last Updated 10 Oct 2017
Article Copyright 2017 by Right Handed Monkey
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid