簡體   English   中英

Android 藍牙掃描錯誤

[英]Android bluetooth scan errors

btAdapter.isDiscovering(),btAdapter.startDiscovery(); btAdapter.cancelDiscovery(); 設備.getName();

4four erros Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission ) 或顯式處理潛在的SecurityException

請解決這個問題

 public void onClickButtonSearch(View view){
    // Check if the device is already discovering

    if(btAdapter.*isDiscovering()*){
        *btAdapter.cancelDiscovery()*;
    } else {
        if (btAdapter.isEnabled()) {
            *btAdapter.startDiscovery();*
            btArrayAdapter.clear();
            if (deviceAddressArray != null && !deviceAddressArray.isEmpty()) {
                deviceAddressArray.clear();
            }
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(receiver, filter);
        } else {
            Toast.makeText(getApplicationContext(), "bluetooth not on", Toast.LENGTH_SHORT).show();
        }
    }
}

// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver receiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Discovery has found a device. Get the BluetoothDevice
            // object and its info from the Intent.
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.*getName();*
            String deviceHardwareAddress = device.getAddress(); // MAC address
            btArrayAdapter.add(deviceName);
            deviceAddressArray.add(deviceHardwareAddress);
            btArrayAdapter.notifyDataSetChanged();
        }
    }
};

protected void onDestroy() {
    super.onDestroy();

    // Don't forget to unregister the ACTION_FOUND receiver.
    unregisterReceiver(receiver);
}

對於目標為 Android 11 或更低版本的應用,調用BluetoothAdapter#startDiscovery()需要Manifest.permission#BLUETOOTH_ADMIN權限,該權限可通過簡單的清單標簽獲得。

對於 API 級別 31 或更高級別的應用,這需要Manifest.permission#BLUETOOTH_SCAN權限。

此外,這需要Manifest.permission#ACCESS_FINE_LOCATION權限或您永遠不會獲得設備物理位置的強烈斷言。

可以通過以下代碼獲取權限:

getActivity().requestPermissions(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION}, 
    YOUR_REQUEST_LOCATION_PERMISSION_CODE);

有關更多信息: https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#startDiscovery()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM