Simulate Touch Controls Through Code

こ雲淡風輕ζ 提交于 2019-11-30 23:47:19

The Solution

In the end I went a different direction then the one I mentioned in my edit above.

I found out that it is possible to call touch controls in the shell by using

adb shell input keyevent <keycode here>

I then found a way to use this in android, I have the following class named issueKey

public class issueKey {
public void issueKey(int keyCode)
{
    try {
        java.lang.Process p = java.lang.Runtime.getRuntime().exec("input keyevent " + Integer.toString(keyCode) + "\n");
    } catch (Exception e) {
        Log.wtf("IssueKeyError", e.getMessage());
    }
}
}

Then I simply call the class and pass the keycode for the corresponding gesture

mIssueKey.issueKey(4);//functions as swipe down

Here is the list of keycodes that I tested for anyone that is interested.

Keys for each respective button/gesture

  • 4: Swipe Down
  • 21: Swipe Left
  • 22: Swipe Right
  • 23: Tap
  • 24: Volume Up
  • 25: Volume Down
  • 26: Lock/Unlock Screen
  • 27: Camera Button

However, what I'm wondering now is. What would be best practice, getting the solution I metioned in my edit to work by using a asyncTask or is the solution I'm currently using better.

Using the Instrumentation class would work if you use a separate thread to call the sendKeyDownUpSync method from.

This can be done using the following steps:

  1. Create and start a thread from your activity
  2. In the run method, use the Looper class and create a Handler as explained here
  3. Every time you want to call sendKeyDownUpSync, post a Runnable instance to the Handler, which calls sendKeyDownUpSync in its run method.

A similar code sample (not from me) is available here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!