-1

I am running a async task in android to ping t a particular URL but the problem is when the url is not valid or not reachable an exception occurs as sockettimeoutexception so on that exception i want to stop the running task. iagve tried using Cancel() method but that causes App crash.

I am using the following code.

private class UrlDataProvider3 extends AsyncTask<String, Void, String>
{

    String ret="";
    int checkStatus;
    Boolean exception=false;
    @Override
    protected String doInBackground(String... url) 
    {

        HttpURLConnection con = null;

        try 
          { 

            Log.i("RAE", "urlData"+url[0]);
            HttpURLConnection.setFollowRedirects(true);
             con = (HttpURLConnection) new URL(url[0]).openConnection();
                 con.setRequestMethod("POST");
              con.setConnectTimeout(20000);




          }


        catch (IOException e)
          {


            if(e.toString().contains("java.net.SocketTimeoutException:"))
            {



                return null;

            }



          }



    return ret;
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.i("RAE"," Asyc finished");



}
Tarun Sharma
  • 601
  • 3
  • 13
  • 31

2 Answers2

0

you do something like this:

if((this.downloadNetTask != null) 
      && (this.downloadNetTask.getStatus() != AsyncTask.Status.FINISHED)){
        this.downloadNetTask.cancel(true);
}

Where downloadNetTask is instance of you async task. In your async task implement the following methods to do what you want when the task is cancelled.

protected void onCancelled(List<CompanyNseQuoteDataVO> result)

protected void onCancelled()
Nazgul
  • 1,892
  • 1
  • 11
  • 15
0

The thing is that AsyncTask.cancel() call only calls the onCancel function in your task. This is where you want to handle the cancel request.

Here is a small task I use to trigger an update method

private class SomeTask extends AsyncTask<Void, Void, Void> {

        private boolean running = true;

        @Override
        protected void onCancelled() {
            running = false;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            onUpdate();
        }

        @Override
        protected Void doInBackground(Void... params) {
             while(running) {
                 publishProgress();
             }
             return null;
        }
     }

Or you can check your task like below.

protected Object doInBackground(Object... x) {
    while (/* condition */) {
      // work...
      if (isCancelled()) 
          break;
      }
    return null;
 }
Jitesh Dalsaniya
  • 1,917
  • 3
  • 20
  • 36