Android開發(fā)中如何模擬輸入
主要思路是使用 adb shell input指令來模擬按鍵及觸摸輸入。
但是前提是需要root,且華為手機出于安全考慮已經(jīng)停止了root解碼。所以測試建議換個別的手機。或是直接用AS中的模擬器,用有Google Apis的版本。
input 指令我們打開adb,進入shell,輸入input可以看到指令的參數(shù)說明。
其中source一般都是用的默認值可以忽略,我們主要關(guān)注的就是后面的command
text:文本輸入;keyevent:鍵盤按鍵;這兩條指令是所有設(shè)備通用的。 tap:點擊屏幕;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.輸入之前需要提前獲取焦點。2.輸入有特殊含義的特殊字符,無法直接輸入 需要使用keyevent 如: ’ ’
我們整一個EditText,然后進行text輸入測試。
execShellCmd('input text ’hello,world’');
我們發(fā)現(xiàn)少了一個H,在控制臺可以看到日志。
可以看到在按下H的時候,EditText沒有獲取到焦點。
可能是頁面初始化以后就開始執(zhí)行輸入操作,此時editText還沒有獲取到焦點,獲取焦點可能存在點延時。所以我們嘗試延遲1s后進行輸入。
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,然后輸入’,然后左移光標
常見的keycode可以參見frameworks/base/core/java/android/view/KeyEvent.java
android 中坐標系如下圖所示。
我們可以打開手機中的 開發(fā)者選項 -> 指針位置 來輔助定位,可以再上方看到x,y相對的偏移量。
點擊屏幕(100,200)位置。
execShellCmd('input tap 100 200');swipe
滑動屏幕和tap相似只需要傳入兩個坐標即可。后面也可以設(shè)置滑動時間(ms),時間越短滑動的相應(yīng)距離就會越長。
從屏幕(100,200)滑動到(300,400)。
execShellCmd('input swipe 100 200 300 400');
以上就是Android開發(fā)中如何模擬輸入的詳細內(nèi)容,更多關(guān)于Android 模擬輸入的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Docker Alpine鏡像時區(qū)問題完美解決方案2. SpringBoot+SpringCache實現(xiàn)兩級緩存(Redis+Caffeine)3. 詳解php如何合并身份證正反面圖片為一張圖片4. php設(shè)計模式之模板模式實例分析【星際爭霸游戲案例】5. AJAX實現(xiàn)省市縣三級聯(lián)動效果6. 專家預(yù)言:PHP將比Java更好更受歡迎7. Spring @Primary和@Qualifier注解原理解析8. ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解9. Java基于redis和mysql實現(xiàn)簡單的秒殺(附demo)10. 詳解springBoot啟動時找不到或無法加載主類解決辦法
