这是我在查找有关超时的事情时出现的问题。我已经实现了一个使用AsyncTask
,Handler
和的答案Runnable
。我在这里提供我的答案,作为未来答案搜索者的潜在模板。
private class DownloadTask extends AsyncTask<Void, CharSequence, Void> {
//timeout timer set here for 2 seconds
public static final int timerEnd = 2000;
private Handler timeHandler = new Handler();
@Override
protected void onPreExecute() {
ProgressDialog dProgress = new ProgressDialog(/*Context*/);
dProgress.setMessage("Connecting...");
dProgress.setCancelable(false);
dProgress.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Dismissing dProgress
dialog.dismiss();
//Removing any Runnables
timeHandler.removeCallbacks(handleTimeout);
//cancelling the AsyncTask
cancel(true);
//Displaying a confirmation dialog
AlertDialog.Builder builder = new AlertDialog.Builder(/*Context*/);
builder.setMessage("Download cancelled.");
builder.setCancelable(false);
builder.setPositiveButton("OK", null);
builder.show();
} //End onClick()
}); //End new OnClickListener()
dProgress.show();
} //End onPreExecute()
@Override
protected Void doInBackground(Void... params) {
//Do code stuff here
//Somewhere, where you need, call this line to start the timer.
timeHandler.postDelayed(handleTimeout, timerEnd);
//when you need, call onProgressUpdate() to reset the timer and
//output an updated message on dProgress.
//...
//When you're done, remove the timer runnable.
timeHandler.removeCallbacks(handleTimeout);
return null;
} //End doInBackground()
@Override
protected void onProgressUpdate(CharSequence... values) {
//Update dProgress's text
dProgress.setMessage(values[0]);
//Reset the timer (remove and re-add)
timeHandler.removeCallbacks(handleTimeout);
timeHandler.postDelayed(handleTimeout, timerEnd);
} //End onProgressUpdate()
private Runnable handleTimeout = new Runnable() {
public void run() {
//Dismiss dProgress and bring up the timeout dialog
dProgress.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(/*Context*/);
builder.setMessage("Download timed out.");
builder.setCancelable(false);
builder.setPositiveButton("OK", null);
builder.show();
}
}; //End Runnable()
} //End DownloadTask class
对于那些对使用有些陌生的人AsyncTask
,您必须DownloadTask object
拨打电话.execute()
。
例如:
DownloadTask dTaskObject = new DownloadTask();
dTaskObject.execute();
实际上,通过让我的所有代码都通过一个函数完成,我实际上还比你看到的更进一步doInBackground()
,所以我实际上不得不使用该对象调用onProgressUpdate()
和其他函数。DownloadTask