編輯:Android 開發實例
用過 Android 系統設定的人都知道,藍牙搜索之後可以做建立配對與解除配對,但這兩個函式偏偏沒有出現在 SDK 裡。想用在自己的 App 上該怎麼辦?答案還是反射。本文示範如何找出並呼叫這兩個函式:createBond 與 removeBond。
第一步,用 Git 把 platform/packages/apps/Settings.git 抓下來,在設定原始碼裡搜尋配對相關的 API,可以確認這兩個方法的宿主是 BluetoothDevice。
第二步,用反射把 BluetoothDevice 的所有方法與常量印出來,親眼確認方法是否真的存在於執行環境中:
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 中撈到的清單(節錄)大致如下,createBond 與 removeBond 都好好地躺在裡面:
method name: cancelBondProcess method name: cancelPairingUserInput method name: createBond <-- 建立配對 method name: createInsecureRfcommSocket method name: createRfcommSocket method name: createRfcommSocketToServiceRecord method name: createScoSocket method name: fetchUuidsWithSdp method name: getAddress method name: getBluetoothClass method name: getBondState method name: getName method name: getTrustState method name: getUuids method name: isBluetoothDock method name: removeBond <-- 解除配對 method name: setPairingConfirmation method name: setPasskey method name: setPin method name: setTrust
第三步,既然方法存在、只是 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();
}
/**
* 與設備解除配對
* 參考源碼同上
*/
static public boolean removeBond(Class btClass, BluetoothDevice btDevice) throws Exception {
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
兩顆按鈕負責搜索與列出方法,下方 ListView 顯示搜索到的設備,點一下即可在配對與解除配對之間切換:
<?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>
把配對、解除配對與「列出所有方法常量」三件事集中到一個工具類,主程式只管呼叫:
package com.testReflect;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
public class ClsUtils {
/** 與設備配對,參考 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();
}
/** 與設備解除配對,參考 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 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,並用 Toast 提示切換結果。
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) { // 列出 BluetoothDevice 的所有方法與常量
ClsUtils.printAllInform(btDevice.getClass());
}
}
}
}
SDK 不公開這些方法通常有原因,可能是安全考量,也可能是為了後續版本的相容性。因此這類寫法無法保證在所有 Android 版本與所有機型上都能正常運作,正式產品請改用官方支援的藍牙 API;把它當成理解 Framework 與反射機制的一次練習,會更有收穫。
Android ApiDemo 系列五:自訂標題欄
Android 預設的標題欄通常由 android:label 決定,顯示在畫面左上角。若開發者想要更特殊的視覺效果,例如左右兩側各放置一個文字區塊,就可以使用自訂標題欄
Android 接入新浪微博、騰訊微博與人人網的 OAuth 2.0 實作
許多 Android 應用會需要接入社交平台的分享、登入或發文能力。本文以新浪微博、騰訊微博與人人網為例,說明整合時最關鍵的授權流程,以及如何取得後續呼叫 API 所需的
Android 載入動畫:Spinner 元件實作教學
當 App 在背後忙著抓資料、算報表時,畫面上不能一片死寂。使用者需要一個訊號,知道自己按下的動作正在被處理——這就是進度條的用途。 Android 的進度條分成兩類:能
Genymotion:高效 Android 模擬器介紹
Genymotion 是一款以速度與真機模擬能力著稱的 Android 模擬器,適合日常開發、測試與展示。它相較傳統模擬器啟動更快,操作也更接近真實設備。主要特色Geny