如何处理蓝牙启用对话框中的“拒绝”按钮?我尝试使用 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);
}
}
此代码会提示用户对话框,直到他按下“允许”或“确定”按钮,但一旦他按下“< strong>拒绝”或“取消”按钮。我该怎么做呢?当我按下“拒绝”按钮时,是否会调用任何函数?
最佳答案
您需要重写 onActivityResult 方法。
您正在使用常量 REQUEST_ENABLE_BT 传递 requestCode
因此,当用户在该 onActivityResult 方法之后按下允许或拒绝按钮时,将从您的 Activity 中调用。
@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);
}
}
关于安卓 : Deny button pressed on Bluetooth enabling dialog box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20652211/