Android improved Bluetooth hidden API Quest _android

Source: Internet
Author: User
Tags getmessage reflection

The previous article explains the basic use of Bluetooth in Android, and this article delves into the hidden APIs in the next Bluetooth context. People who have used the Android system setup (Setting) know that pairing and pairing can be established after a Bluetooth search, but the functions of these two functions are not given in the SDK, so how do you use both of these features? This paper uses the reflection mechanism of Java to invoke the functions of these two functions: Createbond and Removebond, the specific excavation and implementation steps are as follows:

1. Use the Git tool to download the Platform/packages/apps/settings.git, find the APIs for pairing and setting in the source code, and know the hosts of the two APIs (Bluetoothdevice);

2. Use the reflection mechanism to enumerate all its methods and constants for Bluetoothdevice to see if it exists:

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 ());
 }
 Get all Constants
 field[] AllFields = Clsshow.getfields ();
 for (i = 0; i < allfields.length; i++) {
  log.e ("Field name", Allfields[i].getname ());
 }
 catch (Securit Yexception 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 ();
 }
}

The results are as follows:

11-29 09:19:12.012:method Name (452): cancelbondprocess
11-29 09:19:12.020:method Name (452): Cancelpairinguserinput
11-29 09:19:12.020:method Name (452): Createbond
11-29 09:19:12.020:method Name (452): Createinsecurerfcommsocket
11-29 09:19:12.027:method Name (452): Createrfcommsocket
11-29 09:19:12.027:method Name (452): Createrfcommsockettoservicerecord
11-29 09:19:12.027:method Name (452): Createscosocket
11-29 09:19:12.027:method Name (452): describecontents
11-29 09:19:12.035:method Name (452): Equals
11-29 09:19:12.035:method Name (452): FETCHUUIDSWITHSDP
11-29 09:19:12.035:method Name (452): getaddress
11-29 09:19:12.035:method Name (452): Getbluetoothclass
11-29 09:19:12.043:method Name (452): getbondstate
11-29 09:19:12.043:method Name (452): GetName
11-29 09:19:12.043:method Name (452): Getservicechannel
11-29 09:19:12.043:method Name (452): gettruststate
11-29 09:19:12.043:method Name (452): Getuuids
11-29 09:19:12.043:method Name (452): Hashcode
11-29 09:19:12.043:method Name (452): Isbluetoothdock
11-29 09:19:12.043:method Name (452): Removebond
11-29 09:19:12.043:method Name (452): setpairingconfirmation
11-29 09:19:12.043:method Name (452): Setpasskey
11-29 09:19:12.043:method Name (452): Setpin
11-29 09:19:12.043:method Name (452): Settrust
11-29 09:19:12.043:method Name (452): toString
11-29 09:19:12.043:method Name (452): Writetoparcel
11-29 09:19:12.043:method Name (452): convertpintobytes
11-29 09:19:12.043:method Name (452): GetClass
11-29 09:19:12.043:method Name (452): Notify
11-29 09:19:12.043:method Name (452): Notifyall
11-29 09:19:12.043:method Name (452): Wait
11-29 09:19:12.051:method Name (452): Wait
11-29 09:19:12.051:method Name (452): Wait

3. If the enumeration discovers that the API exists (the SDK is hidden), implement the calling method yourself:

/**
 * and equipment pairing 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 ();
}
/**
 * With the equipment to remove pairing 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 ();
}

Note here: The SDK does not give a hidden API for certain reasons, perhaps for security or subsequent version compatibility considerations, so it is not guaranteed that the hidden API will work well on all Android platforms.

The effect of this program is shown in the following illustration:

The

Main.xml source code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " > <linearlayout android:id= "@+id/linearlayout01" android:layout_height= "Wrap_content" Fill_parent "> <button android:layout_height=" wrap_content "android:id=" @+id/btnsearch "Search" Android:layout_width= "160dip" ></Button> <button android:layout_height= "Wrap_content" Android:layout_ Width= "160dip" android:text= "show" android:id= "@+id/btnshow" ></Button> </LinearLayout> < LinearLayout android:id= "@+id/linearlayout02" android:layout_width= wrap_content "android:layout_height=" Wrap_
 Content "></LinearLayout> <listview android:id=" @+id/listview01 "android:layout_width=" Fill_parent "

 android:layout_height= "Fill_parent" > </ListView> </LinearLayout>

Tool class Clsutils.java source code is as follows:

Package com.testreflect;
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import Android.bluetooth.BluetoothDevice;
Import Android.util.Log; public class Clsutils {/** * with device pairing reference Source: Platform/packages/apps/settings.git */settings/src/com/android/settings/bluet Ooth/cachedbluetoothdevice.java */Static public boolean Createbond (Class btclass,bluetoothdevice btdevice) throws Exce
 ption {Method Createbondmethod = Btclass.getmethod ("Createbond");
 Boolean returnvalue = (Boolean) createbondmethod.invoke (Btdevice);
 return Returnvalue.booleanvalue (); /** * With the device to remove pairing 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 ();
 }/** * * @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 ());
  }//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 ();

 }
 }
}

The source code for the

Main program Testreflect.java is as follows:

Package com.testreflect;
Import java.util.ArrayList;
Import java.util.List;
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.widget.AdapterView;
Import Android.widget.ArrayAdapter;
Import Android.widget.Button;
Import Android.widget.ListView;
Import Android.widget.Toast;
 public class Testreflect extends activity {Button btnsearch, btnshow;
 ListView lvbtdevices;
 Arrayadapter<string> adtdevices;
 list<string> lstdevices = new arraylist<string> ();
 Bluetoothdevice Btdevice;
 Bluetoothadapter btadapt;
 @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
 Setcontentview (R.layout.main); Btnsearch = (Button) This.findviewbyid (r.id. btnsearch);
 Btnsearch.setonclicklistener (New Clickevent ());
 Btnshow = (Button) This.findviewbyid (r.id.btnshow);
 Btnshow.setonclicklistener (New Clickevent ());
 Lvbtdevices = (ListView) This.findviewbyid (R.ID.LISTVIEW01); Adtdevices = new Arrayadapter<string> (Testreflect.this, Android.
 R.layout.simple_list_item_1, lstdevices);
 Lvbtdevices.setadapter (adtdevices);

 Lvbtdevices.setonitemclicklistener (New Itemclickevent ()); Btadapt = Bluetoothadapter.getdefaultadapter ()//Initialize native Bluetooth feature if (btadapt.getstate () = = Bluetoothadapter.state_off)//
 Open Bluetooth btadapt.enable ();
 Register receiver to get Bluetooth device-related results intentfilter intent = new Intentfilter ();
 Intent.addaction (Bluetoothdevice.action_found);
 Intent.addaction (bluetoothdevice.action_bond_state_changed);

 Registerreceiver (searchdevices, intent); Private Broadcastreceiver searchdevices = new Broadcastreceiver () {public void OnReceive (context context, Intent inte
  NT) {String action = intent.getaction (); Bundle B = Intent.getextras ();
  object[] Lstname = B.keyset (). ToArray ();
  Displays all messages received and their details for (int i = 0; i < lstname.length; i++) {String keyname = lstname[i].tostring ();
  LOG.E (KeyName, string.valueof (B.get (KeyName))); When searching for a device, obtain the device's MAC address if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {Bluetoothdevice device = intent. Getparc
  Elableextra (Bluetoothdevice.extra_device); if (device.getbondstate () = = Bluetoothdevice.bond_none) {String str = "Not paired |" + Device.getname () + "|" + device.getaddr
   ESS (); Lstdevices.add (str);
  Get the device name and MAC address adtdevices.notifydatasetchanged ();
 }
  }
 }
 }; Class Itemclickevent implements Adapterview.onitemclicklistener {@Override public void Onitemclick (ADAPTERVIEW&LT;?&G T
  arg0, View arg1, int arg2, long arg3) {btadapt.canceldiscovery ();
  String str = lstdevices.get (ARG2);
  String[] values = Str.split ("//|");
  String address=values[2];
  Btdevice = Btadapt.getremotedevice (address); try {if (Values[0].equals ("not paired")) {Toast.maketexT (Testreflect.this, "changed from unpaired to paired"). Show ();
  Clsutils.createbond (Btdevice.getclass (), btdevice);
   else if (Values[0].equals ("paired")) {Toast.maketext (Testreflect.this, from paired to unpaired). Show ();
  Clsutils.removebond (Btdevice.getclass (), btdevice);
  The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); }}/** * key processing * @author GV */class Clickevent implements View.onclicklistener {@Override public void Oncl
  Ick (View v) {if (v = = btnsearch) {//Search nearby Bluetooth device lstdevices.clear ();
  object[] Lstdevice = Btadapt.getbondeddevices (). ToArray ();
   for (int i = 0; i < lstdevice.length i++) {bluetoothdevice device= (bluetoothdevice) lstdevice[i];
   String str = "paired |" + Device.getname () + "|" + device.getaddress (); Lstdevices.add (str);
  Get the device name and MAC address adtdevices.notifydatasetchanged ();
  //Start Search Settitle ("Native Bluetooth address:" + btadapt.getaddress ());
  Btadapt.startdiscovery (); else if (v==btnshow) {//Show all sides of BluetoothdeviceMethods and constants, including hidden API Clsutils.printallinform (Btdevice.getclass ()); }
 }
 }
}

I hope this article will help you to develop Android program.

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.