android耳機(jī)監(jiān)測(cè)
最近在做Marvell的項(xiàng)目,碰到個(gè)耳機(jī)熱插拔的問題,所以順便看了下相關(guān)代碼,這里來貢獻(xiàn)一下給大家。
本文引用地址:http://www.ex-cimer.com/article/201610/305871.htm我們這里以PXA的代碼為例,整個(gè)框架比較的簡(jiǎn)單清晰,上層是分別是HeadsetObserver.java以及HookSwitchObserver.java,
它們會(huì)直接讀取/sys/class/switch/中某一特定的設(shè)備的state,比如/sys/class/switch/h2w/state,來獲取最新的狀態(tài)。
我們把它分為兩部分來看
kernel/drivers/switch/
這里存放著headset以及hook的驅(qū)動(dòng)代碼,首先switch_class.c中會(huì)先注冊(cè)switch這個(gè)子類,并提供switch_dev_register這個(gè)注冊(cè)入口,
對(duì)應(yīng)的設(shè)備驅(qū)動(dòng)調(diào)用switch_dev_register把自己注冊(cè)在switch這個(gè)子類中,比如:
switch_data_headset->sdev.name = pdata_headset->name; //name is h2w
switch_data_headset->name_on = pdata_headset->name_on;
switch_data_headset->name_off = pdata_headset->name_off;
switch_data_headset->state_on = pdata_headset->state_on;
switch_data_headset->state_off = pdata_headset->state_off;
switch_data_headset->sdev.print_state = switch_headset_print_state;
info->psw_data_headset = switch_data_headset;
ret = switch_dev_register(switch_data_headset->sdev);
那么在/sys/class/switch目錄中就會(huì)生成h2w這個(gè)子目錄,里面會(huì)有state,name等一些成員,而驅(qū)動(dòng)判斷耳機(jī)是否插入則是通過
gpio模擬中斷,在耳機(jī)插入的時(shí)候產(chǎn)生電平的變化來調(diào)用中斷回調(diào)函數(shù),回調(diào)函數(shù)中會(huì)改變state狀態(tài)值,就這么簡(jiǎn)單
frameworks/base/services/java/com/android/server/HeadsetObserver.java這是android耳機(jī)監(jiān)測(cè)的代碼
它會(huì)通過讀取/sys/class/switch/h2w/state來判斷此時(shí)是否有耳機(jī)插入,比如:
private static final String HEADSET_STATE_PATH = /sys/class/switch/h2w/state;
FileReader file = new FileReader(HEADSET_STATE_PATH);
然后通過
public void onUEvent(UEventObserver.UEvent event) {
if (LOG) Slog.v(TAG, Headset UEVENT: + event.toString());
try {
update(event.get(SWITCH_NAME), Integer.parseInt(event.get(SWITCH_STATE)));
} catch (NumberFormatException e) {
Slog.e(TAG, Could not parse switch state from event + event);
}
}
來更新耳機(jī)的檢測(cè)狀態(tài)。hook監(jiān)測(cè)和耳機(jī)監(jiān)測(cè)類似,這里就不再重復(fù)了,寫得有點(diǎn)亂,希望對(duì)朋友們有幫助。
評(píng)論