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



更新

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

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


原始帖子

我的代码运行良好,但找不到任何设备。我只收到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;
    }
}
}

所有这些都是因为棉花糖需要此权限才能使用蓝牙进行发现。

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

最新更新