I\'m building an app, on which I want to capture when a user enables or disables mobile data usage on his device.
I read about using android.net.conn.CONNECTIVITY_CH
Hey you can find what you looking for by downloading from here the sample app NetworkUsage.
There aren't any events broadcast when the user changes the mobile data enabled setting. About the only way to do this (other than listening for CONNECTIVITY_CHANGE
events, as you've described) would be to check the state of the mobile data enabled setting on a periodic basis. If you do this too frequently, though, you will just drain the battery.
If you are creating your own custom ROM, you could certainly add code to the Settings app that would broadcast an event when mobile data is enabled/disabled.
EDIT Added a method to get notifications when settings are modified
Actually, I've found a way to do this. You can get a notification whenever the mobile data setting is changed. Unfortunately, the only way to do this is to register for notifications whenever any setting is changed. However, this doesn't happen that often and at least you don't have to poll every so often and drain your battery. What you want to do is to register a ContentObserver
on the Secure
settings, like this:
contentObserver = new SettingsObserver();
getApplicationContext().getContentResolver().registerContentObserver(
Settings.Secure.CONTENT_URI, true, contentObserver);
You should implement the SettingsObserver
like this:
public class SettingsObserver extends ContentObserver {
public SettingsObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
// Here you want to check the state of mobileDataEnabled using reflection to
// see if it has changed - see https://stackoverflow.com/a/12864897/769265
}
}
See https://stackoverflow.com/a/12864897/769265 for more information on how to determine the current state of the mobile data setting.