Android Bluetooth Module Base operation

Source: Internet
Author: User

No previous contact with the Bluetooth module, in the process of learning from a lot of predecessors experience. This session mainly includes the following functions:

1. Detect if there is a Bluetooth module

2. Turn Bluetooth on and off

3. Bluetooth device paired with this machine

4, native Bluetooth visibility settings

5. Scan around Bluetooth devices

about how to communicate between Bluetooth devices next time to tidy up. Let's start with the introduction.

1.1, first to add the operation of Bluetooth permissions in the configuration file

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

The first permission controls the detection, opening, and closing of the Bluetooth module. A second permission is required if you need to scan for more features, such as a nearby Bluetooth device.

1.2. Specific code

Btn_check.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubbluetoothadapter bltadapter = Bluetoothadapter.getdefaultadapter ();//Native Adapter if (Bltadapter = = null) {Toast.maketext (Getapplicationcontext (), "This machine does not have a Bluetooth device", 0). Show (); Tv_result.settext ("This machine does not have a Bluetooth device");} Else{toast.maketext (Getapplicationcontext (), "This machine has a Bluetooth device", 0). Show (); Tv_result.settext ("This machine has a Bluetooth device"); if (! Bltadapter.isenabled ())//detect if Bluetooth is turned on {Intent Intent = new Intent (bluetoothadapter.action_request_enable);// Turn on Bluetooth startactivity (intent);} Set <BluetoothDevice> bltdevices = bltadapter.getbondeddevices (); String address = "Paired Bluetooth device"; if (Bltdevices.size () >0) {for (Iterator Iterator = Bltdevices.iterator (); iterator.hasnext ();)//iterator collects the adapted Bluetooth address and prints {bluetoothdevice Bltdevice = (bluetoothdevice) iterator.next (); address = address+ "\ n" + Bltdevice.getaddress (). toString ();} Tv_result.settext (address);}}});

1.3 Results

A) initial status Bluetooth not turned on

b) Request to turn on Bluetooth

c) Show paired devices

2.1, set the Bluetooth visibility, here need to explain is, according to the official introduction

The current default was seconds, and requests over seconds would be capped. These values could change.

That is, the device visible time defaults to 120s, the maximum is 300s, if the parameter is greater than 300 equals 300.

The code is as follows

Btn_discover.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method Stubintent Intent = new Intent (bluetoothadapter.action_request_discoverable); Intent.putextra ( Bluetoothadapter.extra_discoverable_duration, 400);//400 is a setting of more than 300 of the visible time equals 300startActivity (intent);});

2.2. The results are as follows

3, scan nearby Bluetooth. Bluetooth itself uses a broadcast mechanism. The code is as follows:

Intentfilter intentfilter = new Intentfilter (bluetoothdevice.action_found);//Filter Bluetoothreceiver BluetoothReceiver = new Bluetoothreceiver (); Registerreceiver (Bluetoothreceiver, intentfilter);//Registered Recipient private class Bluetoothreceiver Extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) {//TODO auto-generated method s Tubstring action = intent.getaction (); if (BluetoothDevice.ACTION_FOUND.equals (action)) {Bluetoothdevice Bltdevice = Intent.getparcelableextra (bluetoothdevice.extra_device); result1 = result1+ "\ n" +bltdevice.getaddress (). ToString () ; Tv_result.settext (RESULT1);}} Btn_scan.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubbltadapter.startdiscovery ();}});                

3.2. The results are as follows

4. Finally attach all the code after the change, welcome to criticize.

Java code

Package Com.example.bluetooth;import Java.util.iterator;import Java.util.set;import Android.support.v7.app.actionbaractivity;import Android.annotation.suppresslint;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.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;import Android.widget.toast;public class Mainactivity extends actionbaractivity {TextView tv_result; Button Btn_check; Button Btn_scan; Button Btn_discover; String RESULT1 = "Surround Bluetooth device"; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); final Bluetoothadapter bltadapter = Bluetoothadapter.getdefaultadapter (); Intentfilter intentfilter = new Intentfilter (bluetoothdevice.action_found); BlUetoothreceiver bluetoothreceiver = new Bluetoothreceiver () Registerreceiver (Bluetoothreceiver, intentFilter); tv_ result = (TextView) Findviewbyid (r.id.checkresult); btn_check = (Button) Findviewbyid (R.ID.CHECKBLT); Btn_scan = (Button ) Findviewbyid (r.id.scan), Btn_discover = (Button) Findviewbyid (r.id.visable); Btn_check.setonclicklistener (new Onclicklistener () {@SuppressLint ("showtoast") @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubbluetoothadapter bltadapter = Bluetoothadapter.getdefaultadapter (), if (Bltadapter = = null) {Toast.maketext ( Getapplicationcontext (), "This machine does not have a Bluetooth device", 0). Show (); Tv_result.settext ("This machine does not have a Bluetooth device");} Else{toast.maketext (Getapplicationcontext (), "This machine has a Bluetooth device", 0). Show (); Tv_result.settext ("This machine has a Bluetooth device"); if (! Bltadapter.isenabled ()) {Intent Intent = new Intent (bluetoothadapter.action_request_enable); startactivity (Intent);} Set <BluetoothDevice> bltdevices = bltadapter.getbondeddevices (); String address = "Paired Bluetooth device"; if (Bltdevices.size () >0) {for (Iterator<bluetooThdevice> iterator = Bltdevices.iterator (); Iterator.hasnext ();) {bluetoothdevice Bltdevice = (bluetoothdevice) Iterator.next (); address = address+ "\ n" +bltdevice.getaddress (). toString (); Tv_result.settext (address);}}}); Btn_discover.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated Method Stubintent Intent = new Intent (bluetoothadapter.action_request_discoverable); Intent.putextra ( bluetoothadapter.extra_discoverable_duration); startactivity (intent);}); Btn_scan.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubbltadapter.startdiscovery ();}});} Private class Bluetoothreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent {//TODO auto-generated method stubstring action = Intent.getaction (); if (BluetoothDevice.ACTION_FOUND.equals action) ) {Bluetoothdevice Bltdevice = Intent.getparcelableextra (bluetoothdevice.extra_device); result1 = result1+ "\ n" +bltdevice.getaddress (). toString (); Tv_result.settext (RESULT1);}}} 

XML code

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "   android:layout_width=" fill_parent "   android:layout_height=" Fill_parent   " android:orientation= "vertical"    >    <button     android:id= "@+id/checkblt"    android:layout_width = "Fill_parent"    android:layout_height= "50DP"    android:text= "check native Bluetooth"    /><button     Android:id = "@+id/visable"    android:layout_width= "fill_parent"    android:layout_height= "50DP"    android:text= " Set visibility "    /><button     android:id=" @+id/scan "    android:layout_width=" Fill_parent "    android: layout_height= "50DP"    android:text= "scan around Bluetooth"    /><textview    android:id= "@+id/checkresult"        android:layout_width= "wrap_content"        android:layout_height= "wrap_content"        android:text= "@string /hello_world "/></linearlayout>

Bluetooth main use of the two classes bluetoothadapter and Bluetoothdevice, in communication will use Bluetoothserversocket.

There is only so much to know, and we must continue to work hard.

Note:

1, reprint please indicate out

2, the code although I wrote, but his own long crooked, have a problem try not to find me ~ ~ ~ ~ (>_<) ~ ~ ~ ~ ~ ~ ~ ~ ~

3. Thank you for reading

Android Bluetooth Module Base operation

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.