我正在编写一个执行 Http 请求的函数(在 HttpPost、HttpClient 和 AsyncTask 的帮助下)并显示 AlertDialog if HttpClient.execute()
(在其中运行AsyncTask.doInBackground()
)需要太多时间。
AsyncTask.execute()
问题是我应该在被调用后等待一段时间,然后再显示消息。但是,如果我使用AsyncTask.get()
来阻止我的功能完成,则在 AsyncTask 完成之前,UI 中的任何内容都无法更改。这是代码示例:
{
HttpClient mHttpClient;
HttpPost mHttpPostAuth;
public Boolean openConnection()
{
//Checking if HttpClient.execute() is finished within 300 milliseconds
//howing the message if not
mScheduledThreadPoolExecutor.schedule(new Runnable(){
public void run(){
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if(!mResponseReceived){
try{
mWaitingForResposeAlert = mWaitingForResposeBuilder.show();
}
}
}
});
}
}, 300, TimeUnit.MILLISECONDS);
try{
new AsyncTask<Void, Void, HttpResponse>(){
@Override
protected HttpResponse doInBackground(Void... params){
try {
mResponseReceived = false;
HttpResponse response = mHttpClient.execute(mHttpPostAuth);
mResponseReceived = true;
return response;
}
catch (Exception e){
}
mResponseReceived = true;
return null;
}
protected void onPostExecute(HttpResponse response){
try{
if (response == null) return;
switch (response.getStatusLine().getStatusCode()){
case HttpStatus.SC_OK:{
//Reading the response
break;
}
default:{
break;
}
}
}
catch(Exception e){
}
}
}.execute().get();
if(mWaitingForResposeAlert != null) mWaitingForResposeAlert.dismiss();
return !(sid==null);
}
}
有什么方法可以根据在AsyncTask.execute()
同一代码块中的运行方式显示 AlertDialog 吗?