In the development of Bluetooth, we have this kind of demand: our androidclient to always keep the connection with Bluetooth, when the Bluetooth has data back, Androidclient will be timely to collect data, When Bluetooth has no data to return, we should keep the connection between Androidclient and Bluetooth. At this point we will take the socket to achieve the connection between Bluetooth. Doing projects using HTTP polling to get data, but found that there are always some drawbacks. Then the socket is used to get the data.
Implementation steps: 1, start a service to listen for data return. Start a thread to process the data once the data is returned
2, processing the data, through the broadcast to notify the UI.
In development, it is assumed that the use of loops to listen to data is very easy to produce some bugs. Because sockets in Java are blocked by default, loops can cause the exit to fail. I used a couple of state values to control it myself.
Service class
/** * * @author Li * is responsible for listening for receiving data after starting the application */public class Receivethread extends Service { private socket socket; Private String workstatus;//The current working state, null means processing, success indicates processing succeeded, failure indicates processing failed public static Boolean Mainthreadflag = true; ; Status @overridepublic IBinder onbind (Intent Intent) {//TODO auto-generated method Stubreturn null;} private void Dolisten () {LOG.D ("CHL", "Dolisten ()"),//Start listening while (Mainthreadflag) { //start listening data new Thread (new Threadreadwritersocketserver (receivethread.this, Socket));}}}
Thread
public class Threadreadwritersocketserver implements Runnable{private Socket client=null;private Context context= Null;public threadreadwritersocketserver (Context context,socket client) {this.context=context;this.client=client;} @Overridepublic void Run () {Receive ();} private void Receive () {//Process data}}