Android--------bluetooth® bluetooth

Source: Internet
Author: User

What is Bluetooth?

It can also be said that Bluetooth technology. The so-called Bluetooth technology, actually a short-range radio technology, was invented by Ericsson company. The use of "Bluetooth" technology can effectively simplify communication between mobile devices such as handheld computers, laptops and mobile phone devices, and can also successfully simplify communication between these equipment and internet Internet, so that the transmission between these modern communications equipment and the Internet becomes more rapid and efficient , widening the road for wireless communication.

Android 4.3 (API level 18) has started to introduce the core features of Bluetooth low energy (BLE, Bluetooth) and provides APIs for applications to scan Bluetooth devices, query services, and read and write devices through these APIs chara Cteristics (attribute characteristics) and other operations.

The Bluetooth protocol used by Android BLE is the GATT protocol, and the details of this agreement can be found in the official Bluetooth documentation. Here's a map of the official website that describes some of the professional terms of Bluetooth low energy that we need to know about in Android development.

Android provides bluetoothadapter class Bluetooth communication. Getdefaultadapter () by invoking the static method of the created object. Its syntax is given below.

   Mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();

First, you need to add the Androidmanifest.xml file to the action Bluetooth permission.

<!-- This permission is required to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transmitting data. -     < android:name = "Android.permission.BLUETOOTH" />   <!-- //If you want your app to boot up the device to discover or manipulate Bluetooth settings, you must declare the Bluetooth_admin license  -    <  android:name= "Android.permission.BLUETOOTH_ADMIN"/>

Verify that Bluetooth is turned on and the open prompt is turned on

if (! mbluetoothadapter.isenabled ()) {      // Popup dialog box prompts the user to open after      New Intent (bluetoothadapter.action_request_enable);      Startactivityforresult (enabler, request_enable);               }

Activity code:

/*** Created by Zhangqie on 2017/11/28.*/ Public classBluetoothactivityextendsAppcompatactivityImplementsview.onclicklistener{Private Static Final intrequest_enable = 1; Private Static FinalString TAG = demo1activity.class. GetName ();    Bluetoothadapter Mbluetoothadapter;    TextView tvdevices; @Overrideprotected voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.LAYOUT.DEMO1);    Initview (); }    Private voidInitview () {Findviewbyid (R.ID.BTN1). Setonclicklistener ( This); Tvdevices=(TextView) Findviewbyid (R.id.textblue); Mbluetoothadapter=Bluetoothadapter.getdefaultadapter (); if(!mbluetoothadapter.isenabled ()) {            //Pop-up dialog prompts the user to be open afterIntent Enabler =NewIntent (bluetoothadapter.action_request_enable);            Startactivityforresult (enabler, request_enable); //Do not prompt, directly open, do not recommend the following methods, some phones will have problems. //mbluetoothadapter.enable ();} showbluetooth (); }    Private voidStartsearthbltdevice () {//If you are currently searching, cancel the search first        if(Mbluetoothadapter.isdiscovering ()) {mbluetoothadapter.canceldiscovery (); }        //Open SearchMbluetoothadapter.startdiscovery (); }    Private voidShowboradcast () {//set up broadcast information filteringIntentfilter filter =NewIntentfilter (); Filter.addaction (bluetoothdevice.action_found);//every search to a device sends a broadcastFilter.addaction (bluetoothadapter.action_discovery_finished);//send this broadcast when all searches have been completedFilter.setpriority (Integer.max_value);//setting the priority level//Register a Bluetooth search broadcast recipient to receive and process search results         This. Registerreceiver (receiver, filter); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btn1:showboradcast ();                Startsearthbltdevice ();  Break; }    }    //get Bluetooth devices that are already paired    Private voidShowbluetooth () {Set<BluetoothDevice> paireddevices =mbluetoothadapter.getbondeddevices (); if(Paireddevices.size () > 0) {             for(Bluetoothdevice device:paireddevices) {tvdevices.append (Device.getname ()+ ":" +device.getaddress ()); }        }    }    /*** Define broadcast receivers*/    Private FinalBroadcastreceiver receiver =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {Bluetoothdevice device=Intent.getparcelableextra (Bluetoothdevice.extra_device); if(Device.getbondstate ()! =bluetoothdevice.bond_bonded) {log.i (TAG,":"+device.getaddress ()); Tvdevices.append (Device.getname ()+ ":"+device.getaddress ()); }            } Else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION)) {Toast.maketext (demo1activity. This, "Completed Search", Toast.length_long). Show (); //Finished Search            }        }    };}

Get:

Android--------bluetooth® bluetooth

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.