Android Development Learn cheats notes (19)

Source: Internet
Author: User
Tags getmessage

Yell at. It 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 scanning gun, the terminal can be connected to the device via Bluetooth, And the Bluetooth wireless scanning gun scan QR code or barcode can be the QR code or barcode data output to TextView.


Effect:

Listen to the effect is not feeling very good to do. Description under the function of the Bluetooth scanner, there are 2 frequently used modes-normal mode, SPP mode. Normal mode is equivalent to the Bluetooth connection, the scanner is equivalent to an external keyboard, the ability to scan code and then output the data to EditText (must get the focus). The SPP mode is used to simulate 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.

Not to show it on TextView. is not to sweep the code can only be output to the focus of the edittext. Then I'll set these two controls in the interface code. But edittext I set its height to 1DP. In addition to the developers themselves know there is a edittext outside. The user does not know that there is a edittext here.

You will then be able to get the content directly from the EditText and 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 to operate. Clear thinking, simple rough! But the problem is also very much, in case you have an interface a lot of edittext, such as landing interface. In addition to your own know that others can not see the edittext, but also have two edittext, once one gets the cursor, your scanner will lose its role, but also scare users jump. So this scheme is not suitable for apps that need to be pushed.


Scenario Two: Bluetooth transmission communication, the detailed 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 of the cut off, and then I do the corresponding operation. I read a lot of blogs, seriously. These blogs are all stereotyped. Let's put two more classics here.

1190000004899799


Http://www.cnblogs.com/wenjiang/p/3200138.html


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

Talk about button click events (can be changed according to your needs). Click into an activity to display all of the scanned Bluetooth devices--devicelistacitivty

One: Get the scanned Bluetooth device

What you need to do in devicelistactivity is to display the Bluetooth device that can be scanned in the ListView. You can omit this operation if you are sure you want to connect only one device and know the address of the device. Here when learning to use.

Import Android.app.activity;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 the form requestwindowfeature (window.feature_indeterminate_progress);        Set the form display mode to form 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 (R.id.button_scan); 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 (r.id.paired_devices);        Pairedlistview.setadapter (Mpaireddevicesarrayadapter); PairedlisTview.setonitemclicklistener (Mdeviceclicklistener);        Set up a new Find device list ListView Newdeviceslistview = (listview) Findviewbyid (r.id.new_devices);        Newdeviceslistview.setadapter (Mnewdevicesarrayadapter);        Newdeviceslistview.setonitemclicklistener (Mdeviceclicklistener);        The register receives a check to find the 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 (r.id.title_paired_devices). 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 form display find information setprogressbarindeterminatevisibility (true);        Settitle ("Find device ...");        Displays a list of other devices (not paired devices) Findviewbyid (r.id.title_new_devices). setvisibility (view.visible);        Close the re-performed service lookup if (mbtadapter.isdiscovering ()) {mbtadapter.canceldiscovery (); }//and start again mbtadaptEr.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 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);                    The assumption is that the pairing is skipped, has been shown, and the rest is displayed in the Add to list to display if (device.getbondstate ()! = bluetoothdevice.bond_bonded) {                Mnewdevicesarrayadapter.add (Device.getname () + "\ n" + device.getaddress ());                }else{//Join 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 (r.id.title_paired_d evices). SetvisibiLity (view.visible); }        }    };}


The code is affixed to the top. Detailed code explanation is also written in the code, in fact, I do not intend to do this operation, because for the only need to connect a Bluetooth device program, when I know the Bluetooth device MAC address I can directly find the device, there is no need to query. But I have to say it back. When the manufacturer does not give you the MAC address of the Bluetooth device. You're going to have to do this! So the recommendation is to take this step of the operation to do a good, detailed 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.


II: Transmit data I/O stream in fact, I'm a little worried about it when I do this, because for the socket. You have to at least write the socket and serversocket these two classes, detailed to be able to see my previous on the socket of the blog http://blog.csdn.net/cuihaoren01/article/details/45458265. But there's no way you can program the Bluetooth scanner. So there is no serversocket, as if most of the online Bluetooth transmission is and Ardunio transmission, I do not know that it can not be programmed so it is very worried about whether this can be achieved. Later I found a demo of the Bluetooth serial assistant on GitHub to try and find it capable of data transfer

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

Https://github.com/hzjerry/BluetoothSppPro.


There's no way. Practice is the only standard to test the truth that only can start their own test, then the second article has played a role, perhaps I do not need to implement 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 process of the connection is for example the following:

    1. First you have to get the device you need to connect to.

      (You will need the MAC address of your device here)

    2. You need to establish a socket that communicates with the server. Look at my previous blog client is the socket of communication through IP and port, the service is obtained by the way of accept (), and here This way is shot (feeling can not be said to shoot.) The Bluetooth gun is expected to have a serversocket, go to accept (), and the client has other ways 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;                }//Transfer data with the 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 the operation that connects the Bluetooth device, originally these operation I put in a thread to run. Unfortunately, it will be an error, and then I put it in the UI thread, the result is too, the time-consuming operation in the UI thread will not explode ... Put this issue on a temporary basis. Then another 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 = is.read (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, a detailed example of the source code download.


Source code Download: Known to connect to the device address, only need to change the address string in the Mainactivity value can be.

http://download.csdn.net/detail/cuihaoren01/9496677

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

http://download.csdn.net/detail/cuihaoren01/9496711


Android Development Learn cheats notes (19)

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.