Reputation: 8528
I'm building an app that periodically retrieves data from a website using a recurring alarm and an IntentService. Before running the update, I check for network connectivity with a ConnectivityManager.
If the ConnectivityManager reports that there is no active network, I wish to try the update again when a network becomes active. Using a BroadcastReceiver listening for ConnectivityManager.CONNECTIVITY_ACTION seems like the best way to do this, but what would be the proper way to register/unregister this receiver?
I'm thinking that when the network check fails in the IntentService, that I could register the BroadcastReceiver with the ApplicationContext so it doesn't get unregistered when the service stops. Could I then unregister the receiver in its own onReceive method when it fires? Am I way off base?
Some psuedo code examples:
MyIntentService:
if ( !isNetworkConnected() )
getApplicationContext().registerReceiver( new MyBroadcastReceiver(), new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION );
MyBroadcastReceiver:
public void onReceive( Context context, Intent intent ) {
context.getApplicationContext().unregisterReceiver( this );
Upvotes: 2
Views: 259
Reputation: 8528
I believe I have found the solution to my problem. Registering the receiver with the ApplicationContext won't work because it will be unregistered when the app process is terminated.
I believe the proper way to handle this is to declare the receiver in the Manifest, and then use PackageManager.setComponentEnabledSetting to enable/disable the receiver as necessary (in place of my two examples above).
So, I would register it in the Manifest as disabled (enabled=false), then do the following:
MyIntentService:
protected void onHandleIntent( Intent intent ) {
if ( !isNetworkConnected() )
getPackageManager().setComponentEnabledSetting(
new ComponentName( this, MyBroadcastReceiver.class ),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP );
MyBroadcastReceiver:
public void onReceive( Context context, Intent intent ) {
getPackageManager().setComponentEnabledSetting(
new ComponentName( this, MyBroadcastReceiver.class ),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP );
Upvotes: 1