Android Bluetooth (2) -- receive data

Source: Internet
Author: User

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




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.