Android 6.0 - 蓝牙 - Action_Found 广播意图不存在代码

Android 6.0 - Bluetooth - No code exists for Action_Found broadcast intent

更新

我尝试了很多代码,也来自互联网上显示的示例。他们每个人都遵循我的方法。经过几个小时的测试,我得出的结论是 Android 6.0 无法实现未知设备的蓝牙发现,我们只能检索绑定的设备。 我很确定这个 android 版本有一些东西。

如果有人知道如何解决这个问题,我将不胜感激。


原版Post

我的代码运行良好,但找不到任何设备。 我只收到 DISCOVERY_STARTED 和 DISCOVERY_FINISHED,所以没有找到任何设备,但是使用系统应用程序找到了这些设备。

这是我的应用程序代码,希望对您有所帮助。

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

//other stuff...

    IntentFilter filter=new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    registerReceiver(myreceiver,filter);
}

final BroadcastReceiver myreceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        Log.i("test","RECEIVED: "+ action);
        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        }

        if(BluetoothDevice.ACTION_FOUND.equals(action))
        {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Log.i("test", device.getName() + "\n" + device.getAddress());
        }
    }};

public void scanDevices(View v){

        if (bluetoothAdapter.isEnabled()){

            bluetoothAdapter.startDiscovery();
        }
}

我已经设置了权限:

<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.添加 FINE_LOCATION 权限以显示:

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

2。在运行时请求 FINE_LOCATION 权限:

//since i was working with appcompat, i used ActivityCompat method, but this method can be called easily from Activity subclassess.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSION_REQUEST_CONSTANT);

3。实施 onRequestPermissionsResult 方法:

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

switch (requestCode) {
    case MY_PERMISSION_REQUEST_CONSTANT: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            //permission granted!
        }
        return;
    }
}
}

这一切都是因为 Marshmallows 需要此权限才能使用蓝牙进行发现。

由于此权限属于Dangerous组权限,简单地在清单中声明是行不通的,我们需要用户明确同意才能使用该位置(即使我们实际上不需要这个职位)。