Try using onTouchListener()
and implementing onTouch(View v, MotionEvent e)
to check for the events ACTION_UP
and ACTION_DOWN
.
Implementation example:
Touch Release method in Android
Edit:
Reading over some of your discussions with others, I recommend having an AsyncTask
in your class that runs your update loop constantly, like so:
private static boolean doUpdate = false;
private class PaddleUpdater extends AsyncTask<String,Void,Void> {
@Override
protected Void doInBackground(String... strings) {
while(true) {
if(isCancelled()) { break; }
if(doUpdate) {
//update paddle
}
}
}
}
//in the constructor, do this
PaddleUpdater pu = new PaddleUpdater();
pu.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Then setup a BroadcastReceiver
in the class like this:
public static final String TOUCH_UPDATE = "com.packagename.intent.action.TOUCH_UPDATE";
private class TouchStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context c, Intent i) {
Bundle b = i.getExtras();
if (b != null) {
doUpdate = b.getBoolean("touch");
}
}
}
//in the constructor do this
registerReceiver(new UpdateReceiver(), new IntentFilter(TOUCH_UPDATE));
Then, in your main activity, setup your listener as described in @Lamorack's post, but add an intent broadcast:
view.setOnTouchListener(new OnTouchListener () {
public boolean onTouch(View view, MotionEvent event) {
Intent i = new Intent(<ClassName>.TOUCH_UPDATE);
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// The user just touched the screen
i.putExtra("touch", true);
sendBroadcast(i);
break;
case MotionEvent.ACTION_UP:
// The touch just ended
i.putExtra("touch", false);
sendBroadcast(i);
break;
}
return false;
}
});
Explanation:
So, what you need to do is track a certain state. Android tells you when the screen has been touched, and when it has been released, so we need to track the touch state based on those events. So we've set a boolean to track that state. When the touch case is triggered, we send an Intent
over to your class and tell it to change the boolean
it is tracking to true
. When the released case is triggered, we tell your class to change the boolean
it is tracking to false
.
The class itself has spun up an AsyncTask
that will basically run until you tell it to stop, manually. The loop in the AsyncTask
will constantly check the value of the boolean
, when it is true
, it will do the update, when it is false
, it will skip the update.
The BroadcastReceiver
we set up in your class is what actually receives the Intent
s being sent by your touch listener.