无法从Android中的蓝牙设备读取任何数据

时间:2016-02-26 06:49:31

标签: android bluetooth inputstream

我正在使用蓝牙设备。基本上我希望我的应用程序连接到设备并接收它发送的数据。但到目前为止,我能够连接到蓝牙设备,但我无法从它接收任何输入。

这是我的问题:

i)DataInputStream.available()始终返回0.

ii)如果我在线使用任何断点 bytes = input.read(buffer); //这将冻结并不显示任何内容。 它下面的行永远不会执行

public class ConnectThread extends Thread{

    final String TAG="ConnectThread";
    private ReadThread mReadThread = null;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    private boolean isDeviceConnected;


    public final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private BluetoothSocket mmSocket = null;
    Handler mHandler;
    BluetoothDevice bTdevice;
    private DataInputStream mReadData = null;



    public ConnectThread(BluetoothDevice bTdevice, Handler mHandler) {
        super();
        this.bTdevice = bTdevice;
        this.mHandler = mHandler;

        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        BluetoothSocket socket;
        try {
            socket = bTdevice.createRfcommSocketToServiceRecord(MY_UUID);
            System.out.println("**** Socket created using standard way******");
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
            mmSocket = socket;


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    @Override
    public synchronized void run() {
        // TODO Auto-generated method stub
        super.run();
        // Get a BluetoothSocket to connect with the given BluetoothDevice

        try {

            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            if (adapter != null) {
                adapter.cancelDiscovery();
                Log.i("***Bluetooth Adapter**", "Bluetooth Discovery Canceled");
            }

            if (mmSocket != null) {

                mmSocket.connect();
                Log.i("***Socket Connection Successful**", "Socket Connection Successful");
                isDeviceConnected = true;

                mReadData = new DataInputStream(mmSocket.getInputStream());
                Log.i("***Read data**", "" + mReadData);



                if (mReadThread == null) {
                    mReadThread=new ReadThread(mReadData,mmSocket);
                    mReadThread.start();
                }


            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("***Error**", "Socket Connection failed");
            e.printStackTrace();
            try {
                mmSocket.close();
                isDeviceConnected = false;
            } catch (IOException closeException) {
                e.printStackTrace();

            }

        }

        // mHandler.obtainMessage(DisplayBtdataActivity.SUCCESS_CONNECT,mmSocket).sendToTarget();

    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
        }
    }





    // Read the data from device

    private class ReadThread extends Thread {

        /** The input. */
        private DataInputStream input;

        /**
         * Constructor for ReadThread.
         * 
         * @param input
         *            DataInputStream
         */
        private BluetoothSocket mSocket;

        public ReadThread(DataInputStream input, BluetoothSocket socket) {
            this.input = input;
            this.mSocket = socket;
        }

        /**
         * Method run.
         * 
         * @see java.lang.Runnable#run()
         */
        public synchronized void run() {
            try {
                Log.d(TAG, "ReadThread run");

                byte[] buffer = new byte[1024]; // buffer store for the stream
                int bytes; // bytes returned from read()
                bytes = input.available(); // always return 0
                // bytes = mReadData.readInt();
                Log.i("***Bytes  data**", "" + bytes);// print 0
                Log.i("***Data input stream**", "" + input); // Here input is not null

                if (input != null) {
                    Log.i("***hello world**", "...");
                    while (isDeviceConnected) {
                        try {

                            bytes = input.read(buffer);     // this code never executes 

                            Log.i("**bytes data**", " " + bytes);

                            if (input != null) {
                                int len = input.readInt();
                                Log.i(TAG, "Response Length: " + len);

                                if (len > 65452) {// Short.MAX_VALUE*2
                                    Log.i(TAG, "Error: Accesory and app are not in sync.");
                                    continue;
                                }

                                Log.d(TAG, "Response Length: " + len);
                                Log.d(TAG, "Reading start time:" + System.currentTimeMillis());
                                byte[] buf = new byte[len];
                                Log.d(

                                        TAG, "input.available() " + input.available());
                                if (input.available() > 0) {

                                    input.readFully(buf);
                                    System.out.println("Output:=");


                                }

                                Log.d(TAG, "Reading end time:" + System.currentTimeMillis());
                            }

                        } catch (Exception e) {
                            Log.e(TAG, e.getMessage());
                            isDeviceConnected = false;

                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                isDeviceConnected = false;
                Log.e(TAG, "catch block 3 " + e.toString());

            }
        }

    }

}

1 个答案:

答案 0 :(得分:1)

ReadThread.Run() - 您必须移动代码

bytes = input.available (); // Always return 0

进入while循环

1,在检查null input

之前使用if (input! = null)

2,数据是连续发送的,很可能在运行线程时没有任何数据,因此你必须将input.available bytes = ();放入while循环中。

3,您可以尝试修改数据处理。原则上,快速读取临时缓冲区中的数据,然后移动到MainBuffer,然后用它进行操作。一个例子是c # .net Xamarin,但仅举例:

    private const int BTLPacketSize = 1024;
    private const int BTLdataSize = 65536;
    private System.Object InternaldataReadLock = new System.Object();
    private System.Object dataReadLock = new System.Object();
    private byte[] InternaldataRead = new byte[BTLPacketSize];//posila 64Byte pakety (resp. 62, protoze 2 jsou status bytes)
    private byte[] TempdataRead = new byte[BTLPacketSize];
    private byte[] dataRead = new byte[BTLdataSize];//Tyto pameti pouzivaji cursorc -> musim ohlidat preteceni pameti//Max. prenos rychlost je 115200 b/s. 
    private bool continueRead = true;

    public override void Run()
    {
        while (continueRead)
        {
            try
            {
                int readBytes = 0;
                lock (InternaldataReadLock)
                {//Quick reads data into bigger InternaldataRead buffer and next move only "received bytes" readBytes into TempdataRead buffer
                    readBytes = clientSocketInStream.Read(InternaldataRead, 0, InternaldataRead.Length);
                    Array.Copy(InternaldataRead, TempdataRead, readBytes);
                }
                if (readBytes > 0)
                {//If something reads move it from TempdataRead into main dataRead buffer a send it into MainThread for processing.
                    lock (dataReadLock)
                    {
                        dataRead = new byte[readBytes];
                        for (int i = 0; i < readBytes; i++)
                        {
                            dataRead[i] = TempdataRead[i];
                        }
                    }
                    Bundle dataBundle = new Bundle();
                    dataBundle.PutByteArray("Data", dataRead);
                    Message message = btlManager.sourceHandler.ObtainMessage();
                    message.What = 1;
                    message.Data = dataBundle;
                    btlManager.sourceHandler.SendMessage(message);
                }
            }
            catch (System.Exception e)
            {
                if (e is Java.IO.IOException)
                {
                  //.....
                }
            }
        }
    }