2

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

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();
    }

};
4

1 回答 1

1

我想这正是你所需要的。

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.

但如果你真的想这样做,有办法:

蓝牙适配器.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));
于 2013-08-23T10:56:34.833 回答