Daniele B
Daniele B

Reputation: 20412

Android: show a dialog after 5 seconds

I would like to show an alert dialog, after 5 seconds I am on a certain fragment.

Which is the safest way to do that? avoiding for example to show the dialog in case the fragment is in the process of being paused or destroyed

any suggestion?

Upvotes: 1

Views: 5234

Answers (2)

swapnil gandhi
swapnil gandhi

Reputation: 816

     final ProgressDialog dialog= ProgressDialog.show(this,"Doing something", "Please wait....",true);  
     new Thread(new Runnable() {  
         @Override  
         public void run() {  
             try {  
             Thread.sleep(5000);  
                 dialog.dismiss();  
             }  
             catch(InterruptedException ex){  
                 ex.printStackTrace();  
             }  
         }  
     }).start();  
 

This solution worked for me. It dismisses dialog automatically.

Upvotes: 0

joao2fast4u
joao2fast4u

Reputation: 6892

Use this code inside your Fragment onCreateView() method:

            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    if(this!=null && !isFinishing()){
                        final ProgressDialog dialog = ProgressDialog.show(YourActivity.this,
                                "Please Wait... ", "Loading... ", false, true);
                        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    }
                }
            }, 5000);

This will show a ProgressDialog within 5 seconds. Once the 5 seconds pass, it checks if the Activity is not null or if it is not in the process of finishing. In case it is not, your ProgressDialog shows, and you can cancel it just by hitting back button.

Upvotes: 4

Related Questions