Android: Callback AsyncTask to Fragment(Not Activity)

前端 未结 1 545
攒了一身酷
攒了一身酷 2020-12-04 23:02

I am trying to implement callback between AsyncTask and Fragment but cannot find correct info how to do it. The issue is that all callback implementations are between activ

相关标签:
1条回答
  • 2020-12-04 23:53

    Without taking your code in consideration I will post the most essential to make a functional callback.


    TestFragment:

    public class TestFragment extends Fragment {
    
        /* Skipping most code and I will only show you the most essential. */    
        private void methodThatStartsTheAsyncTask() {
            TestAsyncTask testAsyncTask = new TestAsyncTask(new FragmentCallback() {
    
                @Override
                public void onTaskDone() {
                    methodThatDoesSomethingWhenTaskIsDone();
                }
            });
    
            testAsyncTask.execute();
        }
    
        private void methodThatDoesSomethingWhenTaskIsDone() {
            /* Magic! */
        }
    
        public interface FragmentCallback {
            public void onTaskDone();
        }
    }
    

    TestAsyncTask:

    public class TestAsyncTask extends AsyncTask<Void, Void, Void> {
        private FragmentCallback mFragmentCallback;
    
        public TestAsyncTask(FragmentCallback fragmentCallback) {
            mFragmentCallback = fragmentCallback;
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            /* Do your thing. */
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
            mFragmentCallback.onTaskDone();
        }
    }
    
    0 讨论(0)
提交回复
热议问题