2012-11-13 106 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调用。