我是Android应用程序开发人员和BLE的新手,我正在使用示例代码BluetoothLeGatt [我从Android Studio导入的代码]学习这些内容。该代码可以在我的平板电脑上正常工作(Android 5.0),但扫描活动不会返回Android 6.0上的任何BLE设备。我得到的错误信息如下所示。如何修改BluetoothleGatt以在Android 6.0上启用BLE设备扫描?
07-19 12:41:39.615 7617-7642/? W/Binder: Caught a RuntimeException from the binder stub implementation.
java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results
at android.os.Parcel.readException(Parcel.java:1599)
at android.os.Parcel.readException(Parcel.java:1552)
at android.bluetooth.IBluetoothGatt$Stub$Proxy.startScan(IBluetoothGatt.java:772)
at android.bluetooth.le.BluetoothLeScanner$BleScanCallbackWrapper.onClientRegistered(BluetoothLeScanner.java:331)
at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:56)
at android.os.Binder.execTransact(Binder.java:458)
我看了看后Bluetooth Low Energy startScan on Android 6.0 does not find devices和Requesting Permissions at Run Time的官方页面,但我还是真的不知道如何修改我的代码。
我确实添加了GPS,ACCESS_FINE_LOCATION和ACCESS_COARSE_LOCATION的权限,我打开位置服务在我的平板电脑。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps" />
但该应用程序仍然无法返回任何BLE设备。然后,当我尝试将下面的代码块添加到我的应用程序中时(从请求运行时权限),checkSelfPermission [无法解析符号'checkSelfPermission']总是出错。但我没有进口import android.support.v4.content.ContextCompat;
有人可以帮助我吗?另外,对于如何使DeviceScanActivity工作的问题有没有更简单的答案?我真的不知道在哪里把代码块从请求权限在运行时我的代码:(我知道这是一个非常愚蠢的问题,但我真的很陌生,请帮助我!
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
编辑 以下是我的相关模块
dependencies {
compile "com.android.support:support-v4:25.3.1"
compile "com.android.support:support-v13:25.3.1"
compile "com.android.support:cardview-v7:25.3.1"
compile "com.android.support:appcompat-v7:25.3.1"
}
你的应用程序的目标是什么SDK级别(在应用程序的'build.gradle'文件中定义)? – stkent
另外,你的'dependencies'块包含什么? (也许编辑这些到你的问题:)) – stkent
我的目标SDK级别是25在build.gradle文件。 – Natalie