0

wifiをオフにするBroadcastReceiverを持っています..同じように、データ接続もオフにしたい..どうすればいいですか? これがコードです

public static class LowBatteryReceiver extends BroadcastReceiver{
        public void onReceive(Context context, Intent intent){
            wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
            wifiManager.setWifiEnabled(false);
            wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            Toast.makeText(context, "Turning off wifi..", Toast.LENGTH_LONG).show();
        }
    }

ありがとう

4

1 に答える 1

1

この権限を使用する必要があります

<uses-permission android:name="android.permission.BATTERY_STATS" />

あなたの AndroidManifest.xml で

<receiver android:name=".LowBatteryReceiver">
    <intent-filter>
         <action android:name="android.intent.action.BATTERY_LOW" />
    </intent-filter>
</receiver>

そしてあなたの LowBatteryReceiver

/** FOR CLOSE WIFI **/

public static class LowBatteryReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent){
        String intentAction = intent.getAction();
        if(intentAction.equals(Intent.ACTION_BATTERY_LOW))
            wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
            wifiManager.setWifiEnabled(false);
            Toast.makeText(context, "Turning off wifi..", Toast.LENGTH_LONG).show();
        }
    }
}

/** FOR CLOSE MOBILE DATA **/

public void onReceive(Context context, Intent intent){
        String intentAction = intent.getAction();
        if(intentAction.equals(Intent.ACTION_BATTERY_LOW))
            try {
            ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            Class<?> conmanClass = Class.forName(conman.getClass().getName());
            Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
            iConnectivityManagerField.setAccessible(true);
            Object iConnectivityManager = iConnectivityManagerField.get(conman);
            Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
            Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            setMobileDataEnabledMethod.setAccessible(true);
            setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
            } catch (Exception e) {
            e.printStackTrace();
            }
        }
    }
于 2013-08-04T23:51:55.470 に答える