我有一个继续运行的进度条,直到我连接到BLE。这是代码 -
@Override
public void Progress() {
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (progressDialog == null) {
progressDialog = ProgressDialog.show(activity, getString(R.string.wait), getResources().getString(R.string.connecting), true, false);
}
progress.setVisibility(View.VISIBLE);
container.setVisibility(View.GONE);
}
});
}
当进度正在运行时我的意思是当显示进度对话框时,如果禁用设置中的蓝牙,我需要检测它并停止进度并关闭对话框。我如何在run()
中执行此操作。
答案 0 :(得分:1)
为蓝牙创建一个广播接收器。 所以这将在蓝牙启用和禁用时执行。
您必须注册以下操作。
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
在您的广播接收器中,您必须像下面一样修改您的代码。
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
boolean bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
== BluetoothAdapter.STATE_ON;
//when bluetooth enabled
if(bluetoothState) {
//hide your progress bar here
}
}
}
如果bluetoothState为true则表示启用蓝牙,false表示禁用。
答案 1 :(得分:1)
如果您想要在已经出现的情况下关闭对话框,然后如果您禁用蓝牙并希望隐藏对话框而不在您已经打开的活动中执行任何操作,那么您可以使用广播接收器,为此请参考此链接: How to detect Bluetooth state change using a broadcast receiver?
或者如果您想要点击按钮,那么您可以尝试以下代码:
public static boolean isBluetoothAvailable() {
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return (bluetoothAdapter != null && bluetoothAdapter.isEnabled());
}
答案 2 :(得分:0)
试试这个
-o
答案 3 :(得分:0)
/* Register BroadcastReceiver with intent action BluetoothAdapter.ACTION_STATE_CHANGED and move your notifiyng code into onReceive method. Don't forget to check if new state is OFF */
if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
` if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
== BluetoothAdapter.STATE_OFF)`}
答案 4 :(得分:0)
您可以通过以下方式检查蓝牙是否被禁用:
boolean isBluetoothDiasabled(){
BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(!myBluetoothAdapter.isEnabled()){
return true;
}
return false;
}