蓝牙连接未关闭

时间:2016-10-29 21:04:01

标签: android multithreading bluetooth thread-safety

大家好,我已经在这个应用程序上工作了很长时间了,我想我差不多完成但是有一个问题,我尝试了很多不同的方法来解决它,但我不能这么任何帮助我会很感激。 该应用程序是简单的蓝牙数据发送器到蓝牙模块,它工作得很好,如果我想从应用程序关闭连接,我无法关闭它,我已经尝试中断和取消方法并将条件放入while循环但没有任何运气,所以任何人都可以帮助我,谢谢你。

这是我的客户端线程(与android开发人员相同)

    private class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private boolean x;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;
        // Log.i(tag, "construct");

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);


        }
        catch (IOException e) {
            //    Log.i(tag, "get socket failed");

        }
        mmSocket = tmp;
    }


    public void run() {
        // Cancel discovery because it will slow down the connection
       while (true) {
            bluetoothAdapter.cancelDiscovery();
            Log.i(tag, "connect - run");
            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
                Log.i(tag, "connect - succeeded");
            } catch (IOException connectException) {
                Log.i(tag, "connect failed");
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                } catch (IOException closeException) {
                }
                return;
            }

            // Do work to manage the connection (in a separate thread)

            xHandler.obtainMessage(0, mmSocket).sendToTarget();

           if(x==false){

               break;

           }
        }


}



    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {

            Log.i(tag,"cancel 1");
            mmSocket.close();
            x=false;

            //   mmDevice.close();
        } catch (IOException e) { }
    }
}

这是我的连接类

    private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private   boolean x;
    //private  FileInputStream fis;
    private int s;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        //s=x;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {


        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        //  if (s == 1) {

        byte[] buffer;
        // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs}
        //}
        while (x) {
            try {
                // Read from the InputStream
                buffer=new byte[1024];
                // buffer = new byte[1024];

                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                xHandler.obtainMessage(1, bytes, -1, buffer)
                        .sendToTarget();

            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        Log.i(tag,"write");
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
            mmInStream.close();
            mmOutStream.close();
            x=false;
            Log.i(tag,"cancel 2");

        }
        catch (IOException e) { }

}



   }

最后是处理程序:

       public Handler xHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        Log.i(tag, "in handleeer");
        super.handleMessage(msg);
        switch(msg.what){
            case 0:
                // DO something
                // if(omar==1){
                //(BluetoothSocket)msg.obj
              //  bluetoothSocket=(BluetoothSocket).msg.obj;

                     connectedThread = new      ConnectedThread((BluetoothSocket)msg.obj);
                Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_LONG).show();
                //omar++;}
                //String s = "79";
                String s="h";
                connectedThread.write(s.getBytes());
                Log.i(tag, "connected");
                break;
            case 1:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                break;

        }
    }
};

0 个答案:

没有答案