Http リクエストを実行し (HttpPost、HttpClient、および AsyncTask を使用)、HttpClient.execute()
(で実行されるAsyncTask.doInBackground()
) 時間がかかりすぎる場合に AlertDialog を表示する関数を作成しています。
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 を表示する方法はありますか?