Repeat AsyncTask

前端 未结 3 600
情话喂你
情话喂你 2021-01-02 22:10

I have a doubt about the possibility of repeating an AsyncTask in an application for Android. I would like to repeat some operations, the download of a file from a server fo

3条回答
  •  礼貌的吻别
    2021-01-02 22:37

    I did it that way. It can try and try until (tries == MAX_RETRY) or the result is not null. A slightly modified code from accepted answer, better for me.

    private class RssReaderTask extends AsyncTask> {
    
        // max number of tries when something is wrong
        private static final int MAX_RETRY = 3;
    
        @Override
        protected ArrayList doInBackground(String... params) {
    
            ArrayList result = null;
            int tries = 0;
    
            while(tries++ < MAX_RETRY && result == null) {
                try {
                    Log.i("RssReaderTask", "********** doInBackground: Processing... Trial: " + tries);
                    URL url = new URL(params[0]);
                    RssFeed feed = RssReader.read(url);
                    result = feed.getRssItems();
                } catch (Exception ex) {
                    Log.i("RssReaderTask", "********** doInBackground: Feed error!");
                }
            }
    
            return result;
        }
    
        @Override
        protected void onPostExecute(ArrayList result) {
            // deal with result
        }
    
    }
    

提交回复
热议问题