Handler postDelayed doesn't post on delayed?
-
05-06-2021 - |
Question
I want to change some values onBackPressed method... And i override it like this:
@Override
public void onBackPressed() {
final Handler backHandler = new Handler();
backHandler.postDelayed(new Runnable() {
public void run() {
exitCount = 0;
Log.d("exitCount", "exitCount: " + exitCount);
}
}, Toast.LENGTH_SHORT);
}
But the problem is handler posts immediately... There's no delay. Where am i doing wrong? Sorry if this is a lame question, i'm pretty new on Android. Thanks in advance.
Solution
That is because Toast.LENGTH_SHORT
value is zero. Try declaring your constant with a delay value you choose. see here
OTHER TIPS
Make the handler part of an activity (or part of a thread you are posting a message to if its not for the UI thread), and use a millisecond delay rather than Toast.LENGTH_SHORT which has a value of zero so it will happen instantly.
public class SomeActivity extends Activity {
private Handler mHandler = new Handler();
@Override
public void onBackPressed() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("tag", "Hello, Handler!");
}
}, 1000); // one second
}
}
Use belo code I hope it will work.
runOnUiThread(new Runnable() {
@Override
public void run() {
backHandler.postDelayed(new Runnable() {
public void run() {
exitCount = 0;
Log.d("exitCount", "exitCount: " + exitCount);
}
}, Toast.LENGTH_SHORT);
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow