Android類比鍵盤滑鼠事件

來源:互聯網
上載者:User

 通過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));

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.