蓝牙启用时间

时间:2018-01-17 14:20:26

标签: android bluetooth

我根据客户要求使用以下代码在内部启用蓝牙并在退出应用程序时禁用蓝牙。

if (!bluetoothAdapter.isEnabled()) {
            MMLogger.logInfo(MMLogger.LOG_BLUETOOTH, "BluetoothSyncController - Bluetooth was OFF, so Turn it ON");
            bluetoothAdapter.enable();
            try {
                Thread.sleep(WAIT_FOR_SOMETIME_TO_START_BLUETOOTH);  
            } catch (InterruptedException ignore) {
            }
            MMLogger.logInfo(MMLogger.LOG_BLUETOOTH, "BluetoothSyncController - Bluetooth turned ON");
        }

WAIT_FOR_SOMETIME_TO_START_BLUETOOTH是否有标准时间?我的意思是任何文件?

1 个答案:

答案 0 :(得分:0)

您可以尝试this answer。似乎有一些标准的蓝牙事件和处理程序。

从该来源:您的活动可以管理的事件,例如

STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF

您可以使用BroadcastReciever捕获这些内容。首先,您要确保使用以下内容为清单内的蓝牙授予权限:

<uses-permission android:name="android.permission.BLUETOOTH" />

然后,您可以创建具有以下onReceive()的自定义广播接收器:

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

    if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
        final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
        switch(state) {
            case BluetoothAdapter.STATE_OFF:
                ..
                break;
            case BluetoothAdapter.STATE_TURNING_OFF:
                ..
                break;
            case BluetoothAdapter.STATE_ON:
                ..
                break;
            case BluetoothAdapter.STATE_TURNING_ON:
                ..
                break;
        }

    }
}

然后,不是让线程等待,而是让接收事件触发您想要运行的代码。有关使用BroadcastReciever的更多信息,请参阅我提供的链接或直接访问android文档。

相关问题