編輯:關於 Android 程式設計
之前的文章已經把 Android 藍牙的基本用法講清楚了,這一篇我們再往裡面挖一層,聊聊那些沒有寫進 SDK 的藍牙隱藏 API。
凡是用過 Android 系統設定(Settings)的人應該都記得:搜索到藍牙設備之後,可以進行配對,也可以解除配對。有意思的是,這兩個動作在公開的 SDK 裡完全找不到對應的方法。那麼要怎麼在自己的應用裡實現同樣的效果?答案就是 Java 的反射機制——繞過 SDK 的介面,直接呼叫底層已經存在的 createBond 與 removeBond。
整個挖掘過程可以拆成三步:
第一步,用 Git 把 platform/packages/apps/Settings.git 拉下來,在 Settings 的源碼裡搜索配對與解除配對相關的實現,確認這兩個 API 到底掛在哪個類上——結果是 BluetoothDevice。
第二步,用反射把 BluetoothDevice 的所有方法和常量全部列印出來,看看它們是否真的存在於執行環境中:
static public void printAllInform(Class clsShow) { try { // 取得所有方法 Method[] hideMethod = clsShow.getMethods(); int i = 0; for (; i < hideMethod.length; i++) { Log.e("method name", hideMethod[i].getName()); } // 取得所有常量 Field[] allFields = clsShow.getFields(); for (i = 0; i < allFields.length; i++) { Log.e("Field name", allFields[i].getName()); } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
執行結果大致如下:
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.051: method name(452): wait
11-29 09:19:12.051: method name(452): wait
11-29 09:19:12.051: method name(452): wait
顯然,createBond 和 removeBond 都好好地躺在那裡,只是 SDK 沒有把它們暴露出來。
第三步,既然方法確實存在,就自己動手封裝一層呼叫:
/** * 與設備配對 參考源碼: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(); } /** * 與設備解除配對 參考源碼: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(); }
這裡必須提醒一句:SDK 把這些 API 藏起來是有原因的,可能是出於安全考量,也可能是為了保留後續版本調整的空間。因此別指望它們在所有 Android 版本和廠商定製的 ROM 上都能正常運作,用在正式產品裡風險自負。
本文程式的執行效果如下圖:

main.xml 源碼:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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" android:layout_width="fill_parent"> <Button android:layout_height="wrap_content" android:id="@+id/btnSearch" android:text="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>
工具類 ClsUtils.java:
package com.testReflect; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.bluetooth.BluetoothDevice; import android.util.Log; public class ClsUtils { /** * 與設備配對 參考源碼: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(); } /** * 與設備解除配對 參考源碼: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 { Method[] hideMethod = clsShow.getMethods(); int i = 0; for (; i < hideMethod.length; i++) { Log.e("method name", hideMethod[i].getName()); } Field[] allFields = clsShow.getFields(); for (i = 0; i < allFields.length; i++) { Log.e("Field name", allFields[i].getName()); } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
主程式 testReflect.java:
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();// 初始化本機藍牙功能 if (btAdapt.getState() == BluetoothAdapter.STATE_OFF)// 開藍牙 btAdapt.enable(); // 註冊Receiver來獲取藍牙設備相關的結果 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 intent) { String action = intent.getAction(); Bundle b = intent.getExtras(); Object[] lstName = b.keySet().toArray(); // 顯示所有收到的消息及其細節 for (int i = 0; i < lstName.length; i++) { String keyName = lstName[i].toString(); Log.e(keyName, String.valueOf(b.get(keyName))); } // 搜索設備時,取得設備的MAC地址 if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_NONE) { String str = "未配對|" + device.getName() + "|" + device.getAddress(); lstDevices.add(str); adtDevices.notifyDataSetChanged(); } } } }; class ItemClickEvent implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> 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("未配對")) { Toast.makeText(testReflect.this, "由未配對轉為已配對", 500).show(); ClsUtils.createBond(btDevice.getClass(), btDevice); } else if(values[0].equals("已配對")) { Toast.makeText(testReflect.this, "由已配對轉為未配對", 500).show(); ClsUtils.removeBond(btDevice.getClass(), btDevice); } } catch (Exception e) { e.printStackTrace(); } } } /** * 按鍵處理 */ class ClickEvent implements View.OnClickListener { @Override public void onClick(View v) { if (v == btnSearch) { lstDevices.clear(); Object[] lstDevice = btAdapt.getBondedDevices().toArray(); for (int i = 0; i < lstDevice.length; i++) { BluetoothDevice device=(BluetoothDevice)lstDevice[i]; String str = "已配對|" + device.getName() + "|" + device.getAddress(); lstDevices.add(str); adtDevices.notifyDataSetChanged(); } setTitle("本機藍牙地址:" + btAdapt.getAddress()); btAdapt.startDiscovery(); } else if(v==btnShow){ ClsUtils.printAllInform(btDevice.getClass()); } } } }
以上就是挖掘並呼叫藍牙隱藏 API 的完整思路,希望對正在折騰 Android 藍牙開發的朋友提供一些參考。
微信運動怎麼用?開啟計步與好友排行的設定教學
微信運動是一個基於第三方運動數據的服務,能讀取手機或穿戴裝置的步數,再與微信好友做比較。目前支援 iOS 與 Android 兩大平台,設定一次之後就會自動記錄,不需要每
如何將你的 Android Library 上傳到 jcenter 中央倉庫
將 Android Library 上傳到 jcenter 我們辛苦開發的 Android library,如何上傳到中央倉庫,讓其他開發者一行代碼就能依賴,而不必下載源
違章查詢 App 源碼分享
本文分享一個違章查詢小工具的源碼與測試安裝包,主要透過網路查詢介面取得資料,並將結果呈現在 App 畫面中。源碼地址:https://xiazai.jb51.net/20
Android ListView 快速上手:三步驟做出簡易列表
ListView 是非常常見的控制項,以垂直列表的形式呈現資料。而完成一個最簡單的 ListView,只需要三個步驟: 1、在版面配置 XML 中加入 ListView