Android Development Learn cheats notes (19)

Source: Internet
Author: User

Roar, took 2 days finally made a similar to the Bluetooth Serial assistant function of the small program, in fact, is also the requirements of the internship company--there is a Bluetooth wireless scanner, the terminal can be connected to the device via Bluetooth, And the Bluetooth wireless scanning gun scan QR code or barcode can be two-dimensional code or barcode data output to TextView.


Listen to the effect is not feel good to do. Description under the function of the Bluetooth scanner, there are 2 commonly used modes-normal mode, SPP mode. Normal mode is equivalent to the Bluetooth connection, the scanner is equivalent to an external keyboard, you can scan code and then output the data to EditText (must get the focus). The SPP mode is used for analog serial communication, which in my opinion is equivalent to the developer mode ...

Scenario one: In the interface code under the hands and feet, is an opportunistic approach. is not to be displayed on the TextView, not to sweep the code can only be output to the focus of the edittext. Then I set the two controls in the interface code, but edittext I set its height to 1DP, except that the developer knows there is a edittext, and the user does not know there is a edittext. Then you can get the content directly from the EditText, and in the SetText to TextView.

The main code is edittext the Setonkeylistener in the set up just fine.

Et.setonkeylistener (New Edittext.onkeylistener ()       {       @Override       publicboolean OnKey (View v, int keycode, KeyEvent event)       {           tv.settext (Et.gettext ());           Returnfalse;       }            });

Simple operation, clear thinking, simple and rough! But there are a lot of problems, in case you have a interface many edittext, such as the landing interface, in addition to the one you know others can not see the edittext, there are two edittext, once one gets the cursor, your scanner will lose its role, but also scare users jump. So this scenario is not suitable for apps that need to be pushed.

Scenario Two: Bluetooth transmission communication, the specific use is the Android transmission stream mode, this way is very consistent with the requirements, just when you want to transfer data to the time to cut off your data, and then I do the corresponding operation. I read a lot of blogs, and honestly, these blogs are all stereotyped. Let's put two more classics here.



The concrete explanation I will say in the code, light says theory oneself dish's key foot. First of all talk about layout, super simple. A TextView, a edittext (test), a button (can be removed according to your needs). Code will not be posted, the time to directly send the project!

Say the button click event (can be modified according to your needs), click into an activity show all the scanned Bluetooth device--devicelistacitivty

One: Get the scanned Bluetooth device

The thing to do in Devicelistactivity is to show the Bluetooth device that can be scanned in the ListView, and you can omit this if you're sure you want to connect a device and know the address of the device. Here when learning to use.

Import;import Android.bluetooth.bluetoothadapter;import android.bluetooth.BluetoothDevice; Import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.os.bundle;import Android.util.log;import Android.view.View;import Android.view.window;import Android.view.view.onclicklistener;import Android.widget.adapterview;import Android.widget.arrayadapter;import Android.widget.button;import Android.widget.listview;import Android.widget.textview;import Android.widget.adapterview.onitemclicklistener;public class DeviceListActivity    Extends Activity {//debug with private static final String TAG = "devicelistactivity";    Private static Final Boolean D = true;    Return data label public static String extra_device_address = "Device Address";    Member domain private bluetoothadapter mbtadapter;    Private arrayadapter<string> Mpaireddevicesarrayadapter; Private Arrayadapter<string> MnewdeviceSarrayadapter;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);  Create and Display window Requestwindowfeature (window.feature_indeterminate_progress);        Set the window display mode to Window mode Setcontentview (r.layout.device_list);        Set the default return value to cancel Setresult (activity.result_canceled);        Set the Scan button response button Scanbutton = (button) Findviewbyid (; Scanbutton.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {dodiscovery (                );            V.setvisibility (View.gone);        }        });        Initial enable device storage array mpaireddevicesarrayadapter = new Arrayadapter<> (this, r.layout.device_name);        Mnewdevicesarrayadapter = new Arrayadapter<> (this, r.layout.device_name);        Set up a list of units that have been provisioned ListView Pairedlistview = (listview) Findviewbyid (;        Pairedlistview.setadapter (Mpaireddevicesarrayadapter); PairedlisTview.setonitemclicklistener (Mdeviceclicklistener);        Set up a new Find device list ListView Newdeviceslistview = (listview) Findviewbyid (;        Newdeviceslistview.setadapter (Mnewdevicesarrayadapter);        Newdeviceslistview.setonitemclicklistener (Mdeviceclicklistener);        Register to receive check find device ACTION receiver intentfilter filter = new Intentfilter (bluetoothdevice.action_found);        This.registerreceiver (mreceiver, filter);        Register Find End ACTION receiver filter = new Intentfilter (bluetoothadapter.action_discovery_finished);        This.registerreceiver (mreceiver, filter);        Get local bluetooth handle mbtadapter = Bluetoothadapter.getdefaultadapter ();        Get a list of paired Bluetooth devices//set<bluetoothdevice> paireddevices = Mbtadapter.getbondeddevices (); Add paired devices to the list and show//if (Paireddevices.size () > 0) {//Findviewbyid ( Setvisibil        ity (view.visible);      for (Bluetoothdevice device:paireddevices) {//   Mpaireddevicesarrayadapter.add (Device.getname () + "\ n" + device.getaddress ());        }//} else {//String nodevices = "No devices has been paired";        Mpaireddevicesarrayadapter.add (nodevices);        }} @Override protected void OnDestroy () {Super.ondestroy ();        Close service Find if (mbtadapter! = null) {mbtadapter.canceldiscovery ();    }//Logoff action receiver This.unregisterreceiver (mreceiver);    public void OnCancel (View v) {finish ();        }/** * Start service and Device lookup */private void Dodiscovery () {if (D) log.d (TAG, "dodiscovery ()");        In the window display find information setprogressbarindeterminatevisibility (true);        Settitle ("Find device ...");        Displays a list of other devices (not paired devices) Findviewbyid ( setvisibility (view.visible);        Close the re-performed service lookup if (mbtadapter.isdiscovering ()) {mbtadapter.canceldiscovery (); }//and start mbtadapte againR.startdiscovery (); }//Select device response function private Onitemclicklistener Mdeviceclicklistener = new Onitemclicklistener () {public void onIt Emclick (adapterview<?> av, View v, int arg2, long arg3) {//Prepare to connect device, turn off service lookup Mbtadapter.canceldi            Scovery ();            Get the MAC address String info = ((TextView) v). GetText (). toString ();            String address = info.substring (Info.length ()-17);            Sets the return data Intent Intent = new Intent ();            Intent.putextra (extra_device_address, ADDRESS);            Set the return value and end the program Setresult (ACTIVITY.RESULT_OK, intent);        Finish ();    }    }; Find to device and search complete action listener private final Broadcastreceiver mreceiver = new Broadcastreceiver () {@Override PU            Blic void OnReceive (context context, Intent Intent) {String action = intent.getaction ();    Find to Device ACTION if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {//Get Bluetooth device            Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device);                    If it is paired, it is skipped, has been displayed, and the remainder is displayed in the Add to list if (Device.getbondstate ()! = bluetoothdevice.bond_bonded) {                Mnewdevicesarrayadapter.add (Device.getname () + "\ n" + device.getaddress ());                }else{//Add to paired device List Mpaireddevicesarrayadapter.add (Device.getname () + "\ n" + device.getaddress ()); }//Search complete Action} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (action                ) {setprogressbarindeterminatevisibility (false);                Settitle ("Select the device to be connected");                    if (mnewdevicesarrayadapter.getcount () = = 0) {String nodevices = "No new device found";                Mnewdevicesarrayadapter.add (nodevices); }//if (Mpaireddevicesarrayadapter.getcount () > 0)//Findviewbyid ( evices). Setvisibility (view.visible); }        }    };}

The code is affixed to the above, the specific code explanation is also written in the code, in fact, I do not intend to do this operation, because for a program that only needs to connect a Bluetooth device, when I know the Bluetooth device MAC address I can directly find the device, there is no need to query. But have to say back, when the manufacturer did not give you the Bluetooth device MAC address. You're going to have to do this! So the recommended words or take this step to do a good job, how to operate or to see the project requirements. As for how to find the status of Bluetooth devices and Bluetooth devices, the above code is very detailed, combined with my previous recommendation of the two articles is very understood.

Two: Data transfer I/O stream in fact, when doing this, I am a little worried about the implementation, because for the socket, you have to write at least the socket and serversocket these two classes, specific can see my previous to the socket of the blog http://, but there's no way you can program the Bluetooth scanner, so there's no serversocket, It seems that most of the online Bluetooth transmission is and Ardunio transmission, I do not know if it can be programmed so it is very worried that such a write could be achieved. I found a demo of the Bluetooth serial assistant on GitHub to try and find it can be transferred

But because the code it writes is too complex to be used directly by a framework, it does not delve into it. Https://

No way, practice is the only criterion to test the truth that can only start their own testing, the second article has played a role, perhaps I do not need to implement the ServerSocket server programming, in the use of Bluetooth serial assistant test, you paired on the connection can be directly used, I just need to be able to connect with it (the Bluetooth gun). The procedure for connecting is as follows:

    1. First you have to get the device you need to connect to. (You need the MAC address of your device here)
    2. you need to establish a socket to communicate with the server, see my previous Blog client is the socket of communication through IP and port, the server is obtained by the way of accept (), And here this way was killed (feel can not say shoot, it is estimated that there is a serversocket Bluetooth gun, to accept (), and the client has other methods to get the socket of communication. )
    3. socket.connect ()
 Btn.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                Mbluetoothdevice = Mbluetoothadapter.getremotedevice (address);                            try{Mbluetoothsocket = Mbluetoothdevice.                Createrfcommsockettoservicerecord (uuid.fromstring (My_uuid)); }catch (IOException e) {toast.maketext (Mainactivity.this, "pairing failed due to:" + e.getmessage (), Toast.length_sh                    ORT). Show ();                LOG.E ("Process", "the reason for failure is:" + e.getmessage ());                    }//Connect with the device try{mbluetoothsocket.connect (); Toast.maketext (Mainactivity.this, "Connect" + mbluetoothdevice.getname () + "Success", Toast.length_short).                    Show ();                LOG.E ("TAGGGAGGAGGHG", "connection process"); } catch (IOException e) {Try{Toast.maketext (mainactivity.this, "Connection failed due to:" + e.getmessage (), Toast.length_short). Show ();                        Mbluetoothsocket.close ();                        Mbluetoothsocket = null;                    LOG.E ("Connection Failed", "Connection failed due to:" + e.getmessage ());                    } catch (IOException E1) {e1.printstacktrace ();                } return;                }//data transfer with device try{is = Mbluetoothsocket.getinputstream ();                    }catch (IOException e) {toast.maketext (Mainactivity.this, "failed to receive data", Toast.length_short). Show ();                Return                    } if (ready_receive = = False) {Readthread.start ();                Ready_receive = true;                }else {isreceiving = true; }            }        });

This part is connected to the operation of the Bluetooth device, originally these operations I put in a thread to execute, but unfortunately it will be error, and then I put in the UI thread, the result is too, the time-consuming operation in the UI thread will not explode ... Let's put this problem for the time being. And then there's a thread readthread

Thread readthread = new Thread () {public void run () {int num = 0;            byte[] buffer = new byte[1024];            byte[] buffer_new = new byte[1024];            int n = 0;            isreceiving= true; while (true) {try {while (is.available () = = 0) {while (Isreceivin                        G = = False) {}} while (true) {num = (buffer);                        n = 0;                        String s0 = new string (buffer, 0, num);//fmsg + = S0;                                for (int i = 0; i < num; i++) {if ((buffer[i] = = 0x0d) && (buffer[i + 1] = = 0x0a)) {                                Buffer_new[n] = 0x0a;                            i++;                            }else{Buffer_new[n] = buffer[i];            } n++;            } string s = new string (buffer_new, 0, N);                        Receive_msg + = s;                    if (is.available () = = 0) break;                } handler.sendmessage (Handler.obtainmessage ()); }catch (IOException e) {}}};

This completes the Bluetooth Serial assistant part of the function, specific examples see source download.

SOURCE download: Known to connect to the device address, only need to modify the address string in the Mainactivity value on it.

Scan your Bluetooth device, select the device you want to connect to, and transfer it.

Android Development Learn cheats notes (19)

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: 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.