通過Socket + Instrumentation實現(xiàn)模擬鍵盤鼠標(biāo)事件主要通過以下三個部分組成:
Socket編程:實現(xiàn)PC和Emulator通訊,并進行循環(huán)監(jiān)聽
Service服務(wù):將Socket的監(jiān)聽程序放在Service中,從而達到后臺運行的目的。這里要說明的是啟動服務(wù)有兩種方式,bindService和startService,兩者的區(qū)別是,前者會使啟動的Service隨著啟動Service的Activity的消亡而消亡,而startService則不會這樣,除非顯式調(diào)用stopService,否則一直會在后臺運行因為Service需要通過一個Activity來進行啟動,所以采用startService更適合當(dāng)前的情形
Instrumentation發(fā)送鍵盤鼠標(biāo)事件:Instrumentation提供了豐富的以send開頭的函數(shù)接口來實現(xiàn)模擬鍵盤鼠標(biāo),如下所述:
sendCharacterSync(int keyCode) //用于發(fā)送指定KeyCode的按鍵
sendKeyDownUpSync(int key) //用于發(fā)送指定KeyCode的按鍵
sendPointerSync(MotionEvent event) //用于模擬Touch
sendStringSync(String text) //用于發(fā)送字符串
注意:以上函數(shù)必須通過Message的形式拋到Message隊列中。如果直接進行調(diào)用加會導(dǎo)致程序崩潰。
對于Socket編程和Service網(wǎng)上有很多成功的范例,此文不再累述,下面著重介紹一下發(fā)送鍵盤鼠標(biāo)模擬事件的代碼:
發(fā)送鍵盤KeyCode:
步驟1. 聲明類handler變量
private static Handler handler;
步驟2. 循環(huán)處理Message
java代碼:
[font=宋體]//在Activity的onCreate方法中對下列函數(shù)進行調(diào)用
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(); //主線程創(chuàng)建時,會創(chuàng)建一
個默認(rèn)的Looper對象,而Looper對象的創(chuàng)建,將自動創(chuàng)建一個Message Queue。其他非主線程,不會自動創(chuàng)建Looper,要需要的時候,通過調(diào)
用prepare函數(shù)來實現(xiàn)。
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指定坐標(biāo),如下例子即
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