通過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代碼:
[font=宋體]//在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(); //主線程創建時,會創建一
個默認的Looper對象,而Looper對象的創建,將自動創建一個Message Queue。其他非主線程,不會自動創建Looper,要需要的時候,通過調
用prepare函數來實現。
handler = new Handler(){
public void handleMessage(Message msg) {
//process incoming messages here
}
};
Looper.loop();
Log.i( TAG, "Looper thread ends" );
}
};
t.start();
}[/font]
步驟3. 在接收到Socket中的傳遞信息后拋出Message
java代碼:
[font=宋體]handler.post( new Runnable() {
public void run() {
Instrumentation inst=new Instrumentation();
inst.sendKeyDownUpSync(keyCode);
}
} );[/font]
Touch指定坐標,如下例子即
java代碼:
[font=宋體]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));[/font]
模擬滑動軌跡
將上述方法中間添加 MotionEvent.ACTION_MOVE