Does BroadcastReceiver CONNECTIVITY_CHANGE always start when you first launch the application?

I read it on Google Developer:

("android.net.conn.CONNECTIVITY_CHANGE") when the connection information has changed

I have this code:

public class MainActivity extends AppCompatActivity {

private NetworkChangeReceiver receiver; private boolean connIntentFilterIsRegistered; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver = new NetworkChangeReceiver(); } @Override protected void onPause() { super.onPause(); if (connIntentFilterIsRegistered) { unregisterReceiver(receiver); connIntentFilterIsRegistered = false; } } @Override protected void onResume() { super.onResume(); if (!connIntentFilterIsRegistered) { registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")); connIntentFilterIsRegistered = true; } } 

and //

public class NetworkUtil {

 public static int TYPE_WIFI = 1; public static int TYPE_MOBILE = 0; public static int TYPE_NOT_CONNECTED = 2; public static int getConnectivityStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { return TYPE_WIFI; } if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { return TYPE_MOBILE; } } return TYPE_NOT_CONNECTED; } public static String getConnectivityStatusString(Context context) { int conn = NetworkUtil.getConnectivityStatus(context); String status = null; if (conn == TYPE_MOBILE) { status = "Mobile cellular enabled"; } else if (conn == TYPE_WIFI) { status = "Wifi enabled"; } else if (conn == TYPE_NOT_CONNECTED) { status = "Not connected to internet"; } return status; } 

}

When I first launch the application, this intention always starts and a dialog is displayed with the current state of the network. But based on this document, does this only happen when the connection changes? If I want this display only when changing the network, how can I do this? Many thanks

+7
android android-activity broadcastreceiver
source share
1 answer

Broadcast android.net.conn.CONNECTIVITY_CHANGE is a sticky broadcast . This means that whenever you register a BroadcastReceiver for this ACTION, it will immediately start immediately, and onReceive() will be called with the last connection change . This allows you to get the current connection status without waiting for something to change.

If you want to ignore the current state and only want to process state changes, you can add this to your onReceive() :

 if (isInitialStickyBroadcast()) { // Ignore this call to onReceive, as this is the sticky broadcast } else { // Connectivity state has changed ... (your code here) } 
+18
source share

All Articles