-
StackOverflow 文件
-
Android 教程
-
廣播接收器
-
藍芽廣播接收器
在清單檔案中新增許可權
<uses-permission android:name="android.permission.BLUETOOTH" />
在你的片段(或活動)
private BroadcastReceiver mBluetoothStatusChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final Bundle extras = intent.getExtras();
final int bluetoothState = extras.getInt(Constants.BUNDLE_BLUETOOTH_STATE);
switch(bluetoothState) {
case BluetoothAdapter.STATE_OFF:
// Bluetooth OFF
break;
case BluetoothAdapter.STATE_TURNING_OFF:
// Turning OFF
break;
case BluetoothAdapter.STATE_ON:
// Bluetooth ON
break;
case BluetoothAdapter.STATE_TURNING_ON:
// Turning ON
break;
}
};
註冊廣播
private void registerBroadcastManager(){
final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
manager.registerReceiver(mBluetoothStatusChangedReceiver, new IntentFilter(Constants.BROADCAST_BLUETOOTH_STATE));
}
取消註冊廣播
private void unregisterBroadcastManager(){
final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getActivity());
// Beacon 機能用
manager.unregisterReceiver(mBluetoothStatusChangedReceiver);
}