How to start working on async task in one activity and inform another activity on completion of work in OnBackground

前端 未结 2 1792
星月不相逢
星月不相逢 2021-01-25 14:39

I would like to achieve the following behaviour, but I\'m not sure how:

   1. User start an activity
   2. Activity starts an AsyncTask
   3. After initiating th         


        
2条回答
  •  半阙折子戏
    2021-01-25 15:18

    You can create interface, pass it to the AsyncTask (in constructor), and then call interface method in onPostExecute..and make your second activity implements this interface..

    For example:

    Your interface:

    public interface OnTaskCompleted {
        void onTaskCompleted();
    }
    

    Your second Activity:

    public MyActivity implements OnTaskCompleted {
        //your Activity
    }
    

    And your AsyncTask:

    public YourTask extends AsyncTask { //change Object to required type
        private OnTaskCompleted listener;
    
        public YourTask(OnTaskCompleted listener) {
            this.listener=listener;
        }
    
        //required methods
    
        protected void onPostExecute(Object o) {
            //your stuff
            listener.onTaskCompleted();
        }
    }
    

提交回复
热议问题