mot*_*oku 2 android bluetooth android-intent
我有一个需要一些蓝牙设置的Android应用程序;见下文:
if (!Constants.mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
while (!Constants.mBluetoothAdapter.isEnabled()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.exit(1);
}
}
if (Constants.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivity(discoverableIntent);
}
while (Constants.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.exit(1);
}
} // do some stuff with bluetooth
Run Code Online (Sandbox Code Playgroud)
对我来说,这似乎是一种hack,仅当用户选择“是”时,它才起作用。我很确定我需要等待这些意图的结果。怎么做?
您可以调用startActivityForResult()并实现onActivityResult()当用户从被调用活动返回时将被调用的方法。
要检查是否启用了蓝牙,请将代码更改为:
if (!Constants.mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
progressToNextCheck();
}
Run Code Online (Sandbox Code Playgroud)
然后,在progressNextCheck()工具中以类似方式检查蓝牙可发现性。
private void progressToNextCheck(){
if (Constants.mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT);
} else {
goToTheTask();
}
}
Run Code Online (Sandbox Code Playgroud)
而你的onActivityResult()方法:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
progressToNextCheck();
}
} else if (requestCode == REQUEST_DISCOVERABLE_BT) {
if (resultCode == RESULT_OK) {
goToTheTask();
}
}
}
Run Code Online (Sandbox Code Playgroud)