Android Bluetooth development-communicates with the bluetooth module based on the eclipse project, androideclipse

Source: Internet
Author: User

Android Bluetooth development-communicates with the bluetooth module based on the eclipse project, androideclipse
Before February 20, I participated in a startup project of a junior senior student to build an intelligent car lock App that uses embedded technologies. The App requires Bluetooth, real-time location, and other technologies. So I checked several related technical articles, for more information, see! // First, let's talk about how to enable the bluetooth device and set the visible time:

Private void search () {descrithadapter adapter = descrithadapter. getdefaadapter adapter (); if (! Adapter. isEnabled () {adapter. enable ();} Intent enable = new Intent (effecthadapter. ACTION_REQUEST_DISCOVERABLE); enable. putExtra (effecthadapter. EXTRA_DISCOVERABLE_DURATION, 3600); // 3600 is the visible time of the bluetooth device startActivity (enable); Intent searchIntent = new Intent (this, ComminuteActivity. class); startActivity (searchIntent );}

First, you need to obtain a descrithadapter. You can use getdefaadapter adapter () to obtain the default Bluetooth adapter of the system. Of course, you can also specify it yourself, but this is really unnecessary, at least I don't need it. Then, check whether the Bluetooth of the mobile phone is enabled. If not, enable. Then we can set the visible time for the bluetooth device of the mobile phone to be customized.
After completing these necessary settings, we can officially start communicating with the bluetooth module:

Public class ComminuteActivity extends Activity {private extends threceiver extends er; private extends thadapter; private List <String> devices; private List <BluetoothDevice> deviceList; private Bluetooth client; private final String lockName = "BOLUTEK"; private String message = "000001"; private ListView; @ Override public void onCreate (Bundle savedInstanceState) {super. onC Reate (savedInstanceState); setContentView (R. layout. search_layout); listView = (ListView) this. findViewById (R. id. list); deviceList = new ArrayList <effecthdevice> (); devices = new ArrayList <String> (); effecthadapter = effecthadapter. getdefaadapter adapter (); descrithadapter. startDiscovery (); IntentFilter filter = new IntentFilter (effecthdevice. ACTION_FOUND); operator ER = new incluthreceiver (); r EgisterReceiver (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 (volume ER); super. onDestroy ();} private final Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg. what) {case Bluetooth. CONNECT_FAILED: Toast. makeText (ComminuteActivity. 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 successful", 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 extends threceiver extends BroadcastReceiver {@override public void onReceive (Context context, Intent intent) {String action = intent. getAction (); if (descrithdevice. ACTION_FOUND.equals (action) {descrithdevice device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE); if (isLock (device) {devices. add (device. getName ();} deviceList. add (device) ;}showdevices () ;}} private boolean isLock (descrithdevice 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 must first find 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 that, we must call a method:

 bluetoothAdapter.startDiscovery();

The startDiscovery () method is an Asynchronous Method that searches for other Bluetooth devices for 12 seconds. The search process is actually carried out in System Service. We can use the cancelDiscovery () method to stop this search. When the system searches for a bluetooth device, the system may send the following three broadcasts: ACTION_DISCOVERY_START (Start search), ACTION_DISCOVERY_FINISHED (end of search), and ACTION_FOUND (locate the device ). ACTION_FOUND: This is what we want. This Intent contains two extra fields: EXTRA_DEVICE and EXTRA_CLASS, which contain ththdevice and thclass respectively. EXTRA_DEVICE in thdevice is the device object we have searched. After the device is found, we can obtain the device name and address from the thdevice object.

We need to register broadcast in android, which is no exception here:

 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); receiver = new BluetoothReceiver(); registerReceiver(receiver, filter);

We need to cancel the broadcast registration. This can be done here:

   @Override    protected void onDestroy() {        unregisterReceiver(receiver);        super.onDestroy();    }

In this way, the broadcast will be automatically revoked at the end of the Activity, without manual execution.
Here I use a ListView to display the searched bluetooth device, but because only one Bluetooth device needs to be limited, I checked here to check whether the device is our target device. If yes,. Of course, to prevent repeated addition, it is necessary to add the following sentence:

 boolean isSingleDevice = devices.indexOf(device.getName()) == -1;

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

public void connect(final String message) {        Thread thread = new Thread(new Runnable() {            public void run() {                BluetoothSocket 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());                }

Before connecting to a device, you need a UUID. The so-called UUID is used for pairing. Its full name is Universally Unique Identifier, which is a 128-Bit String ID for Unique identification. Internet examples, including Google examples, all of their UUID can be used but I cannot use them, and such errors will be reported:

Service discovery failed

The possible cause is that the UUID that is the unique identifier does not work. Therefore, I use the reflection principle to allow the device to provide the UUID.

This error can also occur when we use a mobile phone as a client or a server, because what we need as a server is the same UUID:

mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);

As a client, it is like this:

device.createRfcommSocketToServiceRecord(MY_UUID);

When the two UUID want to establish the Rfcomm channel at the same time, we choose to implement them in both threads, but ignore one of the most important things: Only one role can be played at the same time! Therefore, the solution to this problem is to install the same application on the connected devices. Whoever initiates the connection is the client, but here I am a bluetooth module !! How can I install my application !! The solution is in the following communication.

Before connecting to a device, make sure that:

 bluetoothAdapter.cancelDiscovery();

This is to stop the search device, otherwise the connection may become very slow and easy to fail.
For Socket programming, we need to set some status values to identify the communication status, so that we can easily tune the error and put the connection in a thread, to allow this thread to communicate with the main thread of our program, we need to use Handle. For more information about Handle usage, see my other blog http://www.cnblogs.com/wenjiang/p/3180324.html.

When using Socket, I noticed a method: isConnect (), which returns a Boolean value, but this method is not required at all. If no error is reported for the Socket connection, it indicates that it is already connected.

In the example provided by Google, we can see that Google's programmers have a high level of programming, and we can learn some good coding habits, such as try .. variables defined in catch. We should try... declare a temporary variable before catch, and then try... assign a value to the variables we really want to use after catch. The advantage of this approach is that, if we use a real variable directly, when an exception occurs, the use of this variable will cause problems and it is difficult to troubleshoot, if it is a temporary variable, can I check the value of the variable to determine whether it is an error when the value is assigned.

The biggest impression in Google's example is the full exception check, but it is also because of this, which makes it less readable. The exception handling mechanism of java is sometimes not a comfortable thing to read the code. if you can avoid it, try to avoid it.

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

              if (isConnect) {                    try {                        OutputStream outStream = socket.getOutputStream();                        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. The usage is the same as that of the basic Socket, but when writing data, you need to convert the string to hexadecimal:

        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], 16);        }        return bytes;    }

Of course, here we only use the mobile phone as the client, but there is no need to create a server to receive the information sent by the bluetooth module. We only need to listen continuously and read the message of the other party in a loop.
A very simple program can implement functions like Bluetooth serial port assistant. Because it is the project code, it cannot be pasted with complete code, but it is basically above. You can refer to it. To use Bluetooth, the corresponding permissions are also essential:

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

This blog from: http://www.cnblogs.com/wenjiang/p/3200138.html

Projects can be used for reference, but opening a project has some problems.

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 subsequent projects will be uploaded to github.

Related Article

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.