Android永久禁用/启用Wifi和蓝牙

时间:2013-06-20 14:57:46

标签: android bluetooth broadcastreceiver wifi

我有一个应用程序应该管理设备的wifi和蓝牙状态。为此它收到一条状态的消息,并且不应该强制这个状态。然后它应用状态并保存两个值。

例如:我发送消息以禁用wifi并强制它。然后我关闭wifi并保存状态,这是强制的。此外,我有一个收听Wifi状态变化的BroadcastReceiver,如果收到,它首先检查是否启用了wifi,如果可以的话。如果没有,它会立即再次禁用wifi。这就像一个魅力: 公共类WifiStateReceiver扩展BroadcastReceiver {

public void onReceive(final Context context, final Intent intent) {
    // get new wifi state
    final int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_ENABLING);
    final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    // if enabling, check if thats okay
    if (wifiState == WifiManager.WIFI_STATE_ENABLING && WIFI_FORCE_DISABLE) {
        wifiManager.setWifiEnabled(false);
    } else

    // if disabling, check if thats okay
    if (wifiState == WifiManager.WIFI_STATE_DISABLING && WIFI_FORCE_ENABLE) {
        wifiManager.setWifiEnabled(true);
    }
}

但是,如果我尝试使用蓝牙完全相同的东西,它不会将其切换回来......

public void onReceive(final Context context, final Intent intent) {
    // get new wifi state
    final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // if enabling, check if thats okay
    if (bluetoothState == BluetoothAdapter.STATE_TURNING_ON && BT_FORCE_DISABLE) {
        mBluetoothAdapter.disable();
    } else

    // if disabling, check if thats okay
    if (bluetoothState == BluetoothAdapter.STATE_TURNING_OFF && BT_FORCE_ENABLE) {
        mBluetoothAdapter.enable();
    }
}

我是如何永久禁用蓝牙的?

1 个答案:

答案 0 :(得分:1)

仅仅5分钟就让我走上了正确的轨道......

我上面的方法的问题是,我等待听关闭/打开。似乎如果我在蓝牙刚启动时禁用蓝牙,它将继续打开并保持开启状态。所以我必须等到它实际打开然后禁用它。换句话说,我必须删除8个字符,它工作正常:

public void onReceive(final Context context, final Intent intent) {
    // get new wifi state
    final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // if enabling, check if thats okay
    if (bluetoothState == BluetoothAdapter.STATE_ON && BT_FORCE_DISABLE) {
        mBluetoothAdapter.disable();
    } else

    // if disabling, check if thats okay
    if (bluetoothState == BluetoothAdapter.STATE_OFF && BT_FORCE_ENABLE) {
        mBluetoothAdapter.enable();
    }
}
相关问题