我們可以透過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
沒有留言:
張貼留言