Android:在蓝牙启用对话框中按下拒绝按钮
如何处理蓝牙启用对话框上的“拒绝””按钮按下?我尝试使用Android:在蓝牙启用对话框中按下拒绝按钮,android,bluetooth,Android,Bluetooth,如何处理蓝牙启用对话框上的“拒绝””按钮按下?我尝试使用OnDismissListener和OnCancelListener甚至尝试了onActivityResult,但都不起作用。代码是: private BluetoothAdapter mBluetoothAdapter; private static final int REQUEST_ENABLE_BT = 1; @Override protected void onCreate(Bundle save
OnDismissListener
和OnCancelListener
甚至尝试了onActivityResult
,但都不起作用。代码是:
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isBleSupportedOnDevice()) {
initializeBtComponent();
} else {
finish();
}
}
private boolean isBleSupportedOnDevice() {
if (!getPackageManager().hasSystemFeature(
PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE is not supported in this device.",
Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void initializeBtComponent() {
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
@Override
protected void onResume() {
super.onResume();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
此代码提示用户使用对话框,直到他按下“允许”或“确定”按钮,但一旦他按下“拒绝”或“取消”按钮,我必须返回到上一个活动。我该怎么做?当我按下“Deny”按钮时,是否有调用的函数?您需要重写onActivityResult方法 您正在使用常量REQUEST_ENABLE_BT传递requestCode 因此,当任何用户按下“允许”或“拒绝”按钮后,onActivityResult方法将从您的活动中被调用
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
startBluetoothStuff();
}
}
在上面的代码中,检查回调是否针对相同的请求代码
所以你的理想流量是这样的
boolean isBluetoothManagerEnabled()
{
// Some code
}
public void startBluetoothStuff()
{
if(isBluetoothManagerEnabled())
{
// Do whatever you want to do if BT is enabled.
}
else
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
要解决这个问题,只需在onActivityResult()回调中检查结果\u cancelled。像这样的事情:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_ENABLE_BT && resultCode==RESULT_CANCELED){
... Do your stuff...
}
}
谢谢你的回复。我尝试过这种方法,问题是每次调用“onResume”方法时,都会在“onActivityResult”方法之前调用“onResume”方法。所以用户一次又一次地打开对话框。我也遇到了同样的问题。你有什么答案吗?