android - BluetoothChat 示例,无法识别丢失的连接

标签 android bluetooth

我已使用BluetoothChat 示例在我的应用程序中构建蓝牙连接。应用程序正确连接,并正确存储所有配对的设备,但无法正确报告丢失的连接。

我的手机连接的设备由小电池供电,闲置约 30 秒后会关闭。我希望我的应用程序在该设备关闭时通知用户。我原以为这会包含在 BluetoothChat 示例中,但我认为事实并非如此。

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

    public ConnectThread(BluetoothDevice device, boolean secure) {

        mmDevice = device;
        BluetoothSocket tmp = null;
        mSocketType = secure ? "Secure" : "Insecure";

        try {
            if (secure) {
                tmp = device.createRfcommSocketToServiceRecord( MY_UUID
                        );
            } else {
                tmp = device.createInsecureRfcommSocketToServiceRecord(
                        MY_UUID );
            }
        } catch (IOException e) {
            Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
        }
        mmSocket = tmp;
    }

    public void run() {
        //Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
        setName("ConnectThread" + mSocketType);

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

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mmSocket.connect();
        } catch (IOException e) {
            // Close the socket
            try {
                mmSocket.close();
            } catch (IOException e2) {
                Log.e(TAG, "unable to close() " + mSocketType +
                        " socket during connection failure", e2);
            }
            connectionFailed();
            return;
        }

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

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

    public void cancel() {
        RelayAPIModel.bluetoothConnected = false;
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
        }
    }
}

ConnectedThread 如下:

/**
 * This thread runs during a connection with a remote device.
 * It handles all incoming and outgoing transmissions.
 */
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final BufferedReader mmInBuffer;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        Log.d(TAG, "create ConnectedThread: " + socketType);
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        RelayAPIModel.bluetoothConnected = true;
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
        mmInBuffer = new BufferedReader( new InputStreamReader( mmInStream ) );
    }

    public void run(int length) {
        buffer = new byte[1024];


        // Keep listening to the InputStream while connected
        //while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer, 0, length);

                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(MainMenu.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {

                Message msg = mHandler.obtainMessage(MainMenu.MESSAGE_TOAST);
                Bundle bundle = new Bundle();
                bundle.putString( TOAST, "Device has disconnected from the Bluetooth Module." );
                msg.setData(bundle);
                mHandler.sendMessage(msg);
                Log.e(TAG, "disconnected a", e);
                connectionLost();

                // Start the service over to restart listening mode
                BluetoothService.this.start();
                //break;
            }
       // }
    }

    /**
     * Write to the connected OutStream.
     * @param buffer  The bytes to write
     */
    public void write( byte[] buffer ) {
        try {
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity
            mHandler.obtainMessage(MainMenu.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

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

我也有这个connectionLost函数,如果ConnectedThread中捕获到异常,应该调用该函数,但该异常似乎永远不会被捕获。

private void connectionLost() {
    // Send a failure message back to the Activity
    Message msg = mHandler.obtainMessage(MainMenu.MESSAGE_TOAST);
    RelayAPIModel.bluetoothConnected = false;
    Bundle bundle = new Bundle();
    bundle.putString(TOAST, "Device connection was lost");
    msg.setData(bundle);
    mHandler.sendMessage(msg);
    Log.i("Here.",  "Connection Lost" );
    // Start the service over to restart listening mode
    BluetoothService.this.start();
}

最佳答案

在这里,在广播接收器中,重写 onRecieve 以获取蓝牙连接的断开连接 Intent 。

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
            //disconnect request
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //disconnected, do what you want to notify user here, toast, or dialog, etc.
        }
    }
}

关于android - BluetoothChat 示例,无法识别丢失的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13823752/

相关文章:

android - 检查 Volley 是从缓存还是通过网络获取结果

安卓火力地堡 : Robo script failing on Location Permissions Dialog

java - 如何遍历 R.java 类的 id 属性?

c# - Windows 10 UWP 蓝牙与 Arduino 的连接

android - 按下设备的主页键后,如何始终在图标按下时打开当前 Activity

android - 是否可以在 Android 上使用 BL 3.0 实现类似 BLE 的邻近服务?

Linux over BlueZ 下的 C++ 蓝牙耳机

android - 如何设置安卓蓝牙权限

java - Android 到 Playstation 和其他游戏机

android - 为什么不推荐使用绝对布局?