【问题标题】:how to capture mobile data enable/disable event in android如何在android中捕获移动数据启用/禁用事件
【发布时间】:2016-09-09 04:39:33
【问题描述】:

我正在开发一个跟踪应用程序,我需要在其中捕获移动数据启用/禁用事件。我可以通过以下代码成功获得互联网启用/禁用广播:

 private BroadcastReceiver networkInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            ConnectivityManager connect = (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
            NetworkInfo network = connect.getActiveNetworkInfo();
            if (network == null || !network.isConnected()) {
                sharedPreferencesEditor.putBoolean(Constants.INTERNET_STATUS,false);
            } else {
                sharedPreferencesEditor.putBoolean(Constants.INTERNET_STATUS,true);
            }
            sharedPreferencesEditor.commit();

        }

但是通过使用这个代码 sn-p 我只得到了互联网状态。无论数据禁用还是没有网络区域,它都会在两种情况下触发。但我需要一个只有在手动禁用移动数据时才会触发的广播。

【问题讨论】:

标签: android android-broadcast android-gps


【解决方案1】:

试试下面的代码:

        boolean mobileDataEnabled = false; 
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            Class cmClass = Class.forName(cm.getClass().getName());
            Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true); 
            mobileDataEnabled = (Boolean)method.invoke(cm);
        } 
        catch (Exception e) {         
            // TODO do whatever error handling you want here
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2013-05-21
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多