我有一个从网络获取信息的 AsyncTask。有时连接失败并且AsyncTask进程对话框永远运行。
在 doInBackground 中,我最终会检查捕获的信息是否为空,如果是这种情况,它应该出现“肯定”按钮/“否定”按钮,但这没有发生。该对话框刚刚运行。
如何检查 AsyncTask 是否花费了太长的时间(可能 5 秒)并关闭对话框?
代码 fragment (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;
}
提前致谢,如果您需要更多信息,请告诉我!
最佳答案
您可以从进程中获取值并在 onPostExecute()
中检查它,而不是在 doInBackground()
中检查结果,如下所示:
protected void onPostExecute(ArrayList<Order> localOrders){
super.onPostExecute(localOrders);
if (localOrders==null) {
// Paste the positive and negative DialogListeners here
// and dismiss the dialog.
}
}
doInBackground()
过程的结果会传递到 onPostExecute
的参数中,因此您可以检查 ArrayList 对象是否为空或不是。
关于android - 检查 AsyncTask 是否花费太长的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3837445/