【问题标题】:Broadcast Receiver for discover bluetooth devices not working用于发现蓝牙设备不工作的广播接收器
【发布时间】:2019-03-25 17:50:53
【问题描述】:

您好,我已按照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 广播接收器工作正常,是否需要进行更改才能使其适用于 Android 8.1?

【问题讨论】:

  • 嗨,我也有同样的问题。你找到解决办法了吗?

标签: java android bluetooth broadcast receiver


【解决方案1】:

在清单中,我已经设置了权限和其他服务,例如开始停止蓝牙并发现配对设备工作正常......

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

【讨论】:

    【解决方案2】:

    您需要在版本 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多