如何确保蓝牙连接在其他活动中启动时关闭?

时间:2015-06-05 04:54:32

标签: android multithreading socket.io android-bluetooth

我正在开发的APP连接到蓝牙打印机(那些好奇的microFlash 2te)。

蓝牙连接由BluetoothConnectionManager类管理,活动级别的消息处理程序处理来自BluetoothChatService的信息。

当我将活动留在受控环境中时,我确保通过停止停止所有线程的bluetoothConnectionManager来断开蓝牙连接。

然而,当用户退出后退按钮时,我无法确保线程停止。如果我尝试连接套接字,因为蓝牙设备已连接,这会导致问题。

有没有我可以找到并使用或杀死另一个活动创建的bluetoothConnectionManager?或者有没有办法确保在活动关闭时bluetoothConnectionManager停止?

附件是BluetoothConnectionManager中的连接线程类:

    private class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "create() failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectThread");
        setName("ConnectThread");

        // Always cancel discovery because it will slow down a connection
        mAdapter.cancelDiscovery();

        //stop();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            d("About to connect to socket...");
            mmSocket.connect();

        } catch (IOException e) {
            connectionFailed();
            // Close the socket
            try {
                mmSocket.close();


            } catch (IOException e2) {
                d(e2.getMessage().toString());
                Log.e(TAG,
                        "unable to close() socket during connection failure",
                        e2);
            }
            return;
        }

        // Reset the ConnectThread because we're done
        synchronized (BluetoothConnectionManager.this) {
            mConnectThread = null;
        }

        // Start the connected thread
        connected(mmSocket, mmDevice);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

0 个答案:

没有答案