Android Bluetooth (ii)--Receive data

Source: Internet
Author: User

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}}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.