2

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

例如:我发送一条消息以禁用 wifi 并强制它。然后我关闭wifi并保存状态,这是强制的。我还有一个广播接收器,它监听 Wifi 状态的变化,如果收到,它首先检查 wifi 是否已启用以及是否可以。如果没有,它会立即再次禁用 wifi。这就像一个魅力:public class WifiStateReceiver extends 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();
    }
}

有什么想法可以永久禁用蓝牙吗?

4

1 回答 1

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();
    }
}
于 2013-06-20T15:05:11.507 回答