0

I've written an app, touch button, and then open an other app(like facebook), then I want to do touchevent by coordinate, but it not work. It seems like a hack, but actually do screen touch, Does anyone know why the dispatchTouchEvent not work? Is it because of the security? so how to let it work....Thanks.

 private void jumpApp(String appName) {
    System.out.println("entry");
    // TODO Auto-generated method stub
    Toast.makeText(MainActivity.this, "Jumping app...", Toast.LENGTH_LONG).show();
    PackageManager pm = getPackageManager();
    Intent intent = pm.getLaunchIntentForPackage(appName);
    startActivity(intent);
    Log.d(TAG, "sleep 3000ms");
    sleep(5000);
    Log.d(TAG, "after 3000ms");
    Toast.makeText(MainActivity.this, "continue...", Toast.LENGTH_LONG).show();
    touchEvent(385, 466);
 }

private void touchEvent(int x, int y) {
    long firstTime = SystemClock.uptimeMillis();
    final MotionEvent firstEvent = MotionEvent.obtain(firstTime, firstTime,
            MotionEvent.ACTION_DOWN, x, y, 0);

    long secondTime = firstTime + 30;
    final MotionEvent secondEvent = MotionEvent.obtain(secondTime,
            secondTime, MotionEvent.ACTION_UP, x, y, 0);

    dispatchTouchEvent(firstEvent);
    dispatchTouchEvent(secondEvent);        
}
Awakening
  • 3,615
  • 8
  • 35
  • 51

1 Answers1

-1

I don't think you know what dispatchTouchEvent is. It does not generate touch events, it is used to process those events. It is obviously bound to your activity, not the device, so it cannot be used to send touch events to other apps / activities, although you could use it to fake touch events within your own activity.

You cannot fake touch events across apps, that would be a serious security flaw and barely has any practical use. There are ways to fake events using ADB or root access, but luckily not using standard Android APIs.

Update: Okay, to be honest there are some dirty ways to inject events into the system, have a look at this question.

Community
  • 1
  • 1
Tobias
  • 7,723
  • 1
  • 27
  • 44
  • I tried to use ADB, and the touch works, but I want it work without connect pc. Is ADB only exist on pc, right? My device has the root access, so you mean I can run some script to heck this touch? or some other way, could you show me the way? Thanks. – Awakening Sep 08 '14 at 14:42
  • @Awakening I added a link to a related topic to my answer (it is actually possible, just really dirty). Please accept this answer if it answers your question about `dispatchTouchEvent`. – Tobias Sep 08 '14 at 15:02