如何等到蓝牙在android中打开
作者:互联网
我需要以编程方式在Android设备中打开蓝牙并等到它继续进行下一行代码.
我的代码如下
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
ctx.startActivity(enableBtIntent);
}
当这样做时,代码继续从nect行执行,而不必完全等待蓝牙.有什么方法可以解决这个问题吗?我可以添加外观来检查蓝牙是否已打开?
解决方法:
您可以注册BroadcastReceiver以侦听BluetoothAdapter上的状态更改.
首先创建一个将侦听状态更改的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)) {
final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (bluetoothState) {
case BluetoothAdapter.STATE_ON:
//Bluethooth is on, now you can perform your tasks
break;
}
}
}
};
然后在创建时使用您的Activity注册BroadcastReceiver,以便它可以开始接收事件.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set a filter to only receive bluetooth state changed events.
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
记住在销毁Activity时取消注册侦听器.
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
标签:android,android-bluetooth 来源: https://codeday.me/bug/20190716/1475360.html