============ Problem Description ============
I looked at Google's Bluetoothchat demo, where it put Bluetooth to establish a client-side connection is also placed in the sub-thread execution.
My current program, Bluetooth to establish the connection step is in the UI thread, but bluetoothsocket receive the data part is in the sub-thread, but now encountered a problem, after opening the sub-thread, the main thread does not go down execution.
According to my log records, Connectedthread.run (), followed by the log method Loghelper.write ("has already run the child thread"), has been stuck, will not be executed.
Should I say that the main thread should not continue to execute after the child threads run?
The code is as follows
The main thread class, which is the interface that triggers this start () method in a Click event of a button
public void Start () {loghelper.write ("Start connecting Bluetooth device"); Bluetoothadapter bluetoothadapter = Bluetoothadapter.getdefaultadapter (); Bluetoothdevice device = Bluetoothadapter.getremotedevice (this.deviceaddress); UUID deviceuuid=uuid.fromstring ("00001101-0000-1000-8000-00805F9B34FB"); try{this.clientsocket= Device.createrfcommsockettoservicerecord (Deviceuuid); This.clientSocket.connect (); Loghelper.write ("Connection succeeded"); This.connectedthread=new Connectedthread (Clientsocket); byte[] Buffer=new byte[]{0x3a,0x50 , 0x00, (byte) 0x8a};connectedthread.write (buffer); Loghelper.write ("Write to Start command"); Connectedthread.run (); Loghelper.write ("Child threads already Running");} catch (IOException e) {loghelper.write (E.getmessage ());}}
Sub-Threading Class
private class connectedthread extends thread{private final bluetoothsocket mmsocket; private final inputstream mminstream; private final OutputStream mmOutStream; public connectedthread (Bluetoothsocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = Socket.getinputstream (); tmpout = socket.getoutputstream (); } catch ( Ioexception e) { loghelper.write (E.getMessage ()); } mmInStream = tmpIn; mmoutstream = tmpout; } Public void run () { byte[] buffer = new byte[1024]; int bytes; while (True) { try { bytes = Mminstream.read (buffer); //Processing Data writetobuffer (Buffer,seBuffer,readPointer, Writepointer,bytes); readbuffer (Sebuffer,readpointer,writepointer); } catch (ioexception e) { loghelper.write (E.getmessage ()); break; } } } //writes data to the Bluetooth communication pipeline public void write ( Byte[] buffer) { try { Mmoutstream.write (buffer); } catch (ioexception e) {} }}
============ Solution 1============
Connectedthread.run ();
should be written
Connectedthread.start ();
Run () is returned only at the end of the child thread, and your child thread logic is a while loop, which of course is blocked.
After the Bluetooth connection, the boot child thread receives the data, the main thread is stuck