How To Check If Mobile Network Is Enabled/disabled
Solution 1:
I finally found a solution. Apparently not all phones have this option:
Home > Menu > Settings > Wireless & networks > Mobile network (checkbox)
However, for those who do, this method will work:
/**
* @return null if unconfirmed
*/publicBooleanisMobileDataEnabled(){
Object connectivityService = getSystemService(CONNECTIVITY_SERVICE);
ConnectivityManager cm = (ConnectivityManager) connectivityService;
try {
Class<?> c = Class.forName(cm.getClass().getName());
Method m = c.getDeclaredMethod("getMobileDataEnabled");
m.setAccessible(true);
return (Boolean)m.invoke(cm);
} catch (Exception e) {
e.printStackTrace();
returnnull;
}
}
Solution 2:
apparently there is an alternative, more clean solution then the Reflection approach:
finalConnectivityManagercm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
finalNetworkInfonetworkInfo= cm.getActiveNetworkInfo();
inttype= networkInfo.getType();
StringtypeName= networkInfo.getTypeName();
booleanconnected= networkInfo.isConnected()
networkInfo.getType() will return '0' when connected to mobile network or '1' when connected trough WIFI. networkInfo.getTypeName() will return the strings "mobile" or "WIFI". and networkInfo.isConnected() will tell you whether or not you have an active connection.
Solution 3:
UPDATE FOR ANDROID 5.0+ (API 21+)
Calling getMobileDataEnabled
via the reflection leads to NoSuchMethodException
on Android 5.0+ on some devices. So in addition to accepted answer you may wanna do second check if NoSuchMethodException
is thrown.
...
catch(NoSuchMethodException e)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
isDataEnabled = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
}
}
Solution 4:
PackageManagerpm= context.getPackageManager();
booleanhasTelephony= pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY);
Post a Comment for "How To Check If Mobile Network Is Enabled/disabled"