安卓6蓝牙

标签 android bluetooth

我升级到 Android 6,但我使用蓝牙的应用程序无法使用这个新的 API 版本。 Play Store 上的应用程序存在同样的问题:Bluetooth spp tools pro(查看蓝牙是否工作的好应用程序),它没有发现设备。

问题似乎出在蓝牙发现上:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery()
Log.i("BLUETOOTH", String.valueOf(mBluetoothAdapter.isDiscovering())); // Return false

我的应用程序在 Android 4/5 上运行良好,我遵循了:http://developer.android.com/guide/topics/connectivity/bluetooth.html

最佳答案

从 Android 6.0 开始,在 list 中包含权限是不够的。 您必须明确询问用户有关被视为“危险”的每个权限。 BluetoothDevice.ACTION_FOUND 需要 BLUETOOTH 和 ACCESS_COARSE_LOCATION 权限 http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_FOUND

ACCESS_COARSE_LOCATION http://developer.android.com/reference/android/Manifest.permission.html#ACCESS_COARSE_LOCATION 是一种“危险”权限,因此您必须在进行实际发现之前使用 requestPermission 请求它。

  public void doDiscovery() {
    int hasPermission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
    if (hasPermission == PackageManager.PERMISSION_GRANTED) {
        continueDoDiscovery();
        return;
    }

    ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{
                    android.Manifest.permission.ACCESS_COARSE_LOCATION},
            REQUEST_COARSE_LOCATION_PERMISSIONS);
}

然后您将在 onRequestPermissionsResult 上获得用户答案

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case REQUEST_COARSE_LOCATION_PERMISSIONS: {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                continueDoDiscovery();
            } else {
                Toast.makeText(this,
                        getResources().getString(R.string.permission_failure),
                        Toast.LENGTH_LONG).show();
                cancelOperation();
            }
            return;
        }
    }
}

要使用以前版本的 android,您应该使用兼容性库并使用 ActivityCompat 进行调用

关于安卓6蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33142034/

相关文章:

android - 无法发现蓝牙设备

android - Android后台服务中的蓝牙连接?

Android- ArrayAdapter 构造函数

android - 为什么 setWidth 不起作用?

android - 在 android 中获取 uri.parse() 的文件路径

android - 使 HttpDefaultClient 的 execute() 非常慢

java - 获取 java.io.IOException : read failed, 套接字可能已关闭或在 BluetoothSocket.connect() 上超时

android - Xamarin 蓝牙输入流未读取所有字节(有时)

java - Android/Java 理解我何时能够使用/覆盖变量

android - 如何请求OBD参数并接收它们