編輯:關於 Android 程式設計
現在市面上有不少 Android 手機支援「敲兩下螢幕解鎖」,這功能相當實用,但問題是:多半只支援螢幕、功能固定、而且應用層開發者完全插不上手。既然身為開發者,不如自己動手做一個。iOS 上早有名為 Knock 的應用(用敲擊解鎖 Mac,售價 4.99 美元),Android 自然不能落後。
本文以 Java 為示範語言、Android 為平台,完整說明如何用加速度感測器做出可用的敲擊辨識。
手勢姿態辨識的唯一途徑是感測器。Android 2.3 定義了 11 種感測器,到 6.0 已擴充到 26 種,但後期的部分(如心跳感測器)需要特定硬體支援,覆蓋率低;而 2.3 時代那 11 種已經足以應付絕大多數手勢辨識:
SENSOR_TYPE_ACCELEROMETER 加速度 SENSOR_TYPE_MAGNETIC_FIELD 磁力 SENSOR_TYPE_ORIENTATION 方向 SENSOR_TYPE_GYROSCOPE 陀螺儀 SENSOR_TYPE_LIGHT 光線感應 SENSOR_TYPE_PRESSURE 壓力 SENSOR_TYPE_TEMPERATURE 溫度 SENSOR_TYPE_PROXIMITY 接近 SENSOR_TYPE_GRAVITY 重力 SENSOR_TYPE_LINEAR_ACCELERATION 線性加速度 SENSOR_TYPE_ROTATION_VECTOR 旋轉矢量
仔細想一下敲擊的物理過程:手機平放桌面,手指敲下去時給了手機一個力,桌面給了反作用力。在「桌面不形變」的理想前提下,手機受力平衡、加速度為 0——但感測器讀到的卻會是一段短暫而明顯的變化。原因是手機雖然是一個整體,內部構件之間仍存在複雜的作用力傳遞,並非受力瞬間就達到平衡。想像一個形狀與手機相似、內部光滑的容器,裡面放幾顆玻璃球,敲幾下容器不會移動,但球一定會動。手機內部構件比玻璃球穩定得多,但同樣得遵守力學定律。
那麼該選加速度感測器還是線性加速度感測器?線性加速度已經排除重力影響,看似更直觀,但它是軟體合成的,各家平台對重力的分離處理未必一致。實測敲擊某機型的背面時,就出現線性加速度數據幾乎沒有變化的情況。保險起見,選擇硬體的加速度感測器再自行濾波,是更穩妥的做法。
另外要澄清一個常見誤會:看到「壓力感測器」時我以為是偵測作用在手機上的壓力,那豈不是天生適合做敲擊辨識?仔細查才發現它偵測的是氣壓(hPa)。
判斷敲擊的方式,是偵測手機加速度相較於正常狀態是否出現明顯變化。實作上有三個關鍵設計:
註冊感測器是系統原生 API,這裡要特別注意採樣間隔參數:建議使用 SENSOR_DELAY_GAME。因為敲擊造成的加速度變化非常短暫,用 SENSOR_DELAY_UI 或 SENSOR_DELAY_NORMAL 往往採不到;SENSOR_DELAY_FASTEST 當然不會漏,但功耗偏高。
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor == null) {
return;
}
if (sensorEvent.sensor.getType() == accelerometerSensorType) {
float accelerationZ = sensorEvent.values[2];
if (accelerationZ > 0) {
recognitionKnockRatio = 20;
recognitionUniqueRatio = 10;
smoothSectionMaxRatio = 5f;
} else {
recognitionKnockRatio = 7.5f;
recognitionUniqueRatio = 6;
smoothSectionMaxRatio = 2.5f;
}
gravityZ = alpha * gravityZ + (1 - alpha) * accelerationZ;
linearAccelerationZ = accelerationZ - gravityZ;
if (calibrateLinearAcceleration) {
calibrateLinearAccelerationIndex++;
if (calibrateLinearAccelerationIndex <= calibrateLinearAccelerationSectionNumber) {
return;
}
calibrateLinearAcceleration = false;
}
if (sensorDataShowIndex >= sensorDataShowNumber) {
sensorDataShowIndex = sensorDataShowNumber - sensorDataShowDurationNumber;
Iterator<?> it = linearAccelerationZShowList.listIterator(0);
for (int i = 0; i < sensorDataShowDurationNumber; i++) {
it.next();
it.remove();
}
MainActivity.UpdateSensorData(linearAccelerationZShowList);
}
linearAccelerationZShowList.add(linearAccelerationZ);
sensorDataShowIndex++;
if (!stable) {
linearAccelerationZList.add(linearAccelerationZ);
if (linearAccelerationZList.size() >= stableSectionNumber) {
stableRecognition();
linearAccelerationZList.clear();
}
return;
}
knockRecognition(linearAccelerationZ);
}
}
這裡有個有趣的細節:根據 z 軸加速度的正負,為三個門檻係數賦予不同數值。原因是實測發現感測器對「正面敲擊」的反饋明顯敏感於「背面敲擊」。站在手機的角度,其實無法真正判斷敲擊來源,所以就用 z 軸正負做粗略推測——絕大多數情況下 z 為正代表背面朝向地面,使用者更可能在敲螢幕;z 為負則相反。
造成敏感度差異的原因有兩個:一是加速度感測器在硬體上通常比背面更靠近螢幕;二是外殼材質。LG G3 採用帶弧度的塑膠外殼,背面敲擊引起的數據變化明顯低於螢幕;而金屬外殼的三星 S6,兩者差距就小得多。這也說明了為什麼這三個係數屬於「經驗係數」,且最好依機型提供不同預設值——Android 裝置多樣性帶來的調參成本,實在遠高於只有幾款機型的 iOS。
以下做法參考 Android SensorEvent 原始碼中的官方建議:以低通濾波分離重力,再用原加速度減去重力得到線性加速度。
* It should be apparent that in order to measure the real acceleration of
* the device, the contribution of the force of gravity must be eliminated.
* This can be achieved by applying a high-pass filter. Conversely, a
* low-pass filter can be used to isolate the force of gravity.
*
* public void onSensorChanged(SensorEvent event)
* {
* // alpha is calculated as t / (t + dT)
* // with t, the low-pass filter's time-constant
* // and dT, the event delivery rate
* final float alpha = 0.8;
*
* gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
* gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
* gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];
*
* linear_acceleration[0] = event.values[0] - gravity[0];
* linear_acceleration[1] = event.values[1] - gravity[1];
* linear_acceleration[2] = event.values[2] - gravity[2];
* }
其中 calibrateLinearAccelerationSectionNumber 決定要投入多少樣本校準,calibrateLinearAccelerationIndex 與 calibrateLinearAcceleration 負責控制校準何時結束。校準完成後,才開始把資料存入 linearAccelerationZShowList 供畫面顯示,並進入穩態判斷。
判斷方式:取 50 個樣本,計算每個樣本的絕對值,若大於最大偏差 maxStableOffset 則記為異常點;異常點數超過 maxExceptionNumber 即判定為非穩態,反之為穩態。若判定為穩態,則把「剔除異常點後 Z 軸最大值與最小值之差的一半」視為波動區間 linearAccelerationZStableSection。
private void stableRecognition() {
int exceptionNumber = 0;
float accelerationZValue;
float minAccelerationZValue = Integer.MAX_VALUE;
float maxAccelerationZValue = Integer.MIN_VALUE;
for (int i = stableSectionNumber - 1; i >= 0; i--) {
accelerationZValue = linearAccelerationZList.get(i);
if (Math.abs(accelerationZValue) > maxStableOffset) {
exceptionNumber++;
} else {
if (accelerationZValue > maxAccelerationZValue) {
maxAccelerationZValue = accelerationZValue;
} else if (accelerationZValue < minAccelerationZValue) {
minAccelerationZValue = accelerationZValue;
}
}
}
stable = exceptionNumber <= maxExceptionNumber;
if (stable) {
if (linearAccelerationZStableSection == 0) {
linearAccelerationZStableSection = (maxAccelerationZValue - minAccelerationZValue) / 2;
}
if (linearAccelerationZStableSection > maxStableOffset) {
linearAccelerationZStableSection = maxStableOffset;
}
}
MainActivity.UpdateStable(stable);
}
maxStableOffset 與 maxExceptionNumber 同樣是經驗係數,是依實際場景下的線性加速度分佈統計得出。至於「原本穩態、使用者突然拿起手機變成非穩態」該怎麼辦?這個問題會在敲擊辨識階段一併處理。
private void knockRecognition(float linearAccelerationZ) {
float linearAccelerationZAbsolute = Math.abs(linearAccelerationZ);
float linearAccelerationZAbsoluteRadio = linearAccelerationZAbsolute / linearAccelerationZStableSection;
if (linearAccelerationZAbsoluteRadio > recognitionUniqueRatio) {
uniqueLinearAccelerationZList.add(linearAccelerationZ);
currentForecastNumber = forecastNumber;
} else {
if (uniqueLinearAccelerationZList.size() > 0) {
if (currentForecastNumber > 0) {
currentForecastNumber--;
} else {
handleUniqueLinearAccelerationZ();
}
}
}
if (linearAccelerationZAbsoluteRadio < smoothSectionMaxRatio) {
float offsetWeight = 0.001f;
linearAccelerationZStableSection = weightedMean(offsetWeight, linearAccelerationZAbsolute, linearAccelerationZStableSection);
}
}
邏輯是這樣的:先算絕對值與波動區間的比值。若比值大於 recognitionUniqueRatio,代表手機正在受力,先把這個值放進「獨特線性加速度列表」等待後續確認;若比值小於等於門檻,代表手機回到相對穩定狀態,此時若列表不為空,就透過 currentForecastNumber 做一個寬限期,再決定要不要真正處理這批資料。
currentForecastNumber 存在的意義:一次敲擊可能產生兩個相近但不連續的峰值,若沒有這個寬限計數器,一次敲擊會被誤判成兩次。
至於「比值小於 smoothSectionMaxRatio 時平滑波動區間」,有兩個理由:一是手機狀態隨時在變,波動區間應該跟著調整;二是穩態辨識算出的區間可能不準,需要用最新資料持續學習。之所以要加上限,是因為比值過大基本上屬於異常狀態的資料,拿來平滑只會污染基準;如果實測資料的比值普遍超過上限,那大概說明手機根本不在穩態,等下一次穩態辨識重置即可。
private void handleUniqueLinearAccelerationZ() {
int recognitionKnockNumber = 1;
int uniqueLinearAccelerationZListLength = uniqueLinearAccelerationZList.size();
float accelerationZOffsetAbsolute;
float maxAccelerationZOffsetAbsolute = 0;
for (int i = 0; i < uniqueLinearAccelerationZListLength; i++) {
accelerationZOffsetAbsolute = Math.abs(uniqueLinearAccelerationZList.get(i));
if (maxAccelerationZOffsetAbsolute < accelerationZOffsetAbsolute) {
maxAccelerationZOffsetAbsolute = accelerationZOffsetAbsolute;
}
}
uniqueLinearAccelerationZList.clear();
// 資料點過多,判定為非穩態(例如使用者拿起手機)
if (uniqueLinearAccelerationZListLength > unstableListLength) {
stable = false;
MainActivity.UpdateStable(stable);
return;
}
if (maxAccelerationZOffsetAbsolute > linearAccelerationZStableSection * recognitionKnockRatio) {
knockRecognitionSuccess(recognitionKnockNumber);
}
}
這個方法同時完成兩件事:如果獨特資料點數量超過 unstableListLength,就判定為狀態轉為非穩態並直接返回;否則取出最大偏移值,若超過波動區間的 recognitionKnockRatio 倍,就確認為一次敲擊。
流程走到這裡就完整了。但必須誠實說:這套方法仍有誤判。iOS 的 Knock 我實際用過,辨識率高得對得起它的售價,推測背後應該有一套更嚴謹的係數歸納,甚至可能用了機器學習。本文提供的只是一種可行的思路,不能說它成熟,因為它並未經過真實使用者的長期考驗。
這是我寫的第三篇筆記。第一篇挑的是為 MP3 寫入 ID3 標籤——偏門但規範明確;第二篇是音頻合成——同樣有標準可循。敲擊偵測則寬鬆得多,沒有唯一正解,所以這次我特別加了一節「實現思路」,因為連我自己都無法確定思路是否完全正確。感測器的應用有無限可能,大膽嘗試、錯了換方向就好。
如果你想在自己的專案裡做得更好,幾個值得嘗試的方向:改用 LinearAcceleration 並針對機型做能力偵測、以 TYPE_SIGNIFICANT_MOTION 這類系統事件輔助判斷、或用一段時間收集真實樣本訓練簡單的分類模型。演算法可以換,感測器也可以換,重點是把「穩態 → 峰值 → 確認」這個骨架留住。
Android 進程間通信常用方式解析
進程間通信概述 Android 中常見的進程間通信方式包括 Intent、ContentProvider、File、Socket 等。Intent 與 ContentPr
Android Handler 實現執行緒間通訊:主執行緒與子執行緒的雙向溝通
在日常開發中,我們經常需要把背景執行緒的運算結果回傳給主執行緒(UI 執行緒)來更新介面。本文就來深入探討 Handler 的訊息傳遞機制,不只涵蓋子執行緒向主執行緒發送
Android 圖片上傳與即時預覽效果實作
動手寫程式之前,先把需求與邏輯梳理清楚,後續的思路就會清晰許多。這裡要實現的功能如下: 1. 多圖上傳首先得能選圖(此專案要求既支援拍照上傳,也支援從相冊挑選)。 2.
ViewPager 詳解(一):初識 ViewPager 與 PagerAdapter 家族
引言 近期因工作需要在客制化系統,接觸到大量與 ViewPager 相關的 UI。值得注意的是,即便在底層原生介面中,ViewPager + Fragment 依然是主流