Android Bluetooth Development---Communication with Bluetooth module based on Eclipse project

Source: Internet
Author: User

Before 2017.10.20 to participate in a Junior Senior entrepreneurship project, do a smart lock app, using embedded technology, app needs Bluetooth, real-time location technology, so check a few related technical articles, to this reference!Let's talk about how to turn on the Bluetooth device and set the visible time:
private void Search () {        Bluetoothadapter adapter = Bluetoothadapter.getdefaultadapter ();        if (!adapter.isenabled ()) {            adapter.enable ();        }        Intent enable = new Intent (bluetoothadapter.action_request_discoverable);        Enable.putextra (bluetoothadapter.extra_discoverable_duration, 3600); 3600 for Bluetooth device visible time        startactivity (enable);        Intent searchintent = new Intent (this, comminuteactivity.class);        StartActivity (searchintent);    }

First, you need to get a bluetoothadapter, you can get the system default Bluetooth adapter through Getdefaultadapter (), of course, we can also specify, but this is really not necessary, at least I do not need. Then we check whether Bluetooth on the phone is turned on, and if not, turn it on by the Enable () method. Then we set the mobile phone Bluetooth device visible, the visible time can be customized.
With these necessary settings in place, we can formally start communicating with the Bluetooth module:

public class Comminuteactivity extends Activity {private bluetoothreceiver receiver;    Private Bluetoothadapter Bluetoothadapter;    private list<string> devices;    Private list<bluetoothdevice> devicelist;    Private Bluetooth client;    Private final String lockname = "Bolutek";    Private String message = "000001";    Private ListView ListView;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.search_layout);        ListView = (ListView) This.findviewbyid (R.id.list);        Devicelist = new arraylist<bluetoothdevice> ();        devices = new arraylist<string> ();        Bluetoothadapter = Bluetoothadapter.getdefaultadapter ();        Bluetoothadapter.startdiscovery ();        Intentfilter filter = new Intentfilter (bluetoothdevice.action_found);        Receiver = new Bluetoothreceiver ();        Registerreceiver (receiver, filter); Listview.setonitemclicklistener (nEW Adapterview.onitemclicklistener () {@Override public void Onitemclick (adapterview<?> parent                , view view, int position, long id) {Setcontentview (r.layout.connect_layout);                Bluetoothdevice device = devicelist.get (position);                Client = new Bluetooth (device, handler);                try {client.connect (message);                } catch (Exception e) {log.e ("TAG", e.tostring ());    }            }        });        } @Override protected void OnDestroy () {unregisterreceiver (receiver);    Super.ondestroy ();            } private Final Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) { Switch (msg.what) {case Bluetooth.CONNECT_FAILED:Toast.makeText (comminuteactivi                    Ty.this, "Connection Failed", Toast.length_long). Show (); try {client.connect (mesSAGE);                    } catch (Exception e) {log.e ("TAG", e.tostring ());                } break; Case Bluetooth.CONNECT_SUCCESS:Toast.makeText (comminuteactivity.this, "Connection succeeded", Toast.length_long). Show (                    );                Break                    Case Bluetooth.READ_FAILED:Toast.makeText (Comminuteactivity.this, "read failed", Toast.length_long). Show ();                Break                    Case Bluetooth.WRITE_FAILED:Toast.makeText (Comminuteactivity.this, "Write Failed", Toast.length_long). Show ();                Break                    Case Bluetooth.DATA:Toast.makeText (comminuteactivity.this, Msg.arg1 + "", Toast.length_long). Show ();            Break    }        }    };  Private class Bluetoothreceiver extends Broadcastreceiver {@Override public void onreceive (context context, Intent Intent) {String action = iNtent.getaction (); if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {Bluetoothdevice device = Intent.getparcelableextra (Bluet                Oothdevice.extra_device);                if (Islock (device)) {Devices.add (Device.getname ());            } devicelist.add (device);        } showdevices (); }} Private Boolean Islock (Bluetoothdevice device) {Boolean islockname = (Device.getname ()). Equals (Lockname)        ;        Boolean issingledevice = Devices.indexof (Device.getname ()) = =-1;    return islockname && Issingledevice; } private void Showdevices () {arrayadapter<string> adapter = new Arrayadapter<string> (This, Android .        R.layout.simple_list_item_1, devices);    Listview.setadapter (adapter); }}

To communicate with any Bluetooth module, you first need to search for the device:

Private class Bluetoothreceiver extends Broadcastreceiver {        @Override public        void OnReceive (context context, Intent Intent) {            String action = intent.getaction ();            if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {                Bluetoothdevice device = Intent.getparcelableextra ( Bluetoothdevice.extra_device);                if (Islock (device)) {                    Devices.add (Device.getname ());                }                Devicelist.add (device);            }            Showdevices ();        }    }

Before we do that, we have to call a method first:

Bluetoothadapter.startdiscovery ();

The StartDiscovery () method is an asynchronous method that searches for other Bluetooth devices for a duration of 12 seconds. The search process is actually done in the system service, and we can stop the search by using the Canceldiscovery () method. During the system searching for a Bluetooth device, the system may send the following three broadcasts: Action_discovery_start (Start Search), action_discovery_finished (search end) and Action_found (Find device). Action_found This is what we want, this intent contains two EXTRA Fields:extra_device and Extra_class, including Bluetoothdevice and Bluetoothclass, respectively, The Extra_device in Bluetoothdevice is the device object we searched for. After confirming the search to the device, we can get the name and address of the device from the resulting Bluetoothdevice object.

The use of radio in Android requires us to register, and here is no exception:

Intentfilter filter = new Intentfilter (bluetoothdevice.action_found); Receiver = new Bluetoothreceiver (); Registerreceiver (receiver, filter);

Broadcast registration requires us to revoke this, which can be placed here:

   @Override    protected void OnDestroy () {        unregisterreceiver (receiver);        Super.ondestroy ();    }

This will automatically revoke the broadcast at the end of the activity without the need for us to do it manually.
I'm using a ListView here to show the bluetooth device I've searched for, but because I need to qualify only one Bluetooth device, check here to see if the device is our target device, and if so, add it. Of course, in order to prevent duplication of additions, it is necessary to add such a sentence:

Boolean issingledevice = Devices.indexof (Device.getname ()) = =-1;

After the device is searched, we will connect to the device.

public void Connect (final String message) {        thread thread = new Thread (new Runnable () {public            void run () {                Bl Uetoothsocket tmp = NULL;                Method method;                try {                    method = Device.getclass (). GetMethod ("Createrfcommsocket", New Class[]{int.class});                    TMP = (bluetoothsocket) method.invoke (device, 1);                } catch (Exception e) {                    setState (connect_failed);                    LOG.E ("TAG", e.tostring ());                }                socket = tmp;                try {                    socket.connect ();                    Isconnect = true;                } catch (Exception e) {                    setState (connect_failed);                    LOG.E ("TAG", e.tostring ());                }

A UUID is required before connecting the device, and the so-called UUID is used for pairing, the full name is universally unique Identifier, which is a 128-bit string ID for unique identification. Examples of the Internet, including Google's example, their UUID is said to be able to use but I can not use, will report such errors:

Service Discovery failed

The reason may be that the UUID as a unique identifier does not work, so I use the principle of reflection to let the device provide its own UUID.

This error is also possible when we use the phone as a client as a service, as we need the same UUID as a server:

Madapter.listenusingrfcommwithservicerecord (NAME, My_uuid);

As a client, this is the case:

Device.createrfcommsockettoservicerecord (MY_UUID);

When the two UUID wants to build the Rfcomm channel at the same time, our choice is implemented in two threads, but ignores one of the most important things: the same time can only act as a role! So, the way to solve this problem is to install the same application on our connected devices, who first initiates the connection who is the client, but I am here is the Bluetooth module AH!! How can I install my application?! The solution is in the communication below.

One more thing to do before you connect your device is to ensure that:

Bluetoothadapter.canceldiscovery ();

This is to stop the search device, or the connection may become very slow and easy to fail.
For the socket programming, we need to set some status values to identify the state of the communication, so that we can debug the error, and the connection should be placed in a thread, to allow the thread to communicate with our program's main thread, we need to use handle, about the use of handle, can refer to my other blog http://www.cnblogs.com/wenjiang/p/3180324.html, here not much to say.

In using the socket, I notice a method: Isconnect (), it returns a Boolean value, but there is no need to use this method, the socket connection if there is no error, it is already connected.

In the example provided by Google, we can see that the program level of Google programmers is very high, some good coding habits we can learn, like in the try. Variables that are defined in catch, we should declare a temporary variable before try...catch, and then assign a value to the variable we really want to use after Try...catch. The advantage of this approach is that if we are directly using real variables, when there is an exception, the use of the variable will be problematic, and difficult to troubleshoot, if it is a temporary variable, I can check the value of the variable to determine whether it is an assignment error.

Google's example of the biggest sentiment is full of abnormal check, but also because of this, resulting in its low readability. Java exception handling mechanism Sometimes it's really not a comfortable thing to read code, and avoid it as much as possible.

If there is no problem with the connection, we can communicate with the Bluetooth module:

              if (isconnect) {try {outputstream OutStream = socket.getoutputst                        Ream ();                    Outstream.write (gethexbytes (message));                        } catch (IOException e) {setState (write_failed);                    LOG.E ("TAG", e.tostring ());                        } try {InputStream InputStream = Socket.getinputstream ();                        int data;                                while (true) {try {data = Inputstream.read ();                                Message msg = Handler.obtainmessage ();                                Msg.what = DATA;                                MSG.ARG1 = data;                            Handler.sendmessage (msg);                                } catch (IOException e) {setState (read_failed); LOG.E ("TAG", E.tostring ());                            Break                        }}} catch (IOException e) {setState (write_failed);                    LOG.E ("TAG", e.tostring ());                    }} if (socket! = NULL) {try {socket.close ();                    } catch (IOException e) {log.e ("TAG", e.tostring ()); }                }            }        }

This includes writing and reading, and the usage is the same as the basic socket, but when writing, you need to convert the string to 16 binary:

        Private byte[] Gethexbytes (String message) {        int len = Message.length ()/2;        char[] chars = Message.tochararray ();        string[] hexstr = new String[len];        byte[] bytes = new Byte[len];        for (int i = 0, j = 0; j < len; i + = 2, j + +) {            Hexstr[j] = "" + chars[i] + chars[i + 1];            BYTES[J] = (byte) integer.parseint (Hexstr[j], +);        }        return bytes;    }

Of course, this is just the mobile phone as the client, but the receiving Bluetooth module sent over the information is not necessary to deliberately create the service side, we only need a constant listening and read the other side of the message loop on the line.
Very simple program can be implemented like Bluetooth serial assistant function, because it is the code of the project, can not paste the complete code, but basically all on the above, we can refer to. To use Bluetooth, the appropriate permissions are also necessary:

<uses-permission android:name= "Android.permission.BLUETOOTH"/> <uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>

This blog was written by: http://www.cnblogs.com/wenjiang/p/3200138.html

Projects can be borrowed, but opening the project is slightly problematic

Put the code on GitHub: Https://github.com/wenjiang/Bluetooth2.git

On this basis, you can use Android studio to try to modify the code to establish Bluetooth communication!

The follow-up project is uploaded to GitHub.

Android Bluetooth Development---Communication with Bluetooth module based on Eclipse project

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.