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

问题描述 投票:0回答:1

更新

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

如果有人知道如何解决这个问题,我将非常感谢任何帮助。


原帖

我的代码工作正常,但找不到设备。 我只收到 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" />
android bluetooth bluetooth-device-discovery
1个回答
12
投票

非常简单的解决方案:

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 组权限,因此仅在清单中声明它是行不通的,我们需要用户明确同意才能使用该职位(即使我们实际上不需要该职位)。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.