广播接收器,用于发现蓝牙设备不起作用

时间:2018-10-21 13:56:34

标签: java android bluetooth broadcast receiver

您好,我已按照https://developer.android.com/guide/topics/connectivity/bluetooth中的示例进行操作,我的广播接收器可能无法正常工作。我在我的Android Xiaomi mi A1设备中运行android 8.1。

@Override
protected void onCreate(Bundle savedInstanceState) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
    bluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mReceiver = 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 = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceHardwareAddress = device.getAddress(); // MAC address
            Toast.makeText(MainActivity.this, deviceName, Toast.LENGTH_SHORT).show();
            Toast.makeText(MainActivity.this, deviceHardwareAddress, Toast.LENGTH_SHORT).show();
            mDeviceList.add(deviceHardwareAddress);
            ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,mDeviceList);
            listV.setAdapter(arrayAdapter);
        }
    }
};

谢谢!

注意

对于android Api 21 Broadcast接收器来说,它可以正常工作吗?我必须进行一些更改以使其适用于Android 8.1吗?

2 个答案:

答案 0 :(得分:0)

清单中,我放了权限和其他服务,例如启动停止蓝牙,发现配对的设备运行正常...

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

答案 1 :(得分:0)

您需要在版本M以上的代码中添加权限

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1000);