我需要以编程方式在Android设备中打开蓝牙并等到它继续进行下一行代码。
我的代码如下
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
ctx.startActivity(enableBtIntent);
}
当这样做时,代码继续从nect行执行,而不必完全等待蓝牙。有什么方法可以解决这个问题吗?我可以添加外观来检查蓝牙是否已打开?
答案 0 :(得分:8)
您可以注册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;
}
}
}
};
然后注册 BroadcastReceiver
创建Activity
,以便它可以开始接收事件。
@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);
}
答案 1 :(得分:2)
使用此代码 您的清单文件的权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
和代码
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent , 0);
} else
{
Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(),"Turned on",Toast.LENGTH_LONG).show();
}
if(resultCode == RESULT_CANCELED){
}
答案 2 :(得分:2)
您可以使用startActivityForResult()
并在您的清单文件中检查onActivityResult()
中的 resultCode 是否为 RESULT_OK 并具有蓝牙权限。
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 0);
}
onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
// bluetooth enabled
}else{
// show error
}
}
答案 3 :(得分:0)
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//do your things
}