我有一系列在 onclick 方法中以菊花链形式连接的 AlertDialogs。在最后一个我需要向 URL 发送调用并等待响应。一旦响应返回,我需要获取响应的消息并创建最后一个 AlertDialog。问题是这在 2.3 Android 中有效,但由于 REST http 调用在 UI 线程上运行,因此对 Android 4.0 的最新更改出错了。所以我想把它移到一个 AsyncTask 中。我通读了教程,但没有找到我的具体困境。这是我的代码:如何让 AlertDialog 等待响应,并在等待时显示 ProgressDialog 或 Spinner?我正在寻找一些优雅的东西,其中 AsyncTask 是一个通用调用,并且可以在其他情况下用于 REST 调用。
public void onClick(View view) {
if(alert != null && alert.isShowing()) {
break;
}
alert = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.alertPingTitle1).toString())
.setMessage(getResources().getString(R.string.alertPingMessage1).toString())
.setPositiveButton(getResources().getString(R.string.alertPingPositive1).toString(),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (onClicked) {
log.info("Preventing multiple clicks to Ping Node Id");
return;
}
onClicked = true;
String returnMessage = "";
int iconId = 0;
try {
String url = String.format(getResources().getString(R.string.urlIdPing).toString(), getRestUrl(), getId() );
// This is where the Rest call will happen in an AsyncTask
AsyncRest rest = new AsyncRest( Preferences.this );
rest.execute( new RestObject(type,null,null,true,false) );
..........................
// This is the current state of the 2.3 code
JSONObject sent = RestRequest.sendPost(RestHttp.createHttpClient(), url, null, true);
if (sent != null && sent.getInt("response") == 200) {
returnMessage = "VALID REST call ";
iconId = android.R.drawable.ic_dialog_info;
} else {
if (sent != null) {
returnMessage = "INVALID REST response " + "\n\n Response code: " + sent.getInt("response");
} else {
returnMessage = "INVALID REST call.";
}
iconId = android.R.drawable.ic_dialog_alert;
}
} catch(JSONException e) {
returnMessage = "Errored in JSON payload.";
}
alert = new AlertDialog.Builder(SetPreferences.this)
.setTitle(getResources().getString(R.string.alertPingTitle2).toString())
.setMessage(returnMessage)
.setIcon(iconId)
.setPositiveButton(getResources().getString(R.string.alertOkay).toString(),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
}
})
}).show();
onClicked = false;
}