Check if AsyncTask is taking too long

2019-07-14 18:05发布

I have an AsyncTask that get info from the web. Sometimes the connection fails and the AsyncTask processdialog is running forever.

In the doInBackground I have a check in the end if my catched info are empty and if this is the case, it should appear Positive button/Negative button, but this is not happening. The dialog is just running.

How can I check if an AsyncTask is taking too long time (Maybe 5 seconds) and dismiss the dialog?

Code snippet (doInBackground):

 //orders is my ArrayList<Order> object, from my own Order class.
 if(orders==null) {
                pdia.dismiss();
                AlertDialog.Builder alt_bld = new AlertDialog.Builder(ctx);
                alt_bld.setMessage("Try agin?")
                .setCancelable(false)
                .setPositiveButton("Try again", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    button_refresh.setVisibility(View.GONE);

                     new ListTask().execute(null, null , null);


                }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
                }

                });
                AlertDialog alert = alt_bld.create();
                alert.setTitle("Connection failed!");
                alert.show();
            }
            else {
                return orders;
            }

Thanks in advance and tell me if you need more info!

标签: android
2条回答
手持菜刀,她持情操
2楼-- · 2019-07-14 18:18

Instead of checking your result in doInBackground() you can get the value from the process and check it in onPostExecute(), like this:

protected void onPostExecute(ArrayList<Order> localOrders){
    super.onPostExecute(localOrders);
    if (localOrders==null) {
       // Paste the positive and negative DialogListeners here 
       // and dismiss the dialog.
    }
}

The result from your doInBackground() process passes into onPostExecute's parameter, thence you can check if your ArrayList object is empty or not.

查看更多
Fickle 薄情
3楼-- · 2019-07-14 18:28

But then writing the above code snippet in the onPostExecute will defeat the purpose right? We want the user to not wait past 5 seconds for an answer from the webservice and therefore we must handle the timeout within doInBackground itself.

查看更多
登录 后发表回答