In Bluetooth development, we have the following requirement: Our android client must always be connected to Bluetooth. When Bluetooth has data returned, the android client must collect data in a timely manner, when Bluetooth does not return data, we need to maintain the connection between the android client and Bluetooth. At this time, we need to use socket to connect to Bluetooth. The project uses http Round Robin to retrieve data, but it always has some drawbacks. So we used the socket method to obtain data.
Implementation steps: 1. Start a service to monitor whether data is returned. Once data is returned, a thread is started to process the data.
2. After processing the data, broadcast the notification to the UI.
During development, it is easy to generate bugs to listen to data cyclically. Because the socket in java is blocked by default, the loop may fail to exit. I used several status values to control them.
Service
/***** @ Author li * monitors the received data after the application is started */public class deletehread extends Service {private Socket socket; private String workStatus; // The current working status, null indicates processing is in progress, success indicates processing is successful, and 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 ("chlorophyll", "doListen ()"); // start listening for while (mainThreadFlag) {// start listening for 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 }}