編輯:關於 Android 開發
上一篇講了 Android 藍牙的基本用法,這次我們再往下挖一層,看看藍牙相關的隱藏 API。
用過 Android 系統設定的人都知道,藍牙搜尋到裝置後可以進行「配對」與「解除配對」。有趣的是,這兩個功能對應的方法並沒有出現在 SDK 裡。那麼要怎麼在自己的應用中呼叫它們?答案依然是 Java 反射機制——本文要挖掘的目標是 createBond 與 removeBond。
第一步是找到這兩個 API 的宿主類別。用 Git 拉下 platform/packages/apps/Settings.git,在 Settings 的原始碼中搜尋配對相關的呼叫,很快就能定位到關鍵檔案:Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java。從這裡可以確認,配對與解除配對的方法都掛在 BluetoothDevice 上。
第二步是驗證 SDK 的執行環境裡是否真的存在這些方法。做法很直接:把 BluetoothDevice 的所有方法與常數都印到 Log,再逐一比對。
static public void printAllInform(Class clsShow) {
try {
Method[] hideMethod = clsShow.getMethods(); // 取得所有方法
for (int i = 0; i < hideMethod.length; i++) {
Log.e("method name", hideMethod[i].getName());
}
Field[] allFields = clsShow.getFields(); // 取得所有常數
for (int 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();
}
}執行後的 Log 輸出(節錄)大致如下:
method name: cancelBondProcess
method name: cancelPairingUserInput
method name: createBond
method name: createInsecureRfcommSocket
method name: createRfcommSocket
method name: createRfcommSocketToServiceRecord
method name: createScoSocket
method name: describeContents
method name: equals
method name: fetchUuidsWithSdp
method name: getAddress
method name: getBluetoothClass
method name: getBondState
method name: getName
method name: getServiceChannel
method name: getTrustState
method name: getUuids
method name: hashCode
method name: isBluetoothDock
method name: removeBond
method name: setPairingConfirmation
method name: setPasskey
method name: setPin
method name: setTrust
method name: toString
method name: writeToParcel結果很明確:createBond 與 removeBond 確實存在於執行環境,只是沒有開放給 SDK 使用。順帶一提,這份清單還揭露了不少有趣的東西,例如 setPin、setPasskey、setPairingConfirmation、setTrust 等,全都屬於未公開的配對控制能力。
確認方法存在後,就能用反射把它包成一般方法來用:
/**
* 與裝置配對
* 參考: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();
}這裡用 getMethod 而非 getDeclaredMethod,因為我們呼叫的是公開可見的方法,只是 SDK 沒有把它們列進 API 文件。傳入的 btClass 通常直接給 btDevice.getClass() 即可。

版面很簡單:Search 鈕負責搜尋、Show 鈕負責印出所有方法清單,下方 ListView 列出搜尋到的裝置。
<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
android:layout_height="wrap_content"
android:layout_width="160dip"
android:text="Show"
android:id="@+id/btnShow" />
</LinearLayout>
<LinearLayout
android:id="@+id/LinearLayout02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ListView
android:id="@+id/ListView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</LinearLayout>工具類 ClsUtils.java 除了上述兩個配對方法,也包含前面用來盤點 API 的 printAllInform:
package com.testReflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
public class ClsUtils {
/** 與裝置配對 */
static public boolean createBond(Class btClass, BluetoothDevice btDevice) throws Exception {
Method createBondMethod = btClass.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
/** 與裝置解除配對 */
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 void printAllInform(Class clsShow) {
try {
Method[] hideMethod = clsShow.getMethods();
for (int i = 0; i < hideMethod.length; i++) {
Log.e("method name", hideMethod[i].getName());
}
Field[] allFields = clsShow.getFields();
for (int 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();
}
}
}主程式的流程是:註冊 BroadcastReceiver 接收 ACTION_FOUND 與 ACTION_BOND_STATE_CHANGED,把找到的裝置名稱與 MAC 位址放進清單;使用者點擊某一列時,根據目前的配對狀態呼叫 createBond 或 removeBond,完成配對狀態的切換。
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 adtDevices;
List lstDevices = new ArrayList();
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(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) {
// 印出 BluetoothDevice 的所有方法與常數,含隱藏 API
ClsUtils.printAllInform(btDevice.getClass());
}
}
}
}SDK 之所以不公開這些方法,背後一定有原因——可能是安全性考量,也可能是為了保留後續版本調整的空間。因此不能保證這些隱藏 API 能在所有 Android 版本與各家 ROM 上正常運作。此外,配對與解除配對都需要 android.permission.BLUETOOTH_ADMIN 權限,別忘了在 AndroidManifest.xml 中宣告。若要用在正式產品,建議加上版本判斷與完整的例外處理。
CAS 單一登入原理完整解析:TGC、ST、PGT 與代理認證
一、CAS 是什麼 CAS(Central Authentication Service)源自耶魯大學,是一套企業級的開源單一登入解決方案,屬於 Web SSO 範疇。專
用 Kotlin 開發 Android(三):擴展函數與參數預設值
系列第三篇 原文:Kotlin for Android (III): Extension functions and default values 作者:Antonio
Android 特效:仿微信雷達搜尋好友動畫
Android 特效:仿微信雷達搜尋好友動畫 雷達搜尋好友是許多即時通訊應用中常見的互動效果。它的視覺核心其實不複雜:中間放置一張圖片,周圍畫出同心圓,再搭配一個持續旋轉
藍牙防丟器原理與 Android BLE 開發實作
藍牙防丟器原理與 Android BLE 開發實作 藍牙防丟器的核心概念,是利用接收端測得的 RSSI 訊號強度估算距離。當距離超過門檻或連結中斷時,手機或裝置端即可發出