我正在开发蓝牙应用程序。在我的应用程序中,我有以下代码。当蓝牙关闭时,意味着我的else语句会在打开蓝牙时发现设备列表(它工作正常),否则,如果该语句将运行并获取设备列表。

My problem is "if condition is runnning but it doesn't discover the devices"


。任何人都可以提出解决方案。

if (btAdapter.isEnabled()) {

        registerReceiver(ActionFoundReceiver, new IntentFilter(
                BluetoothDevice.ACTION_FOUND));
        btAdapter.startDiscovery();
    } else {
        Intent i1 = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivity(i1);

        new java.util.Timer().schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                registerReceiver(ActionFoundReceiver, new IntentFilter(
                        BluetoothDevice.ACTION_FOUND));
                btAdapter.startDiscovery();
            }
        }, 5000);

    }


//接收器检测设备代码

 private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {

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

        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            items += device.getName() + ",";

        }
        Toast.makeText(getApplicationContext(), items, Toast.LENGTH_LONG)
                .show();
    }

};

最佳答案

我想这正是您所需要的。

http://developer.android.com/guide/topics/wireless/bluetooth.html#FindingDevices

http://developer.android.com/guide/topics/wireless/bluetooth.html#DiscoveringDevices

关于在不询问用户的情况下启用蓝牙的内容,文档内容如下:

Bluetooth should never be enabled without direct user consent. If you

want to turn on Bluetooth in order to create a wireless connection, you should use the ACTION_REQUEST_ENABLE Intent, which will raise a dialog that requests user permission to turn on Bluetooth. The enable() method is provided only for applications that include a user interface for changing system settings, such as a "power manager" app.


但是,如果您真的想这样做,可以采取以下方法:

BluetoothAdapter.enable()

您可以调用此电话而无需询问用户

为了使enable()起作用,您必须在Android Manifest文件中添加权限

“ android.permission.BLUETOOTH_ADMIN”

尝试一下,

getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

关于android - 蓝牙发现无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18401021/

10-11 22:03
查看更多