Reputation: 593
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_CHANGE
to monitor such changes, but then I came across various posts and questions here that said that this wouldn't work, and the majority of the answers suggested to use reflection.
These led me to believe that there is no specific event being fired when the user changes the state of mobile data that I can use.
Is it possible that a custom event can be created to handle it? If not, what would you suggest the best practice is for monitoring the state of mobile data?
Thanks in advance
Upvotes: 2
Views: 567
Reputation: 95578
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.
Upvotes: 3