You'll need to use some view to register your touch listener. I chose the default RelativeLayout
. I've set the delay of the callback click to be 2 seconds.
Note that you need to save the last simulated touch (simulationEvent
) and check inside of your onTouchListener
if it's not that event. Without this check you would get repeated clicks in the same place over and over, as the simulation would call itself back.
If you want only the simulated touch to be registered, change the onTouchListener
's last return to true
.
package com.example.virtualclicker;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
/**
* Created by Simon on 2014 Jul 09.
*/
public class MainActivity extends ActionBarActivity {
private MotionEvent simulationEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.myLayout);
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event == simulationEvent)
return false;
int action = event.getAction();
int x = (int)event.getX();
int y = (int)event.getY();
Log.e("onTouchListener", "User touch at X:" + x + " Y:" + y);
long length = 0;
if (action == MotionEvent.ACTION_DOWN) {
click(v, x, y);
}
return false;
}
});
}
public void click(final View view, final int x, final int y) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// SIMULATION BEGINS HERE AFTER 2000 Millis ///
long touchTime = SystemClock.uptimeMillis();
simulationEvent = MotionEvent.obtain(touchTime, touchTime,
MotionEvent.ACTION_DOWN, x, y, 0);
view.dispatchTouchEvent(simulationEvent);
simulationEvent = MotionEvent.obtain(touchTime, touchTime,
MotionEvent.ACTION_UP, x, y, 0);
view.dispatchTouchEvent(simulationEvent);
Log.e("simulatedTouch","simulated touch executed at X:"+x+" Y:"+y);
}
}, 2000);
}
}
Hope this works for ya.
EDIT:
layout/activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"/>