Reputation: 380
I am in a situation where i need an alert dialog to pop up after some seconds. I tried Handler with postDelayed(), it didn't work.
new Handler().postDelayed(new
Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(
MyActivity.this);
builder.setTitle("My title... ");
builder. setMessage("my msg..");
builder. setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Log. e("info", "OK");
}
});
builder.show();
}
});
}
}, 33000);
Upvotes: 7
Views: 9090
Reputation: 158
I know it's an old question by I think the problem might be that you aren't running from the main (UI) thread.
Make sure your handler is associated with the main thread with
new Handler(Looper.getMainLooper()).postDelayed(...);
Hope this helps!
Upvotes: 1
Reputation: 478
private Thread mMainThread;
mMainThread = new Thread(){
@Override
public void run(){
try{
synchronized (this) {
wait(33);
try{
AlertDialog.Builder builder = new AlertDialog.Builder(
MyActivity.this);
builder.setTitle("My title... ");
builder. setMessage("my msg..");
builder. setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Log. e("info", "OK");
}
});
builder.show();
}catch(Exception e){
}
}
}catch (Exception e) {
}
}};
Hope it helps
Upvotes: 0
Reputation: 282
You have to add this piece of code below builder.show(); It works for me.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 1500); // 1500 seconds
Edit:
I use this in a different way that I could see in your case. Here you can see my complete code. In my case I only want that apears a "simulate" Progress Dialog, and after some time it disappears.
protected void ActiveProgressDialog() {
final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", getResources().getString(R.string.carregantInfo), true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 1500); // 1500 milliseconds
}
}
Upvotes: 8