2013-06-20 147 views
2

我有一個應用程序,應該管理設備的WiFi和藍牙狀態。爲此,它收到一條帶有狀態的消息,並且該狀態是否應該被強制。然後它應用狀態並保存兩個值。Android禁用/啓用Wifi和藍牙永久

例如:我發送信息禁用wifi並強制它。然後,我關掉wifi並保存狀態,並強制執行此操作。另外我有一個BroadcastReceiver監聽Wifi狀態的變化,如果收到,它首先檢查是否啓用了WiFi,如果這是好的。如果不是,它會立即禁用wifi。這就像一個魅力: 公共類WifiStateReceiver擴展廣播接收器{

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

僅有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(); 
    } 
}