顯示具有 bluetooth 標籤的文章。 顯示所有文章
顯示具有 bluetooth 標籤的文章。 顯示所有文章

2013年9月5日

Android─利用BroadcastReceiver接收wifi與bluetooth狀態變化

當app需要知道wifi bluetooth狀態被切換時,
我們可以透過BroadcastReceiver來監聽 wifi 與 bluetooth 的狀態
首先我們需要在onresume的狀態下去註冊wifi 與 bluetooth 狀態改變所發出的Broadcast事件
程式碼如下

@Override
public void onResume() {
    super.onResume();
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); \\bluetooth狀態改變事件
    filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); \\wifi狀態改變事件
    registerReceiver(mReceiver, filter);
}

當我們註冊完所要監聽的Broadcast事件後,我們就可以利用BroadcastReceiver來監聽註冊的事件。
程式碼如下
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED))  //收到bluetooth狀態改變
        {
          //執行想做的程式碼
        }
        else if((action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION))  //收到wifi狀態改變
        {
          //執行想做的程式碼
        }
    }
};// end of OnReceive

Android─開啟wifi與bluetooth及偵測wifi與bluetooth狀態

Wifi開啟及狀態偵測

首先需要在Manifest.xml 加入以下三個permission





然後在程式內加入

private WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE)
if (wifiManager.isWifiEnabled()) //判斷目前wifi狀態 開啟會回傳true
    wifiManager.setWifiEnabled(false);   //把wifi關閉
else
    wifiManager.setWifiEnabled(true); //把wifi開啟

bluetooth開啟及狀態偵測

首先需要在Manifest.xml 加入以下兩個permission

然後在程式內加入

private BluetoothAdapter mBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled())\\判斷目前bluetooth狀態 開啟會回傳true
    mBluetoothAdapter.disable();  //將bluetooth關閉
else
    mBluetoothAdapter.enable();  //將buletooth開啟

參考網頁
http://goo.gl/A6anzN 
http://goo.gl/11Qi7Y 
http://goo.gl/Slssm 
http://goo.gl/xgLsp