我有一系列在onclick方法中以菊花鏈方式連接的AlertDialog。在最後一個我需要發送一個URL調用並等待響應。一旦響應回來,我需要採取響應的消息並創建最後一個AlertDialog。問題是在2.3 Android中有效,但由於REST http調用在UI線程上運行,所以最新更改了Android 4.0錯誤。所以我想把它移到一個AsyncTask。我通讀了教程,但還沒有找到我的具體困境。這裏是我的代碼:我如何使AlertDialog等待響應,並等待顯示ProgressDialog或Spinner?我在尋找優雅的地方,AsyncTask是一個通用調用,可以在其他情況下用於REST調用。Inner AlertDialog調用REST URL,我如何等待進度對話返回
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;
}
編輯的問題要問更具體的一個。我已經在使用AysyncTasks,不知道如何讓警報等待AsyncTask產生回調,因爲這些警報是嵌入的,並且在Activity的onClick方法中。如果需要,我也可以發佈我的AsyncTask。 – JPM 2013-02-08 21:14:30
在'onPostExecute'上發出信號提示關閉或任何需要它的提示 – howettl 2013-02-08 21:15:26
我已經知道所有這些了,但是我不知道如何在async被觸發時讓代碼中的警報等待它不會暫停UI線程。 – JPM 2013-02-08 21:19:11