How to trigger BroadcastReceiver when I turn on/off Mobile Cellular Data(Mobile Internet)

后端 未结 2 997
温柔的废话
温柔的废话 2021-01-05 17:26

I want to know how to trigger BroadcastReceiver if I turn on/off mobile cellular data. I already registered BroadcastReceiver and i

2条回答
  •  鱼传尺愫
    2021-01-05 18:05

    Try the following this will receives when the mobile data and wifi changes

     public class NetworkCheckReceiver extends BroadcastReceiver {
    
            /*
             * (non-Javadoc)
             * 
             * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
             * android.content.Intent)
             */
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e("NetworkCheckReceiver","ConnectionChangeReceiver.onReceive()");
                String statusString = getConnectivityStatusString(context);
                Toast.makeText(context, statusString, Toast.LENGTH_SHORT).show();
            }
    
            public int TYPE_WIFI = 1;
            public int TYPE_MOBILE = 2;
            public int TYPE_NOT_CONNECTED = 0;
    
            public int getConnectivityStatus(Context context) {
                ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                if (null != activeNetwork) {
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                        return TYPE_WIFI;
    
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                        return TYPE_MOBILE;
                }
                return TYPE_NOT_CONNECTED;
            }
    
            public String getConnectivityStatusString(Context context) {
                int conn = getConnectivityStatus(context);
                String status = null;
                if (conn == TYPE_WIFI) {
                    status = "Wifi enabled";
                } else if (conn == TYPE_MOBILE) {
                    status = "Mobile data enabled";
                } else if (conn == TYPE_NOT_CONNECTED) {
                    status = "Not connected to Internet";
                }
                return status;
            }
    
        }
    

提交回复
热议问题