1

I have some asynctasks in my application that do network functions (download/upload files,http requests) in the background.While these actions are in progress I use ProgressDialog in order to display messages about the progress of the task. However some tasks may require more time to complete (for example downloading a file on a slow network) and this is something unwanted in the application.

How can I set a parameter to control the duration of each asynctask? I want the asynctask to complete at some point regardless of the completion of the job in the task. I have to make the asynctask call the onPostExecute method.

I read about this http://developer.android.com/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29

This was not very helpful because the UI would freeze and there was no actual control of the duration of the asynctask

This is a part of my code

public void downloadFiles(String address) {
        String mainUrl =address;

        //// I overrride the onPostExecute to get
        /// results and call another asynctask
        new Downloader(this){ //<--asynctask
            @Override
            protected void onPostExecute(String result){
                super.onPostExecute(result);
                TestResults=result;

            //another method called that creates another asynctask
             uploadFiles(mainUrl);

            }
        }.execute(mainUrl);


    }

I also tried to use a Handler like this But it didn't work either.

Is there a way to make the asynctask return results (which means to make asynctask call onPostExecute method) after a period of time ?

Using a while loop in the doInBackground method of asnctask is not the solution. I guess I need a timer from the mainUI to make the asynctask return results.

PS I have my application using fragments, that is why I call new Downloader(this) to pass the gui from the fragment.

Just tried this:

public void downloadFiles(String address) {
        String mainUrl =address;


        final Downloader tempObject =new Downloader(this){
            @Override
            protected void onPostExecute(String result){
                super.onPostExecute(result);
                downloadResults=result;
                }
        };
        try {
            tempObject.execute(mainUrl).get(3000L, TimeUnit.MILLISECONDS);
        } 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();
        }

This would make the UI freeze for 3 seconds and then the task would be evoked.... Which is not what I want.

Also tried out this:

Handler handler = new Handler();
        handler.postDelayed(new Runnable()
        {
          @Override
          public void run() {
              if ( tempObject.getStatus() == Downloader.Status.RUNNING )
                  tempObject.cancel(true);
          }
        }, 5000 );

This would cause the message of onProgressUpdate of asynctask to stop, however the asynctask keeps running....

Any ideas ?

Community
  • 1
  • 1
malcolm the4
  • 347
  • 2
  • 5
  • 15
  • How are you downloading the file? I would put the timeouts in there, for example like this: http://stackoverflow.com/a/3002544/833647 – Ken Wolf Jul 04 '13 at 17:18
  • I do it like in the example you posted. The problem is that the connection will not drop when data is transfered. For example when you are on an EDGE netowkr you may get 5-6 KB/sec speed. The connection will not drop and the download may take several minutes. The connection is time-out when the server is not responding or not transmitting for several seconds. I want to be able to determine the duration of the asynctask and make it, for example,last less than 30 seconds – malcolm the4 Jul 04 '13 at 17:58
  • The problem is that I want to make the asynctask have a certain duration. After this time interval the onPostExecute method of the asnctask should be called – malcolm the4 Jul 04 '13 at 18:04
  • Hmm, I understand. Then I guess the Handler + .get() approach you posted seems the best to me. But it kind of defeats the purpose of AsyncTask IMO. Sorry I have no better suggestion! – Ken Wolf Jul 04 '13 at 18:39
  • @KenWolf I tried the methodology you say but the handler causes only the message update to stop. The asynctask is still executed in the backgroud and the message update (which is a percentage bar of the files downloaded) freezes. I am struggling for days. Any ideas? Thank you in advance! – malcolm the4 Jul 04 '13 at 19:08

1 Answers1

0

The methodology of the Handler function needs something additional to work. The solution to the problem lies here

AsyncTask may be canceled, however the doInbackground method is still running. Actually the task is set to value "cancel", but the doInbackgroung will still be running until it finishes. To solve this we must periodically check within a loop in doInbackground to see whether the task was set to cancel. Although this is not exactly what I wanted to do, this seems to be the only solution.

In doInBackground we have to check for the status of the task to see whether it was cancelled or not. So actually ,someone could just have the timer inside the doInbackground and make life easier without using the handler class.

I find it disappointing that one can not just terminate the execution of a synctask at will..... If anyone has a better idea, please let me know.

malcolm the4
  • 347
  • 2
  • 5
  • 15