首页 > 解决方案 > Android ble扫描蓝牙附近的设备kotlin

问题描述

我正在尝试使用 BLE API 扫描附近的蓝牙设备,但它似乎无法正常工作

我已经在清单中添加了权限

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

<uses-feature
    android:name="android.hardware.bluetooth_le"
    android:required="true" />

以下在 oncreate 创建对象

 val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    val bluetoothAdapter = bluetoothManager.adapter
    val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner
    if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
    }
    when (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
        else -> requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 1)
    }

创建扫描器回调对象并进一步扫描

private val leScanCallback = object :ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        super.onScanResult(callbackType, result)
        Log.e("DeviceListActivity","onScanResult: ${result.device.address} - ${result.device.name}")
        Log.e("device ", "kskd   " + result.getRssi())
    }

    override fun onBatchScanResults(results: MutableList<ScanResult>?) {
        super.onBatchScanResults(results)
        Log.e("DeviceListActivity","onBatchScanResults:${results.toString()}")
    }

    override fun onScanFailed(errorCode: Int) {
        super.onScanFailed(errorCode)
        Log.e("DeviceListActivity", "onScanFailed: $errorCode")
    }

}

bluetoothLeScanner.startScan(leScanCallback)

在 logcat 中,我只看到以下内容

D/BluetoothAdapter: STATE_ON
 D/BluetoothAdapter: BLE support array set: 010011
 D/BluetoothLeScanner: Start Scan with callback
D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=4 mScannerId=0

这是我的应用程序构建 gradle

android {
compileSdkVersion 30
buildToolsVersion "30.0.2"

defaultConfig {
    applicationId "com.mine.ble"
    minSdkVersion 23
    targetSdkVersion 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
    jvmTarget = '1.8'
}

}

有人可以指出我在这里可能缺少什么吗?

标签: androidkotlinbluetoothbluetooth-lowenergy

解决方案


试试这个代码

    if (bluetooth.isEnabled()&&checkCoarseLocationPermission()){
        final BroadcastReceiver receiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                BluetoothDevice deviceExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d("TAG",deviceExtra.getName());

            }
        };
        IntentFilter filter = new IntentFilter();
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver,filter);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!isGpsEnabled) {
            startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 12);
            return;
        }
        adapter.cancelDiscovery();
        adapter.startDiscovery();
    }

清单.xml

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

推荐阅读