Bluetooth auto-pairing, that is, to search for other Bluetooth devices directly after pairing, do not need to pop up a pairing confirmation box or key input box.
Reprint please specify the source http://blog.csdn.net/qq_25827845/article/details/52400782
After a recent period of time to study, for the online case. Summed up a pro-test demo.
The description is as follows:
1, this demo is used to connect Bluetooth device HC-05, if you want to connect other Bluetooth devices, pay attention to modify the relevant name and modify the device pin value.
2, the demo installed on the Android phone, click the button, you can achieve with the target Bluetooth device automatic pairing.
3, if the target Bluetooth device for Android phone Bluetooth, you can only ensure that the device does not eject the matching box, the other side will pop up the matching box. But!! Whether the target Bluetooth is clicked "Confirm" or "Cancel", the pairing is displayed on this device successfully. The measured results show that the pairing is done and the data can be transferred.
4, because of the use of the broadcast mechanism, so the androidmanifest.xml need to do the following configuration.
Configure Bluetooth usage Rights First:
<uses-permission android:name= "Android.permission.BLUETOOTH"/>
<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/>
Then configure the action
<receiver android:name= "Com.ywq.broadcast.BluetoothReceiver" >
<intent-filter android:priority= ">"
<action android:name= "Android.bluetooth.device.action.PAIRING_REQUEST"/>
<action android:name= "Android.bluetooth.device.action.FOUND"/>
</intent-filter>
</receiver>
Program Run Process:
1, click the button to determine whether Bluetooth is turned on, to perform bluetoothadapter.startdiscovery (); The remote Bluetooth device is scanned by a local Bluetooth device, and the StartDiscovery () method is an asynchronous method that returns immediately after the call. This method will search for the Bluetooth device for 12 seconds.
2, search, the system will send 3 broadcasts, respectively:action_discovery_start: Start Search,action_discovery_finished: Search end, action_found: Find the device, the intent contains two extra fields;
3. In the broadcast receive class, Bluetoothreceiver.java executes its OnReceive method when the device is found.
4, String action = Intent.getaction (); Get Action,
The value of the first action is Bluetoothdevice.action_found, and when you continue broadcasting, the value of the action is Android.bluetooth.device.action.PAIRING_REQUEST is the pairing operation.
5, pairing operation with the tool class Clsutils.java get the Android Bluetooth API hidden methods, to achieve automatic pairing, do not eject the function of the matching box.
The code is as follows:
Mainactivity.java
Package Com.example.mybuletooth;import Android.app.activity;import Android.bluetooth.bluetoothadapter;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; public class Mainactivity extends activity implements onclicklistener{/** called when the activity is first created. */PR Ivate Button autopairbtn=null;private Bluetoothadapter bluetoothadapter = Bluetoothadapter.getdefaultadapter (); overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); autopairbtn= (Button) Findviewbyid (R.id.button1); Autopairbtn.setonclicklistener (this);} Set the Listener method for the button @overridepublic void OnClick (View arg0) {if (!bluetoothadapter.isenabled ()) {bluetoothadapter.enable ();// Asynchronously, does not wait for the result, and returns directly. }else{bluetoothadapter.startdiscovery ();}}}
Bluetoothreceiver.java
Package Com.ywq.broadcast;import Com.ywq.tools.clsutils;import Android.bluetooth.bluetoothdevice;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.util.log;public class Bluetoothreceiver extends broadcastreceiver{string pin = "1234"; Here is the initial key for the Bluetooth device you want to connect to, typically 1234 or 0000public bluetoothreceiver () {}//broadcast receiver, when the remote Bluetooth device is discovered, the callback function Onreceiver () is executed @ overridepublic void OnReceive (context context, Intent Intent) {String action = intent.getaction ();//Get ACTIONLOG.E (" Action1= ", action); Bluetoothdevice Btdevice=null; Create a Bluetooth Device object//Get the device object from Intent Btdevice = Intent.getparcelableextra (Bluetoothdevice.extra_device); if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {//Discover device LOG.E ("Discovery Device:", "[" +btdevice.getname () + "]" + ":" + Btdevice.getaddress ()); if (Btdevice.getname (). Contains ("HC-05")//hc-05 device if there are multiple, the first one to be searched will be tried. {if (btdevice.getbondstate () = = Bluetoothdevice.bond_none) {log.e ("Ywq", "Attemp to BOND:" + "[" +btdevice.getname () + "]" ); try {//Through tool classClsutils, call the Createbond method Clsutils.createbond (Btdevice.getclass (), btdevice);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} }}ELSELOG.E ("Error", "is Faild");} else if (action.equals ("Android.bluetooth.device.action.PAIRING_REQUEST"))//The action received again will be equal to PAIRING_REQUEST{LOG.E ("action2=", Action), if (Btdevice.getname (). Contains ("HC-05")) {LOG.E ("Here", "Okokok"); try {//1. Confirm Pairing Clsutils.setpairingconfirmation (Btdevice.getclass (), Btdevice, True)//2. Terminate ordered broadcast LOG.I ("Order ...", " Isorderedbroadcast: "+isorderedbroadcast () +", Isinitialstickybroadcast: "+isinitialstickybroadcast ()); Abortbroadcast ();//If the broadcast is not terminated, a flashing pairing box appears. 3. Call the Setpin method to pair ... boolean ret = Clsutils.setpin (Btdevice.getclass (), btdevice, PIN);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} ELSELOG.E ("Prompt Message", "This device is not a target Bluetooth device");}}}
Tool Class Clsutils.java
Package com.ywq.tools;/************************************ Bluetooth Pairing function * **************/import Java.lang.reflect.Method ; Import Java.lang.reflect.Field; Import Android.bluetooth.BluetoothDevice; Import Android.util.Log; public class Clsutils {/** * paired with Device reference source: Platform/packages/apps/settings.git */settings/src/com/android/ Settings/bluetooth/cachedbluetoothdevice.java */Static public boolean Createbond (Class btclass, Bluetoothdevice Btdevice) throws Exception {Method Createbondmethod = Btclass.getmethod ("Createbond"); Boolean returnvalue = (Boolean) createbondmethod.invoke (Btdevice); return Returnvalue.booleanvalue (); }/** * Pairing with Device reference Source: Platform/packages/apps/settings.git */settings/src/com/android/settings/bluetooth/ Cachedbluetoothdevice.java */Static public boolean Removebond (class<?> btclass, Bluetoothdevice btdevice) Throws Exception {Method remOvebondmethod = Btclass.getmethod ("Removebond"); Boolean returnvalue = (Boolean) removebondmethod.invoke (Btdevice); return Returnvalue.booleanvalue (); } static public boolean setpin (class<? extends Bluetoothdevice> Btclass, Bluetoothdevice Btdevice, String str) throws Exception {try {Method Removebondmethod = btclass.getdeclared Method ("Setpin", new class[] {byte[].class}); Boolean returnvalue = (Boolean) Removebondmethod.invoke (Btdevice, new object[] { Str.getbytes ()}); LOG.E ("ReturnValue", "" "+ returnvalue); } catch (SecurityException e) {//throw new RuntimeException (E.getmessage ()); E.printstacktrace (); } catch (IllegalArgumentException e) {//throw new RuntimeException (E.getmessage ()); E.printstacktrace (); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace () ; } return true; }//Cancel user input static public boolean cancelpairinguserinput (class<?> btclass, Bluetoothdevice Device) throws Exception {Method Createbondmethod = Btclass.getmethod ("Cancelpairinguserinput"); Cancelbondprocess (btclass, device); Boolean returnvalue = (Boolean) createbondmethod.invoke (device); return Returnvalue.booleanvalue (); }//de-pairing static public boolean cancelbondprocess (class<?> btclass, bluetoothdevice device ) throws Exception {Method Createbondmethod = Btclass.getmethod ("cancelbondprocess"); Boolean returnvalue = (Boolean) createbondmethod.invoke (device); return Returnvalue.booleanvalue (); }//Confirm pairing static public voidSetpairingconfirmation (class<?> btclass,bluetoothdevice Device,boolean isconfirm) throws Exception {Method SE Tpairingconfirmation = Btclass.getdeclaredmethod ("Setpairingconfirmation", Boolean.class); Setpairingconfirmation.invoke (device,isconfirm); }/** * * @param clsshow * * * static public void Printallinform (Class clsshow) { try {//Get all methods method[] Hidemethod = Clsshow.getmethods (); int i = 0; for (; i < hidemethod.length; i++) {log.e ("method name", Hidemethod[i].getname () + "; The I is: "+ i); }//Get all constants field[] AllFields = Clsshow.getfields (); for (i = 0; i < allfields.length; i++) {log.e ("Field name", Allfields[i].getname ()); }} catch (SecurityException e) {//thRow New RuntimeException (E.getmessage ()); E.printstacktrace (); } catch (IllegalArgumentException e) {//throw new RuntimeException (E.getmessage ()); E.printstacktrace (); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace () ; } } }
Androidmanifest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.mybuletooth "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android Oid.permission.BLUETOOTH "/><uses-permission android:name=" Android.permission.BLUETOOTH_ADMIN "/> < Application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/ap P_name "Android:theme=" @style/apptheme "> <activity android:name=". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> <receiver android:name= "Com.ywq.broadcast.BluetoothReceiver" > <intent-filter android:priority= "1000" > <action android:name= "Android.bluetooth.device.action.PAIRING_REQUEST"/> <action android:name= "Android.bluetooth.device.action.FOUND"/> </intent-filter></receiver> </application></ Manifest>
Layout configuration file Activity_main.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: context= "Com.example.mybuletooth.MainActivity" > <button android:id= "@+id/button1" Android:layout_w Idth= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" Androi D:layout_alignparenttop= "true" android:layout_marginleft= "54DP" android:layout_margintop= "56DP" Andro id:text= "Auto Pairing"/> <textview android:id= "@+id/textview1" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_cenTervertical= "True" android:text= "click button to automatically search for Bluetooth devices and pair"/></relativelayout>
For other online posts in the cause of the demo, give some of my views, is not so sure, at least in part is the reason for it ...
1. What about a flashing pairing box?
Answer: That is because the broadcast does not stop, you have to call Abortbroadcast (), stop the broadcast.
2, automatic matching box or will bounce out how to do?
A: Many of the online post code is wrong, or not clearly stated. Note the related configuration in Androidmanifest.
This is my own self-test so that the automatic matching demo, for reference only, I hope to help you. If you have any questions, you can contact me.
Attached to the demo on GitHub: Https://github.com/chaohuangtianjie994/BlueTooth-AutoPair
Important Update: ********************************************************************************
2016-10-20, today and a consultation with my little buddy in detail for a while. His problem is that the IF statement block shown does not go in.
It's btdevice.getbondstate () = 12, but bluetoothdevice.bond_none=10, it's not sure to get in.
Among them, consult the SDK, you can see Bluetoothdevice of these functions and the meaning of the number is what.
Reference URL: http://www.cnblogs.com/over140/archive/2010/12/21/1912482.html
As shown below:
I see, my goodness, it's obviously a low-level mistake. I let him open the settings to see if the display is already paired. The result is naturally paired.
Cause: Before the demo ran, he had manually paired the target Bluetooth in the phone-Setup-Bluetooth. It's still a hair.
When the pairing is manually canceled, the program is running normally, and log printing is automatically paired with the same as expected.
Tips:
Through this small error, it can be seen that the comments in a lot of said that this is not possible, that is not. Since so many people say so, why can't you? Or more from their own to find the problem, thoughtful point, to avoid such low-level mistakes. elder brother, you are the program ape good or not.
Android Bluetooth auto pairing demo, Pro Test!!!