-
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);
}