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
android android-activity broadcastreceiver
Truong vu
source share