蓝牙扫描什么都不返回

时间:2016-04-08 08:11:05

标签: android bluetooth

我最近在学习Android。我试图实现搜索蓝牙设备的功能。我能够列出所有以前配对的设备,但我无法发现新设备。

权限在AndroidManifest.xml中设置。

这是我的代码:

public void listDiscoverableDevices(boolean status) {
    // Create a BroadcastReceiver for ACTION_FOUND
    mBluetoothAdapter.cancelDiscovery();
    mArrayAdapter.clear();
    mDisplay.setText("Search");
    mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //BluetoothDevice.
            if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mArrayAdapter.add(device.getAddress());
            } else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                //mDisplay.setText(action);
                mArrayAdapter.add(action);
            } else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //mDisplay.setText(action);
                mArrayAdapter.add(action);
            }
        }
    };

    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

    if(!mBluetoothAdapter.startDiscovery()) {
    mDisplay.setText("Discover failed!");
    }
}

在我看来,从未收到过BluetoothDevice.ACTION_FOUND操作。我这两天一直在努力。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我花了两天时间。今天我终于发现了为什么我的程序第一次没有工作。从Android 6.0开始,您还需要android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_FINE_LOCATION权限才能扫描远程蓝牙设备。

您可能需要转到"设置" - >"应用" - > yourApp->"权限"打开位置服务权限。或者我猜您也可以通过编程方式请求权限。