I am working on Android project in which I want to call a function repetitively until I dont release touch from button so which event should I use?I am currently using ontouch listener but that calls the function once.
-
1Possible duplicate of [android repeat action on pressing and holding a button](http://stackoverflow.com/questions/10511423/android-repeat-action-on-pressing-and-holding-a-button) – Ralph Mar 14 '16 at 17:01
2 Answers
There is no such listener that will be called many times while you hold your finger on a button. This will pollute the UI message queue.
What you can do is to implement OnTouchListener
which has onTouch(View v, MotionEvent event)
method. The MotionEvent
object can be used for distinguishing actions such as ACTION_DOWN
and ACTION_UP
. Those are called when you press and release button respectively.
http://developer.android.com/reference/android/view/MotionEvent.html#ACTION_DOWN
So, after you detect the ACTION_DOWN
event, call your function as many times as you need. Stop calling it when you receive ACTION_UP
.
Be careful though, if you call your function on the UI thread there is a risk that you will block it. If that happens, consider using a Handler
or a background thread.

- 4,505
- 8
- 31
- 41
Use an onTouchListener to detect the button press. Then you can use a Handler or AlarmManager to call your event until a certain condition is reached:
this.handlerMethod = new MethodHandler(this);
boolean myCondition = false;
imageButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
if (myCondition == false) {
handlerMethod.sendEmptyMessageDelayed(0, 55000);
}
return true;
}
return false;
}
});
/**
* private static handler so there are no leaked activities.
*/
private static class MethodHandler extends Handler {
private final WeakReference<Home> activity;
public MyTimeHandler(Home activity) {
this.activity = new WeakReference<Home>(activity);
}
@Override
public void handleMessage(Message msg) {
if (activity.get() != null) {
activity.get().myMethod();
}
sendEmptyMessageDelayed(0, 55000);
}
}

- 7,828
- 12
- 64
- 106