【问题标题】:Android ble scanning bluetooth nearby devices kotlinAndroid ble扫描蓝牙附近的设备kotlin
【发布时间】:2020-12-02 16:29:38
【问题描述】:

我正在尝试使用 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'
}

}

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

【问题讨论】:

    标签: android kotlin bluetooth bluetooth-lowenergy


    【解决方案1】:

    试试这个代码

        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();
        }
    

    Manifest.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"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2016-06-26
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      相关资源
      最近更新 更多