馬上加入Android 台灣中文網,立即免費下載應用遊戲。
您需要 登錄 才可以下載或查看,沒有帳號?註冊
x
通過Socket + Instrumentation實現模擬鍵盤滑鼠事件主要通過以下三個部分組成:
Socket編程:實現PC和Emulator通訊,並進行循環監聽
Service服務:將Socket的監聽程式放在Service中,從而達到後台執行的目的。這裡要說明的是啟動服務有兩種方式,bindService和startService,兩者的區別是,前者會使啟動的Service隨著啟動Service的Activity的消亡而消亡,而startService則不會這樣,除非顯式調用stopService,否則一直會在後台執行因為Service需要通過一個Activity來進行啟動,所以採用startService更適合當前的情形
Instrumentation發送鍵盤滑鼠事件:Instrumentation提供了豐富的以send開頭的函數接口來實現模擬鍵盤滑鼠,如下所述:
sendCharacterSync(int keyCode) //用於發送指定KeyCode的按鍵
sendKeyDownUpSync(int key) //用於發送指定KeyCode的按鍵
sendPointerSync(MotionEvent event) //用於模擬Touch
sendStringSync(String text) //用於發送字符串
注意:以上函數必須通過Message的形式拋到Message隊列中。如果直接進行調用加會導致程式崩潰。
對於Socket編程和Service網上有很多成功的範例,此文不再累述,下面著重介紹一下發送鍵盤滑鼠模擬事件的代碼:
發送鍵盤KeyCode:
步驟1. 聲明類handler變量
private static Handler handler;
步驟2. 循環處理Message
java代碼:- //在Activity的onCreate方法中對下列函數進行調用
- private void createMessageHandleThread(){
- //need start a thread to raise looper, otherwise it will be blocked
- Thread t = new Thread() {
- public void run() {
- Log.i( TAG,"Creating handler ..." );
- Looper.prepare();
- handler = new Handler(){
- public void handleMessage(Message msg) {
- //process incoming messages here
- }
- };
- Looper.loop();
- Log.i( TAG, "Looper thread ends" );
- }
- };
- t.start();
- }
複製代碼 步驟3. 在接收到Socket中的傳遞訊息後拋出Message
java代碼:- handler.post( new Runnable() {
- public void run() {
- Instrumentation inst=new Instrumentation();
- inst.sendKeyDownUpSync(keyCode);
- }
- } );
複製代碼 Touch指定坐標,如下例子即
java代碼:- touch point(240,400)
- Instrumentation inst=new Instrumentation();
- inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 240, 400, 0));
- inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 240, 400, 0));
複製代碼 模擬滑動軌跡
將上述方法中間添加 MotionEvent.ACTION_MOVE |
評分
-
查看全部評分
|