裝置配有物理 WiFi 開關鍵,需實現「按一下切換 WiFi 開關狀態」。涉及 Linux Kernel 驅動、Android Framework、應用層服務多層協作。
思路:在按鍵驅動中攔截 WiFi 按鍵,直接調用 WiFi 驅動開關 API。
痛點:
結論:實現難度極大,不建議採用。
架構圖

核心流程:
KEY_F16 (186),ADC 採樣檢測按下/鬆開,寫入 sysfs 節點 /sys/devices/platform/misc_ctl/wifikey_onoff (1/0)。WifiManager.setWifiEnabled()。Kernel 按鍵定義 (RK3066 範例)
static struct rk29_keys_button key_button[] = {
// ...
{
.desc = "wifi",
.code = KEY_F16, // 186
.adc_value = 4,
.gpio = INVALID_GPIO,
.active_low = PRESS_LEV_LOW,
},
// ...
};
ADC 回調同步按鍵狀態
static void callback(struct adc_client *client, void *client_param, int result) {
// ... 遍歷按鍵判斷 ADC 範圍 ...
if (result in range) button->adc_state = 1; else button->adc_state = 0;
synKeyDone(button->code, pre_state, button->adc_state);
}
static void synKeyDone(int keycode, int pre, int cur) {
if (cur == pre) return;
if (keycode == KEY_F16) set_wifikey(cur); // 寫入 sysfs
}
Sysfs 節點實現
static ssize_t show_wifikey_onoff(struct device *dev, struct device_attribute *attr, char *buf) {
return sprintf(buf, "%d\n", combo_module.status_wifikey);
}
static ssize_t store_wifikey_onoff(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count) {
unsigned int val;
if (sscanf(buf, "%du", &val)) {
combo_module.status_wifikey = val ? 1 : 0;
}
return count;
}
static DEVICE_ATTR(wifikey_onoff, 0664, show_wifikey_onoff, store_wifikey_onoff);
Android 服務輪詢 (Kotlin)
class WifiToggleService : Service() {
private var running = false
private val handler = Handler(Looper.getMainLooper())
private val runnable = Runnable {
if (running) {
val pressed = WifiKeyJni.isKeyPressed() // JNI 讀取 sysfs
if (pressed != lastState) {
lastState = pressed
if (pressed) toggleWifi()
}
handler.postDelayed(this, 200) // 200ms 輪詢
}
}
private fun toggleWifi() {
val wifiManager = getSystemService(WIFI_SERVICE) as WifiManager
wifiManager.isWifiEnabled.let { wifiManager.setWifiEnabled(!it) }
}
override fun onCreate() {
super.onCreate()
running = true
handler.post(runnable)
}
override fun onDestroy() {
running = false
handler.removeCallbacks(runnable)
super.onDestroy()
}
}
在 InputReader / InputDispatcher 層攔截 KEY_F16,轉發給系統處理。需修改 AOSP 核心代碼,OTA 升級風險高,一般廠商定製才採用。
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Kernel 直接控制 | 延遲最低 | 強依賴廠商驅動、架構違規 | 極少見 |
| 系統服務輪詢 Sysfs | 架構清晰、不改 AOSP 核心、易維護 | 輪詢有微小延遲 (∼200ms) | 主流量產方案 |
| Input 子系統攔截 | 事件驅動、無輪詢 | 需修改 Framework、升級風險高 | 深度定製 ROM |
0664,屬於 system:system,僅系統服務可讀寫。android:exported="false",防止第三方惡意調用。InputDeviceListener 監聽實體按鍵,簡化 JNI 層。