更改蓝牙可发现性时未发送广播

时间:2012-03-25 21:14:21

标签: android bluetooth

目前我正在尝试设置一个应用程序让两台设备通过蓝牙进行通信。

我有一个显示单个Button的屏幕。单击此按钮将使设备可被发现并禁用该按钮。当设备不再可被发现时,应再次启用该按钮。

Dev Guide中的建议一样,我注册BroadcastReceiver,以便在可发现性结束时通知

问题:

有时,当设备不再可被发现时,我不会收到任何广播。另一方面,我通常会在进入可发现性时收到2个广播。可发现工作正常,由LogCat和设备看到我的手机(HTC Desire HD)120秒证明。

这是来自LogCat的记录,显示在开始发现后立即收到2个广播:

03-25 23:01:47.557: INFO/System.out(16905): --------broadcast received-------------
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): current scan mode: 21
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): previous scan mode: 23
03-25 23:01:47.557: INFO/System.out(16905): --------broadcast received-------------
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): current scan mode: 23
03-25 23:01:47.557: DEBUG/MuliplayerServerActivity(16905): previous scan mode: 21

启动可发现性的代码如下:

private void becomeVisible() {

    Intent discoverableIntent = new Intent(
            BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    startActivityForResult(discoverableIntent,
            CODE_REQUEST_MAKE_DISCOVERABLE);

}

我的BroadcastReceiver看起来像这样:

private final BroadcastReceiver discoverableModeChangedReceiver = new BroadcastReceiver() {

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

        System.out.println("--------broadcast received-------------");
        int scanMode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,
                0);
        int scanModePrevious = intent.getIntExtra(
                BluetoothAdapter.EXTRA_PREVIOUS_SCAN_MODE, 0);
        Log.d(TAG, "current scan mode: " + scanMode);
        Log.d(TAG, "previous scan mode: " + scanModePrevious);

        if (scanMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            // show button
            findViewById(R.id.btn_become_visible).setEnabled(false);
        } else {
            // hide button
            findViewById(R.id.btn_become_visible).setEnabled(true);
        }
    }
};

1 个答案:

答案 0 :(得分:2)

您必须先注册行动:

IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); 
registerReceiver(discoverableModeChangedReceiver, intent);