關於部落格
  • 78070

    累積人氣

  • 2

    今日人氣

    0

    追蹤人氣

[Android] 模擬實體按鍵 (hard key)

先看圖:

    


final IWindowManager windowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));

在 onCreate() 中:
        Button volup = (Button) findViewById(R.id.volup);
        volup.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new Thread(new Runnable() {
                    public void run() {
                         /* Simulate a KeyStroke to the menu-button. */
                        simulateKeystroke(KeyEvent.KEYCODE_VOLUME_UP);
                    }
               }).start(); /* And start the Thread. */
               
        }});


然後設利用以下兩個函式:
    private void simulateKeystroke(int KeyCode) {
        doInjectKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyCode));
        doInjectKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyCode));

   }


   
    private void doInjectKeyEvent(KeyEvent kEvent) {
       
        try {
             windowManager.injectKeyEvent(kEvent, true);
                                
        } catch (Exception e) {
             e.printStackTrace();
        }
       
   }

接著可能會出現一些類別無法編譯的問題,
如 IWindowManager, ServiceManager...,
請依以下步驟解決:(假設用Eclipse)

  1. 在專案按下右鍵,選擇選單中的 "BuildPath| Configure Build path".
  2. 選擇標籤 Libraries.
  3. 按下按鈕 "Add library".
  4. 選擇 "User library" 後按下按鈕 next .
  5. 按下按鈕 "user library" .
  6. 按下按鈕"new" 。輸入一個library 名稱"layoutlib".
  7. 選擇 "layoutlib" library,後按下按鈕 "add jar"來新增 jar檔案 "D:android-sdk_r04-windowsandroid-sdk-windowsplatformsandroid-2.0.1datalayoutlib.jar"
  8. 按下按鈕 OK.
這樣就可以了。 

參考資源:
1. http://hi.baidu.com/zzliru/blog/item/23961bf20a487dc50b46e04e.html
2. http://www.eoeandroid.com/thread-57171-1-1.html
3. http://nathanwork.blogspot.com/2011/02/android-app-uri-menu-key.html
4. http://programfeelings.blogspot.com/2011/01/eclipse-can-not-find-class.html
相簿設定
標籤設定
相簿狀態