1

I created a broadcast receiver for monitoring my connection data and notify the user. I use an activity with a custom view to show a logo with no connection.

If I register the receiver in the manifest and the app is closed, when change the status of connection, the app is re-opened and I don't want this behavior.

What is the right pattern to follow? Example? Link?

This is my receiver:

public class ConnectionHelper extends BroadcastReceiver {

static final String ACTION_CLOSE_ACTIVITY = "android.net.conn.CLOSE_ACTIVITY";


@Override
public void onReceive(Context context, Intent intent) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (!isConnected) {
            Intent mainIntent = new Intent(context, NoConnectionActivity.class);
            mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mainIntent);
        } else {
            Intent in = new Intent(ACTION_CLOSE_ACTIVITY);
            context.sendBroadcast(in);
        }
}
....

Thanks in advance for the response.

===UPDATE===

In the end, for my application I used NetworkEvents lib as suggested by @Anderson C Silva.

I created a simple application to help all the others who have doubts about how to solve this problem. github repository

davideagostini
  • 111
  • 3
  • 14
  • Check the best two according to requirements: 1. http://stackoverflow.com/questions/33562037/detecting-internet-connectivity-android/33562461#33562461 ,2. http://stackoverflow.com/questions/33505738/i-want-to-run-a-background-process-for-internet-checking-in-android/33505783#33505783 – Androider Nov 13 '15 at 17:53

1 Answers1

1

I guess that a good solution for this issue is enable and disable the Broadcast programmatically. when app it is closed, so disable the Broadcast, something like this:

PackageManager pm = getPackageManager();
ComponentName compName =
      new ComponentName(getApplicationContext(),
            YourReceiver.class);
pm.setComponentEnabledSetting(
      compName,
      PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
      PackageManager.DONT_KILL_APP);

See more here:

Enabling and Disabling BroadcastReceivers at Runtime

Another possible solution to this case is use some lib EventBus, this way you register in your Activity to receiver the status of the network state from broadcast by Message.

This is a great lib to do this:

NetworkEvents

I hope this helps!

Anderson K
  • 5,445
  • 5
  • 35
  • 50
  • I call your code in `onDestroy` method for disable the broadcast receiver, but even when the app is closed and change the status of the connection the activity is reopened. – davideagostini Nov 13 '15 at 21:23