首页 文章

启用/禁用移动数据的侦听器(未连接或不连接)

提问于
浏览
3

我测试了一些动作(见下文) .

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)

但他们只听状态(连接或断开连接) .

当wifi断开连接时,它可以监听(启用移动数据 - >连接 - >广播 - >监听器)

When wifi copnnnected, It cannot listen (启用移动数据 - >连接性不会更改!)

我需要启用或不启用移动数据设置

我可以监听移动数据启用还是禁用事件?

2 回答

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

    所以,在深入挖掘它之后,它并没有听取变化;它只检查 onCreate()onResume() . 因此,您似乎无法听取更改,但您可以获得当前状态 . 不幸的是,'s a private API so you'将不得不使用反射:

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

相关问题