Android Bluetooth SPP protocol communication

Source: Internet
Author: User

Get ready

1. Bluetooth serial port based on SPP protocol (Serial Port profile), can create serial port between Bluetooth devices for data transmission
2.SPP of UUID:00001101-0000-1000-8000-00805F9B34FB
3.Android mobile phones Generally actively connect the SPP protocol device to the client's role

Connection process

1. Detecting Bluetooth status
If Bluetooth is not turned on, turn on Bluetooth ~

Bluetoothadapter =Bluetoothadapter.getdefaultadapter (); @Overrideprotected voidOnresume () {Super. Onresume (); if(!bluetoothadapter.isenabled ()) {        //Open BlueToothIntent enablebtintent =NewIntent (bluetoothadapter.action_request_enable);    Startactivityforresult (Enablebtintent, REQUEST_ENABLE_BT); }} @Overrideprotected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {    if(Requestcode = = Request_enable_bt && ResultCode = =activity.result_canceled)        {Finish (); return; }}

2. Registering devices to search for broadcast information
Use Registerreceiver to register broadcastreceiver for messages such as search devices

Intentfilter Intentfilter =NewIntentfilter (); intentfilter.addaction (Bluetoothdevice.action_found); Intentfilter.addaction ( bluetoothadapter.action_discovery_finished); Registerreceiver (receiver, intentfilter);//receiverPrivate FinalBroadcastreceiver receiver =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {//Find a DeviceBluetoothdevice device =intent. Getparcelableextra (Bluetoothdevice.extra_device); if(Device.getbondstate ()! =bluetoothdevice.bond_bonded) {                //Device not pairedNewdevicearrayadapter.add (Device.getname () + "\ n" +device.getaddress ()); }Else {                //devices that have been pairedTextView tvpaired =(TextView) Findviewbyid (r.id.tv_paired);                Tvpaired.setvisibility (view.visible);                Lvpaireddevices.setvisibility (view.visible); Paireddevicearrayadapter.add (Device.getname ()+ "\ n" +device.getaddress ()); } log.i (TAG,"Name:" + device.getname () + "address" +device.getaddress ()); } Else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION) {//Search FinishLOG.I (TAG, "Search finish!"); }    }};

3. Using Blueadatper Search
Using the Bluetoothadapter search device, Bluetoothadapter.startdiscovery () will issue three broadcast messages during the search process:
Action_discovery_start: Start Search
Action_discovery_finished: End of search
Action_found: Find the device

@Override  Public void OnClick (View v) {    if  (bluetoothadapter.isdiscovering ()) {        Bluetoothadapter.canceldiscovery ();    }    Bluetoothadapter.startdiscovery ();}

4. Get the Bluetooth device information you have searched for
Get Bluetooth device information (such as name, Mac,rssi) found in Broadcastreceiver's OnReceive ()
5. Create a Bluetoothdevice object with the MAC address of the Bluetooth device:

Bluetoothdevice Romotedevice = Bluetoothadapter.getremotedevice (mdeviceaddress);

6. Derived from Bluetoothdevice Bluetoothsocket
Use the Bluetoothsocket Createrfcommsockettoservicerecord () method to select the Protocol/service for the connection, using SPP (uuid:0 0001101-0000-1000-8000-00805F9B34FB)

Try {    =catch  (IOException e) {    e.printstacktrace ();    Toast.maketext (This, "Socket init failed", Toast.length_short). Show ();

7. Use Bluetoothsocket to connect and read and write Bluetooth devices
Read and write can be attributed to a separate thread to implement ~

Try{bluetoothsocket.connect (); Toast.maketext ( This, "Connect Success", Toast.length_short). Show ();} Catch(IOException E2) {e2.printstacktrace (); Toast.maketext ( This, "Connect Failed", Toast.length_short). Show (); Try{bluetoothsocket.close (); Bluetoothsocket=NULL; } Catch(IOException e) {e.printstacktrace (); Toast.maketext ( This, "Socket close failed", Toast.length_short). Show (); }    return;}Try{InputStream=Bluetoothsocket.getinputstream ();} Catch(IOException E2) {e2.printstacktrace (); Toast.maketext ( This, "Get InputStream Failed", Toast.length_short). Show (); return;}Try{outputstream OS=Bluetoothsocket.getoutputstream (); byte[] Osbytes =Etinput.gettext (). toString (). GetBytes ();  for(inti = 0; i < osbytes.length; i++) {        if(Osbytes[i] = = 0x0a) n++; }    byte[] Osbytesnew =New byte[osbytes.length+N]; N= 0;  for(inti = 0; i < osbytesnew.length; i++) {        //mobile "\ n" is 0a,modify 0d 0a then send        if(Osbytesnew[i] = = 0x0a) {Osbytesnew[n]= 0x0d; N++; Osbytesnew[n]= 0x0a; }Else{Osbytesnew[n]=Osbytes[i]; } N++; } os.write (osbytesnew);} Catch(Exception e) {e.printstacktrace ();}

Android Bluetooth SPP protocol communication

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.