How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

前端 未结 17 2148
鱼传尺愫
鱼传尺愫 2020-11-21 04:50

I have this two classes. My main Activity and the one that extends the AsyncTask, Now in my main Activity I need to get the result from the OnPostExecute(

17条回答
  •  感情败类
    2020-11-21 05:20

    You can write your own listener. It's same as HelmiB's answer but looks more natural:

    Create listener interface:

    public interface myAsyncTaskCompletedListener {
        void onMyAsynTaskCompleted(int responseCode, String result);
    }
    

    Then write your asynchronous task:

    public class myAsyncTask extends AsyncTask {
    
        private myAsyncTaskCompletedListener listener;
        private int responseCode = 0;
    
        public myAsyncTask() {
        }
    
        public myAsyncTask(myAsyncTaskCompletedListener listener, int responseCode) {
            this.listener = listener;
            this.responseCode = responseCode;
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
    
        @Override
        protected String doInBackground(String... params) {
            String result;
            String param = (params.length == 0) ? null : params[0];
            if (param != null) {
                // Do some background jobs, like httprequest...
                return result;
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(String finalResult) {
            super.onPostExecute(finalResult);
            if (!isCancelled()) {
                if (listener != null) {
                    listener.onMyAsynTaskCompleted(responseCode, finalResult);
                }
            }
        }
    }
    

    Finally implement listener in activity:

    public class MainActivity extends AppCompatActivity implements myAsyncTaskCompletedListener {
    
        @Override
        public void onMyAsynTaskCompleted(int responseCode, String result) {
    
            switch (responseCode) {
                case TASK_CODE_ONE: 
                    // Do something for CODE_ONE
                    break;
                case TASK_CODE_TWO:
                    // Do something for CODE_TWO
                    break;
                default: 
                    // Show some error code
            }        
        }
    

    And this is how you can call asyncTask:

     protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // Some other codes...
            new myAsyncTask(this,TASK_CODE_ONE).execute("Data for background job");
            // And some another codes...
    }
    

提交回复
热议问题