0

I have BroadcastReceiver (NetworkListener).

public class NetworkReceiver extends BroadcastReceiver {
Context context;
public static NetworkReceiver instance = new NetworkReceiver();
public static InnerObservable observable = instance. new InnerObservable();
...

This receiver sends notifications:

@Override
public void onReceive(Context ctx, Intent intent) {

    Log.d("tag", "onReceive");

    NotificationManager notif = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(android.R.drawable.ic_dialog_alert,"bla-bla-bla",System.currentTimeMillis());

Manifest file:

 <receiver 
        android:name="com.mypckg.network.NetworkReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver> 

It works fine. But after phone reboot, it continues to work. how to avoid it?

Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
Yuriy Aizenberg
  • 373
  • 9
  • 28

2 Answers2

1

If you want your broadcast receiver to start working when application gets launched then you should register/unregister it programatically from your main activity:

private BroadcastReceiver networkReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    networkReceiver = new NetworkReceiver();
    registerReceiver(networkReceiver, ConnectivityManager.CONNECTIVITY_ACTION);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(networkReceiver)
}
sdabet
  • 18,360
  • 11
  • 89
  • 158
  • Yes, otherwise it'll still be launched at startup – sdabet Nov 09 '12 at 09:46
  • Note that with this solution the broadcast receiver will stop when switching to another activity. If you want the receiver's lifecycle to be the same as the app's then you should do this in the Application class – sdabet Nov 09 '12 at 10:29
1

You can mess around with the PackageManager to disable a BroadcastReceiver registered in your manifest, check this thread for code.

Another solution would be to register this receiver dynamically, possibly in a service. The receiver would be active and registered as long as the service is alive, so you could easily toggle the receiver by starting/stopping the service. This might not fit you use case however, you didn't provide much detail on that.

Community
  • 1
  • 1
Zsombor Erdődy-Nagy
  • 16,864
  • 16
  • 76
  • 101