How to run the same asynctask more than once?

前端 未结 12 1985
难免孤独
难免孤独 2020-12-01 03:32

I have my asyncTask run when the activity first starts, then if network connectivity is not available then i have a refresh button that tries to run the asyncTask to try aga

相关标签:
12条回答
  • 2020-12-01 03:58

    @coder_For_Life22 I think am late for the answer ,anyway you can do like

        @Override
        protected void onPostExecute(Void a) {
    
            myAsyncTask=new MyAsyncTask();
        }
    

    in order to start a new AsyncTask after execution :)

    0 讨论(0)
  • 2020-12-01 03:59

    You could cancel your asyncTask when you press the button and then execute it again.

    Inside OnClic method:

    asyncTask.cancel();
    AsyncTask asyncTask = new AsyncTask();
    asyncTask.execute();
    
    0 讨论(0)
  • 2020-12-01 04:01

    in your MainActivity you can put so this:

    LeoAsyncTask leoAsyncTaskGeneric;
    
    
    public void onClick_AsyncTask(View view) {
    
        LeoAsyncTask leoAsyncTaskInner = new LeoAsyncTask();
        leoAsyncTaskInner.execute();
    
        leoAsyncTaskGeneric=leoAsyncTaskInner; 
    

    }

    /**if you create a space in memory of your AsyncTask class as a generic, then you can create an instance of that same class within the onClick method, and there the equals, so every time you press onClick you will be using a new instance of the Class AsyncTask, it will not give you problems */

    0 讨论(0)
  • 2020-12-01 04:02

    Just create another instance and execute it.

    0 讨论(0)
  • 2020-12-01 04:14

    Just make a new call like new asyncTask().execute(); You must create a new object to restart that task.

    0 讨论(0)
  • 2020-12-01 04:15

    You can do it like this :

    private MyAsyncTask createAsyncTask(){
        if (myAsyncTask == null){
            return myAsyncTask = new MyAsyncTask();
        }
            myAsyncTask.cancel(true);
            return myAsyncTask = new MyAsyncTask();
     }
    

    and then you can use it :

    createAsyncTask().execute();
    

    this make a new instance of your background task everytime.

    0 讨论(0)
提交回复
热议问题