i have an app that contains a dialog
i want to close this dialog after x second, when user haven't any interact with app, like volume seekbar popup(that's open when the volume button clicked, and closed after 2 second of inactivity). what is the simplest way to implement this?
thank you
You could for example use a Handler and call its .removeCallbacks() and .postDelayed() method everytime the user interacts with the dialog.
Upon an interaction, the .removeCallbacks() method will cancel the execution of .postDelayed(), and right after that, u start a new Runnable with .postDelayed()
Inside this Runnable, you could close the dialog.
// a dialog
final Dialog dialog = new Dialog(getApplicationContext());
// the code inside run() will be executed if .postDelayed() reaches its delay time
final Runnable runnable = new Runnable() {
@Override
public void run() {
dialog.dismiss(); // hide dialog
}
};
Button interaction = (Button) findViewById(R.id.bottom);
final Handler h = new Handler();
// pressing the button is an "interaction" for example
interaction.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
h.removeCallbacks(runnable); // cancel the running action (the hiding process)
h.postDelayed(runnable, 5000); // start a new hiding process that will trigger after 5 seconds
}
});
For tracking user interaction, you could use:
@Override
public void onUserInteraction(){
h.removeCallbacks(runnable); // cancel the running action (the hiding process)
h.postDelayed(runnable, 5000); // start a new hiding process that will trigger after 5 seconds
}
Which is available in your activity.
I like to do this with AsyncTask:
class ProgressDialogTask extends AsyncTask<Integer, Void, Void> {
public static final int WAIT_LENGTH = 2000;
private ProgressDialog dialog;
public ProgressDialogTask(Activity activity) {
dialog = new ProgressDialog(activity);
}
@Override
protected void onPreExecute() {
dialog.setMessage("Loading");
}
@Override
protected Void doInBackground(final Integer... i) {
long start = System.currentTimeMillis();
while(!isCancelled()&&System.currentTimeMillis()-start< WAIT_LENGTH){}
return null;
}
@Override
protected void onPostExecute(final Void v) {
if(dialog.isShowing()) {
dialog.dismiss();
}
}
}
Then trigger it from your Activity on click:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ProgressDialogTask task = new ProgressDialogTask(this);
task.execute(0);
}
});
If you need better precision you can also use System.nanoTime()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With