Reputation: 560
Im am trying to create a delayed action, when I touch the Display for more than 5 Seonds.
I am using a Handler and a Runnable for this, using handler.postDelayed(runnable, 5000);
I also want a ProgressBar, to show, when the Handler will kickoff. From researching i found, that i have to Override the handleMessage()
method.. this is what i tried.
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progress.setProgress(progress.getProgress() + 100);
sendEmptyMessageDelayed(0, 100);
}
};
private Runnable runnable = new Runnable() {
public void run() {
playAlarm();
}
};
...
progress = (ProgressBar) findViewById(R.id.progressBar1);
...
@Override
public boolean onTouchEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
// Execute Runnable after 5000 milliseconds = 5 seconds.
progress.setProgress(0);
handler.postDelayed(runnable, 5000);
mBooleanIsPressed = true;
}
if (e.getAction() == MotionEvent.ACTION_UP) {
if (mBooleanIsPressed) {
mBooleanIsPressed = false;
progress.setProgress(0);
handler.removeCallbacks(runnable);
}
}
return true;
}
It is not crashing. But the ProgressBar is simply not showing anything.
Upvotes: 1
Views: 1592
Reputation: 820
if you want to use a handler there some things missing, this should work (not tested):
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progress.setProgress(progress.getProgress() + 100);
if (mBooleanIsPressed)
sendEmptyMessageDelayed(0, 100);
}
};
private Runnable runnable = new Runnable() {
public void run() {
playAlarm();
}
};
...
progress = (ProgressBar) findViewById(R.id.progressBar1);
...
@Override
public boolean onTouchEvent(MotionEvent e) {
// only start your handler if the view isn't touched
if (e.getAction() == MotionEvent.ACTION_DOWN && !mBooleanIsPressed) {
// Execute Runnable after 5000 milliseconds = 5 seconds.
progress.setProgress(0);
handler.postDelayed(runnable, 5000);
// send the first empty message, which will be handled...
sendEmptyMessageDelayed(0, 100);
mBooleanIsPressed = true;
}
if (e.getAction() == MotionEvent.ACTION_UP) {
if (mBooleanIsPressed) {
mBooleanIsPressed = false;
progress.setProgress(0);
handler.removeCallbacks(runnable);
}
}
return true;
}
feel free to ask if you have any questions
Upvotes: 1