2012-11-13 110 views
2

我正在嘗試開發一項服務,在服務與某些硬件/遠程服務器交互時向系統注入觸摸事件。我已使用Google搜索,並且所有人都建議使用InputManager課程,並將Monkey作爲示例項目。爲什麼我沒有InputManager.getInstance()?和injectInputEvent()?

但是,InputManager對我沒有getInstance()方法!我所能訪問的只是documentation所顯示的內容。沒有getInstance()方法,最重要的是沒有injectInputEvent()方法。

我的構建目標SDK是Android 4.1.2,我的AndroidManifest.xml文件指定了16的目標SDK版本(我試圖將min目標也更改爲16,這並沒有幫助(加上我會如果可能的話保持在8))。

我怎麼可以像猴子一樣使用InputManager?猴子使用的方法在哪裏,爲什麼我不能使用它們?

+1

「注入觸摸事件的服務」不起作用。只有系統可以做到這一點。請參閱http://stackoverflow.com/questions/5635486/android-keyevent-injection-requires-system-permissions它是關於關鍵事件,但觸摸相同 – zapl

回答

1
Class cl = InputManager.class; 
try { 
    Method method = cl.getMethod("getInstance"); 
    Object result = method.invoke(cl); 
    InputManager im = (InputManager) result; 
    method = cl.getMethod("injectInputEvent", InputEvent.class, int.class); 
    method.invoke(im, event, 2); 
} 
catch (IllegalAccessException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IllegalArgumentException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (NoSuchMethodException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
}catch (InvocationTargetException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
+0

我得到了InputManager實例,但它仍然沒有用,感嘆! – JulianHe

0

也許這有點晚,但可能有助於未來的參考。

方法1:使用的儀器對象

Instrumentation instrumentation = new Instrumentation(); 
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); 
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)); 

方法2:使用內部API與反射

此方法使用反射來訪問內部API。

private void injectInputEvent(KeyEvent event) { 
    try { 
     getInjectInputEvent().invoke(getInputManager(), event, 2); 
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { 
     e.printStackTrace(); 
    } 
} 

private static Method getInjectInputEvent() throws NoSuchMethodException { 

    Class<InputManager> cl = InputManager.class; 
    Method method = cl.getDeclaredMethod("injectInputEvent", InputEvent.class, int.class); 
    method.setAccessible(true); 
    return method; 
} 

private static InputManager getInputManager() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { 
    Class<InputManager> cl = InputManager.class; 
    Method method = cl.getDeclaredMethod("getInstance"); 
    method.setAccessible(true); 
    return (InputManager) method.invoke(cl); 
} 

injectInputEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); 
injectInputEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)); 

請注意:方法1是基於公共API一個乾淨的解決方案,並在內部,它使用從方法2相同的調用。

另請注意,這兩種方法都不能從MainThread調用。