如何等到蓝牙在Android中打开 [英] how to wait till bluetooth turn on in android

查看:164
本文介绍了如何等到蓝牙在Android中打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式在android设备中打开蓝牙,然后等到它继续进行下一行代码.

I need to turn on Bluetooth in an android device programmatically and wait till it on to proceed to next line of code.

我的代码如下

if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                ctx.startActivity(enableBtIntent);
}

这样做时,代码将从下一行继续执行,而无需等待蓝牙完全打开.有什么办法可以解决这个问题?我可以添加外观以检查蓝牙是否打开吗?

When doing like this, the code continue to execute from next line without waiting for bluetooth completely on. Is there any way to solve this? Can I add a look to check if bluetooth is on?

推荐答案

您可以注册BroadcastReceiver来侦听BluetoothAdapter上的状态更改.

You can register a BroadcastReceiver to listen for state changes on the BluetoothAdapter.

首先创建一个BroadcastReceiver,它将监听状态更改

First create a BroadcastReceiver that will listen for state changes

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                                                BluetoothAdapter.ERROR);
            switch (bluetoothState) {
            case BluetoothAdapter.STATE_ON:
                //Bluethooth is on, now you can perform your tasks
                break;
            }
        }
    }
};

然后在创建ActivityBroadcastReceiver注册 ,以便它可以开始接收事件.

Then register the BroadcastReceiver with your Activity when it is created so that it can start receiving events.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Set a filter to only receive bluetooth state changed events.
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mReceiver, filter);
}

Activity被销毁时,请记住取消注册监听器.

Remember to unregister the listener when the Activity is destroyed.

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
}

这篇关于如何等到蓝牙在Android中打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆