Android開發中如何模擬輸入
主要思路是使用 adb shell input指令來模擬按鍵及觸摸輸入。
但是前提是需要root,且華為手機出于安全考慮已經停止了root解碼。所以測試建議換個別的手機。或是直接用AS中的模擬器,用有Google Apis的版本。
input 指令我們打開adb,進入shell,輸入input可以看到指令的參數說明。
其中source一般都是用的默認值可以忽略,我們主要關注的就是后面的command
text:文本輸入;keyevent:鍵盤按鍵;這兩條指令是所有設備通用的。 tap:點擊屏幕;swipe:滑動屏幕;這兩條指令適用于有觸摸屏的設備。 press,roll適用于有觸摸球的設備。模擬輸入在使用input指令之前我們要先獲取一下root權限。
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’');
我們發現少了一個H,在控制臺可以看到日志。
可以看到在按下H的時候,EditText沒有獲取到焦點。
可能是頁面初始化以后就開始執行輸入操作,此時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 中坐標系如下圖所示。
我們可以打開手機中的 開發者選項 -> 指針位置 來輔助定位,可以再上方看到x,y相對的偏移量。
點擊屏幕(100,200)位置。
execShellCmd('input tap 100 200');swipe
滑動屏幕和tap相似只需要傳入兩個坐標即可。后面也可以設置滑動時間(ms),時間越短滑動的相應距離就會越長。
從屏幕(100,200)滑動到(300,400)。
execShellCmd('input swipe 100 200 300 400');
以上就是Android開發中如何模擬輸入的詳細內容,更多關于Android 模擬輸入的資料請關注好吧啦網其它相關文章!
相關文章:
