Android - Setting a Timeout for an Asynctask

Android - Setting a Timeout for an AsyncTask?

Yes, there is AsyncTask.get()

myDownloader.get(30000, TimeUnit.MILLISECONDS);

Note that by calling this in main thread (AKA. UI thread) will block execution, You probably need call it in a separate thread.

How to set time out for AsyncTask execution?

I think you can use AsyncTask.get()

GetLongLat n = new GetLongLat();
n.get(30000, TimeUnit.MILLISECONDS);

you will have to use the n.get in a separate Thread..

Edited: one more different method but not efficient.,

GetLongLat n = new GetLongLat();
n.execute();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
@Override
public void run() {
if ( n.getStatus() == AsyncTask.Status.RUNNING )
n.cancel(true);
}
}, 30000 );

Set timeout function with AsyncTask [Android]

get() method will block the UI thread and I guess you don't want this.

You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
AsyncTask.cancel();
}
}, 1);

Be aware there are many gotchas with AsyncTask, check my article.

AsyncTask with timeout

I have put one dummy code change your code by referring this.

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

if (commonUtils.isNetworkAvailable(mContext)) {
NewHistoryAsync task = new NewHistoryAsync(getContext(), listDataHeader, listDataChild);
task.execute(CommonUtils._History + "ID=" + userUhid);
} else {
Toast.makeText(mContext, "No Network Available!!",
Toast.LENGTH_LONG).show();
}

private class NewHistoryAsync extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
Context mContext;
List listDataHeader;
HashMap listDataChild;

public NewHistoryAsync(Context context, List listDataHeaderList, HashMap listDataChildMap) {
mContext = context;
listDataHeader = listDataHeaderList;
listDataChild = listDataChildMap;
this.listDataHeader = new ArrayList<String>();
this.listDataChild = new HashMap<String, List<String>>();

}

@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog = ProgressDialog.show(mContext, Html.fromHtml(
"<b>Heading<b>"), Html.fromHtml("<medium>Downloading Details..</medium>"), true);

// progressDialog.setTitle("Downloading Details");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}

@Override
protected String doInBackground(String... params) {
String resResult = NewHistoryService(params[0]);
JSONObject jsonResponse;

try {
//JSONObject jsonObject = new JSONObject(resResult);
JSONArray jsonArray = new JSONArray(resResult);

// Log.i("doinb---> ", resResult);
/* ArrayList<ClaimsHistoryNewSearchModel> listDataHeader=new ArrayList<ClaimsHistoryNewSearchModel>();*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
List<String> historyResult = new ArrayList<String>();
historyResult.add((jsonObject.get("AdmissionDate").toString()));
historyResult.add((jsonObject.get("DischargeDate").toString()));
//AdmissionDate= exact name to ur json response from server

listDataHeader.add(KeyString);
listDataChild.put(KeyString, historyResult);

}

} catch (Exception e) {
e.printStackTrace();

}
return resResult;
}

@Override
protected void onProgressUpdate(String... values) {

Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
}

@Override
protected void onPostExecute(String result) {
if (progressDialog != null && progressDialog.isShowing() == true) {
progressDialog.dismiss();
if (result.equals("[]")) {
Toast.makeText(mContext, "No Details found!!",
Toast.LENGTH_LONG).show();
} else
// Log.i("Result:", result);
// Log.i("listDataHeader:", listDataHeader.toString());
// Log.i("listDataChild:", listDataChild.toString());
listAdapter = new ClaimHistoryNewAdapter(getActivity(), listDataHeader, listDataChild);
if (listDataHeader != null && listDataHeader.size() > 0 && listDataChild != null && listDataHeader.size() > 0) {
expListView.setAdapter(listAdapter);
} else {
// setting list adapter
tClaimHistory.setVisibility(View.VISIBLE);
}
}
}

public String NewHistoryService(String serviceUrl) {

StringBuffer response = new StringBuffer();
URL url = null;

HttpURLConnection conn = null;
try {

url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}

// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;

while ((line = rd.readLine()) != null) {
response.append(line);

}
rd.close();

} catch (Exception e) {
e.printStackTrace();
//ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
//response.append("Error");
}
Log.v("Response:", response.toString());
return response.toString();

}
}
}

Android: AsyncTask timeout

because you are trying to start AsyncTask again inside doInBackground when it's still running . change your code as to get it work :

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
downloadFAQ.execute().get(2000, TimeUnit.MILLISECONDS);

SplashActivity.thisrunOnUiThread(new Runnable() {
public void run() {
// start Activity here
Intent i = new Intent(SplashActivity.this,
TabsActivity.class);
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}

and you will need to remove downloadFAQ.get(2000, TimeUnit.MILLISECONDS); from doInBackground method change your AsyncTask as

private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}

protected void onPostExecute(Void result) {

}

}

How to Handle connection timeout in async task

You can use getErrorStream() ,

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inp;

// if some error in connection
inp = connection.getErrorStream();

check this answer for more details..

according to the doc it returns

an error stream if any, null if there have been no errors, the
connection is not connected or the
server sent no useful data

.

What is the simple way to limit the execution time of an AsyncTask?

You can set CountDownTimer to stop the AsyncTask if it runs more than 30 seconds.

For Example:

new CountDownTimer(30000, 28000) {

public void onTick(long millisUntilFinished) {

}

public void onFinish() {
asyncTask.cancel(true); //
}
}.start();

Another way is Handler.

  new Handler().postDelayed(new Runnable(){
@Override
public void run() {
asyncTask.cancel(true);
}
},30000)

Another simple way is to set Connection Timeout for your HTTP call to 30 seconds. It will automatically ends the async task after 30 seconds.

How to set a fixed time if AsyncTask is not finished

You can use handler to run after a definite amount time and maintain a boolean flag which you can update in postExecute function of async task.

In your activity/fragment class:

new Handler().postDelayed(new Runnable(){
public void run(){
//Check whether the flag has been updated or not
},1000)


Related Topics



Leave a reply



Submit