Android 检测蓝牙关闭并停止进度对话框

标签 android

我有一个进度条,它会一直运行,直到我连接到 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/

相关文章:

java - 将自定义对话框设置为 Activity 一次

javascript - 安卓 WebView : is there a way to get a javascript stack trace?

java - 连接失败 : ECONNREFUSED

android - Cordova Android 崩溃回溯

android - 如何在android中通过向左滑动或向右滑动一张一张地切换图像?

java - GAE无法访问客户端中实体类的公共(public)方法

android - 在 android/Xamarin.Android 中单击通知时切换到运行 Activity

java - @AutoAnnotation 有什么用?怎么可以用呢?

android - 什么时候在android中使用不推荐使用的方法是合适的

java - 安卓。保存自定义对象的小型 arrayList 的简单方法