我有一个进度条,它会一直运行,直到我连接到 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()
中执行此操作。
最佳答案
创建一个蓝牙广播接收器。 因此,这将在蓝牙启用和禁用时执行。
您必须通过以下操作进行注册。
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 则表示禁用蓝牙。
关于Android 检测蓝牙关闭并停止进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41673686/