Reputation: 5448
I test some actions (see below).
ConnectivityManager.CONNECTIVITY_ACTION
WifiManager.NETWORK_STATE_CHANGED_ACTION
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE (it is not actually action)
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE (it is not actually action)
But they listen only state (connected or disconnected).
When wifi disconnected, It can listen (enable mobile data -> connnected -> broadcast - > listener)
When wifi copnnnected, It cannot listen (enable mobile data -> connetivity does not changed!)
I need wheather mobile data settings is enable or not
Can I listen mobile data enabled or disabled event?
Upvotes: 4
Views: 2643
Reputation: 679
While there's no broadcast by the system for this, we can actually use a ContentObserver to get notified of when the user toggles the Mobile Data setting.
e.g:
ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange, Uri uri) {
// Retrieve mobile data value here and perform necessary actions
}
};
...
Uri mobileDataSettingUri = Settings.Secure.getUriFor("mobile_data");
getApplicationContext()
.getContentResolver()
.registerContentObserver(mobileDataSettingUri, true,
observer);
Don't forget to unregister the observer appropriately! E.g.
getContentResolver().unregisterContentObserver(mObserver);
Upvotes: 2
Reputation: 134714
So, after digging into it a bit, it doesn't seem like any broadcasts are sent out when that value is changed. Even the mobile network settings fragment in the Android Settings app doesn't listen for changes; it only checks in onCreate()
and onResume()
. So it seems you can't listen for changes, but you can get the current state. Unfortunately, it's a private API so you'll have to use reflection:
public static boolean isMobileDataEnabled(Context ctx) {
try {
Class<?> clazz = ConnectivityManager.class;
Method isEnabled = clazz.getDeclaredMethod("getMobileDataEnabled", null);
isEnabled.setAccessible(true);
ConnectivityManager mgr = (ConnectivityManager)
ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
return (Boolean) isEnabled.invoke(mgr, null);
} catch (Exception ex) {
// Handle the possible case where this method could not be invoked
return false;
}
}
Upvotes: 1