I want to know how to trigger BroadcastReceiver if I turn on/off mobile cellular data. I already registered BroadcastReceiver and i
You need to specify appropriate permissions and do the needful as mentioned below:
Permissions in manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Receiver declaration in manifest:
<receiver
android:name=".NetworkCheckReceiver"
>
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
NetworkCheckReceiver class file:
public class NetworkCheckReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.d("NetworkCheckReceiver", "NetworkCheckReceiver invoked...");
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (!noConnectivity) {
Log.d("NetworkCheckReceiver", "connected");
}
else
{
Log.d("NetworkCheckReceiver", "disconnected");
}
}
}
}
Note:
Make sure you have working mobile cellular data connection. This receiver won't trigger if you don't have internet pack and you just switching on/off. You surely need to have working connection to test.
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;
}
}