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

前端 未结 17 2234
鱼传尺愫
鱼传尺愫 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:15

    I felt the below approach is very easy.

    I have declared an interface for callback

    public interface AsyncResponse {
        void processFinish(Object output);
    }
    

    Then created asynchronous Task for responding all type of parallel requests

     public class MyAsyncTask extends AsyncTask {
    
        public AsyncResponse delegate = null;//Call back interface
    
        public MyAsyncTask(AsyncResponse asyncResponse) {
            delegate = asyncResponse;//Assigning call back interfacethrough constructor
        }
    
        @Override
        protected Object doInBackground(Object... params) {
    
          //My Background tasks are written here
    
          return {resutl Object}
    
        }
    
        @Override
        protected void onPostExecute(Object result) {
            delegate.processFinish(result);
        }
    
    }
    

    Then Called the asynchronous task when clicking a button in activity Class.

    public class MainActivity extends Activity{
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
        Button mbtnPress = (Button) findViewById(R.id.btnPress);
    
        mbtnPress.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {
    
                        @Override
                        public void processFinish(Object output) {
                            Log.d("Response From Asynchronous task:", (String) output);
    
                            mbtnPress.setText((String) output);
                       }
                    });
    
                    asyncTask.execute(new Object[] { "Your request to aynchronous task class is giving here.." });
    
    
                }
            });
    
        }
    
    
    
    }
    

    Thanks

提交回复
热议问题