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

时间:2016-07-04 16:16:19

标签: android bluetooth discovery

更新

我尝试了许多代码,也可以从互联网上显示的示例中找到。他们每个都遵循我的方法。经过几个小时的测试,我得出结论,在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" />

1 个答案:

答案 0 :(得分:11)

非常简单的解决方案:

<强> 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;
    }
}
}

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

由于此权限属于危险权限组,只需在清单中声明它不起作用,我们需要用户明确同意使用该位置(甚至如果我们实际上不需要这个职位。

相关问题