ProgressDialog for some specific time if I do not get a response

1.4k views Asked by At

I am using a ProgressDialog when I call an API and I close it after getting a response from the server but I want this ProgressDialog to appear only for 20 seconds. If the API response does not appear in 20 seconds then this ProgressDialog will close and then I will close my Activity too and showing 1 message. This is my approach:

myProgressDialog is defined in class level:

ProgressDialog myProgressDialog;
myProgressDialog= new ProgressDialog(FlyerActivity.this);
myProgressDialog.setMessage("Loading");
myProgressDialog.setCancelable(false);
myProgressDialog.show();
myAPIcallingMethod();

myAPIcallingMethod Implementation:

private void myAPIcallingMethod(){
    someAPICall;
    if (myProgressDialog.isShowing()){
        myProgressDialog.dismiss();
    }
}

Now here in someAPICall I want if API response is not coming after 20 seconds then this ProgressDialog will disappear.

3

There are 3 answers

0
Surya Prakash Kushawah On

Use this

  private static int TIME_OUT = 1000 * 20;
 new Handler(Looper.getMainLooper()).postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        //Do something here
                        progress.dismiss();
                    }
                }, TIME_OUT);
1
Nitesh On

Use Handler to put a delay of desired 20 seconds

Handler handler = new Handler(Looper.getMainLooper());

//This will get called when response is not received in 20 sec. **call this where you are hitting your server.**

   handler.postDelayed(new Runnable() {
    @Override
    public void run() {
    //hide Progressbar here or close your activity.
      if(progressbar!=null && progressbar.isShowing())
      {
      progressbar.dismiss();
      }

    }
},20*1000);


//**on Response**  remove the callback from that handler so that your app will not get crashed if service respond within 20 sec.

handler.removeCallbacksAndMessages(null);

Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you can simply put a desired timeout value in your case 20 sec on your api request.

0
Raymond On

My approach would be to be so set the timeout to 20 seconds on the APICall. Then have a specific callback for that, which in turn can dismiss the dialog.

I cannot see how your APICall works, so I can't really help on that end at this point.