編輯:Android 開發實例
前文講解了 Android 藍牙的基本用法,本文則更深入一步,探討藍牙方面的隱藏 API。用過 Android 系統設置的人都知道,藍牙搜索之後可以建立配對或解除配對,但這兩項功能對應的函數並未在 SDK 中公開,那麼該如何調用它們呢?本文借助 Java 的反射機制,去調用這兩個功能對應的函數:createBond 與 removeBond。具體的發掘與實現步驟如下:
1. 使用 Git 工具下載 platform/packages/apps/Settings.git,在 Settings 源碼中查找關於建立配對與解除配對的 API,可知這兩個 API 的宿主是 BluetoothDevice;
2. 使用反射機制枚舉 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) { // 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(); } } 結果如下:
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
3. 如果枚舉發現 API 確實存在(只是被 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 必有其原因,可能是出於安全性或後續版本兼容性的考量,因此無法保證隱藏 API 能在所有 Android 平台上穩定運行。
本文程序運行效果如下圖所示:

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) { // 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(); } } } 主程序 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); // 獲取設備名稱和mac地址 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) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 按鍵處理 * @author GV * */ 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); // 獲取設備名稱和mac地址 adtDevices.notifyDataSetChanged(); } // 開始搜索 setTitle("本機藍牙地址:" + btAdapt.getAddress()); btAdapt.startDiscovery(); } else if(v==btnShow){//顯示BluetoothDevice的所有方法和常量,包括隱藏API ClsUtils.printAllInform(btDevice.getClass()); } } } }希望本實例能為大家進行 Android 開發提供一定的借鑒與幫助。
Android Dialog 去除白色邊框的實作思路與程式碼
用系統預設的 Dialog 樣式時,四周總會帶一圈白框,很多時候並不是我們想要的。要拿掉它,正解不是去改圖片,而是覆寫樣式。 第一步:自訂 style 在 values
Android JSON 解析:JSONObject 與 JSONArray 的實際應用
JSON 是 Android 開發中常見的資料格式。當 App 需要從網路取得資料時,後端通常會回傳 JSON 字串,開發者再透過 JSONObject 與 JSONAr
Android SDK 線上更新鏡像伺服器大全與設定教學
中國科學院開源協會鏡像站位址:IPV4/IPV6: https://mirrors.opencas.cn 連接埠:80IPV4/IPV6: https://mirrors
Android 照片塗鴉功能實作全解析:UI 分層、Matrix 變形與座標映射
「在照片上隨手畫幾筆再分享出去」已經是社群產品的標配玩法。聽起來簡單,但真正要讓筆跡精準落在使用者手指的位置上,背後牽涉到不少細節。 單純的繪圖本身不難,難的是在圖片經過