Android開發(fā)中如何模擬輸入
主要思路是使用 adb shell input指令來模擬按鍵及觸摸輸入。
但是前提是需要root,且華為手機(jī)出于安全考慮已經(jīng)停止了root解碼。所以測試建議換個(gè)別的手機(jī)?;蚴侵苯佑肁S中的模擬器,用有Google Apis的版本。
input 指令我們打開adb,進(jìn)入shell,輸入input可以看到指令的參數(shù)說明。
其中source一般都是用的默認(rèn)值可以忽略,我們主要關(guān)注的就是后面的command
text:文本輸入;keyevent:鍵盤按鍵;這兩條指令是所有設(shè)備通用的。 tap:點(diǎn)擊屏幕;swipe:滑動屏幕;這兩條指令適用于有觸摸屏的設(shè)備。 press,roll適用于有觸摸球的設(shè)備。模擬輸入在使用input指令之前我們要先獲取一下root權(quán)限。
private void execShellCmd(String cmd) { try { Process process = Runtime.getRuntime().exec('su'); OutputStream outputStream = process.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream( outputStream); dataOutputStream.writeBytes(cmd); dataOutputStream.flush(); dataOutputStream.close(); outputStream.close(); } catch (Throwable t) { t.printStackTrace(); } }text
1.輸入之前需要提前獲取焦點(diǎn)。2.輸入有特殊含義的特殊字符,無法直接輸入 需要使用keyevent 如: ’ ’
我們整一個(gè)EditText,然后進(jìn)行text輸入測試。
execShellCmd('input text ’hello,world’');
我們發(fā)現(xiàn)少了一個(gè)H,在控制臺可以看到日志。
可以看到在按下H的時(shí)候,EditText沒有獲取到焦點(diǎn)。
可能是頁面初始化以后就開始執(zhí)行輸入操作,此時(shí)editText還沒有獲取到焦點(diǎn),獲取焦點(diǎn)可能存在點(diǎn)延時(shí)。所以我們嘗試延遲1s后進(jìn)行輸入。
private Handler handler = new Handler();private Runnable task = new Runnable() { public void run() { execShellCmd('input text ’hello,world’'); }};// 延遲1s后輸入handler.postDelayed(task,1000);
execShellCmd('input text ’hello,world’ n input keyevent 68 n input keyevent 21');
輸入hello,world,然后輸入’,然后左移光標(biāo)
常見的keycode可以參見frameworks/base/core/java/android/view/KeyEvent.java
android 中坐標(biāo)系如下圖所示。
我們可以打開手機(jī)中的 開發(fā)者選項(xiàng) -> 指針位置 來輔助定位,可以再上方看到x,y相對的偏移量。
點(diǎn)擊屏幕(100,200)位置。
execShellCmd('input tap 100 200');swipe
滑動屏幕和tap相似只需要傳入兩個(gè)坐標(biāo)即可。后面也可以設(shè)置滑動時(shí)間(ms),時(shí)間越短滑動的相應(yīng)距離就會越長。
從屏幕(100,200)滑動到(300,400)。
execShellCmd('input swipe 100 200 300 400');
以上就是Android開發(fā)中如何模擬輸入的詳細(xì)內(nèi)容,更多關(guān)于Android 模擬輸入的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
