在Android蓝牙编程中连接和断开范围

时间:2013-12-27 08:51:56

标签: android sockets bluetooth connection range

我编写了关于android蓝牙编程的代码。我正在连接到HC06模块。我使用套接字并且我使用了Runnable方法。如果连接已经结束我关闭套接字

当我断开蓝牙线缆时,我可以看到连接失败的消息。但是我从蓝牙连接范围退出,我看不到连接失败的消息。

我无法退出蓝牙设备连接范围。即使我搬走了。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用意图过滤器来收听ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECT_REQUESTED和ACTION_ACL_DISCONNECTED广播:

public void onCreate() {
    ...
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter1);
    this.registerReceiver(mReceiver, filter2);
    this.registerReceiver(mReceiver, filter3);
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           ... //Device found
        }
        else if (BluetoothAdapter.ACTION_ACL_CONNECTED.equals(action)) {
           ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           ... //Done searching
        }
        else if (BluetoothAdapter.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
           ... //Device is about to disconnect
        }
        else if (BluetoothAdapter.ACTION_ACL_DISCONNECTED.equals(action)) {
           ... //Device has disconnected
        }           
    }
};