Listener for turning on / off mobile data (not connected or disconnected)

I am testing 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 only listen on the state (connected or disconnected).

When Wi-Fi is disabled, it can listen (enable mobile data → connected → broadcast → listener)

When wifi copnnnected, he can not listen (turn on mobile data → communication has not changed!)

I need mobile data settings for mobile devices or not

Can I listen to mobile data with the event turned on or off?

+3
source share
2 answers

, , , , , . " Android" ; onCreate() onResume(). , , . , API, :

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;
    }
}
+1

, ContentObserver , " ".

:

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);

! .

getContentResolver().unregisterContentObserver(mObserver);
+1

All Articles