android - onActivityResult() 之后的错误结果代码以启用蓝牙和发现
问题描述
我有一项活动要求启用蓝牙和发现模式。请求被正确执行并被onactivityresult()
. 问题出在发现请求中。
如果我点击拒绝,那么RESULT_CANCELED
是正确的,而如果我点击允许,结果代码是 120,因此它不是RESULT_OK
,我无法启动活动,它是 120 而不是正常RESULT_OK
吗?
我的活动
public class TransitionActivity extends AppCompatActivity {
private static final int ENABLE_REQUEST = 0;
private static final int DISCOVER_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transition);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null){ //bluetooth not supported
Toast.makeText(this, "Bluetooth not supported.", Toast.LENGTH_SHORT).show();
finish();
}
if(!bluetoothAdapter.isEnabled()){
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i,ENABLE_REQUEST);
}
if(!bluetoothAdapter.isDiscovering()){
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i,DISCOVER_REQUEST);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ENABLE_REQUEST){
if(resultCode == RESULT_OK){
}
if(resultCode == RESULT_CANCELED){
Toast.makeText(this, "You need to enable the bluetooth.", Toast.LENGTH_SHORT).show();
finish();
}
}
if(requestCode == DISCOVER_REQUEST){
System.out.println("RESULT CODE" + resultCode); //it is 120
if(resultCode == RESULT_OK){ //skipped
Intent secondActivity = new Intent(this, com.project.secondActivity.class);
this.startActivity(secondActivity);
}
if(resultCode == RESULT_CANCELED){
finish();
}
}
}
}
解决方案
EXTRA_DISCOVERABLE_DURATION
resultCode 的值与Intent 中传递的可发现持续时间相同。默认持续时间为 120。所以没关系。
如果你要开始这样的活动
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 240);
startActivityForResult(i,DISCOVER_REQUEST);
它将返回 240 作为结果代码。
推荐阅读
- java - 如何在spring webflux webclient中发送“一劳永逸”的请求?
- regex - 重定向 301:如何从 Nginx 转换为 Apache
- javascript - 如何在 extJS 组合框中设置 store 的特定索引值
- android - 必须引用包含私钥和相应公钥证书链的有效 KeyStore 密钥条目
- ios - 减少 Firebase 实时数据库负载
- mips - 当我加载自己的文件时 QtSpim 没有响应并在加载其他文件时抛出错误
- javascript - Bootstrap + Masonry 不正确的堆叠图像
- machine-learning - 使用差价时消失
- webrtc - STUN 如何对候选对执行 ICE 连接检查?
- sql - 使用 SQL Group By 或 Window Function 按时间顺序分析行?