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

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

    Probably going overboard a bit but i provided call backs for both the execution code and the results. obviously for thread safety you want to be careful what you access in your execution callback.

    The AsyncTask implementation:

    public class AsyncDbCall extends AsyncTask
    {
        public interface ExecuteCallback
        {
            public R execute(E executeInput);
        }
        public interface PostExecuteCallback
        {
            public void finish(R result);
        }
    
        private PostExecuteCallback _resultCallback = null;
        private ExecuteCallback _executeCallback = null;
    
    
        AsyncDbCall(ExecuteCallback executeCallback, PostExecuteCallback postExecuteCallback)
        {
            _resultCallback = postExecuteCallback;
            _executeCallback = executeCallback;
        }
    
        AsyncDbCall(ExecuteCallback executeCallback)
        {
            _executeCallback = executeCallback;
        }
    
        @Override
        protected ResultType doInBackground(final ExecuteType... params)
        {
            return  _executeCallback.execute(params[0]);
        }
    
        @Override
        protected void onPostExecute(ResultType result)
        {
            if(_resultCallback != null)
                _resultCallback.finish(result);
        }
    }
    

    A callback:

     AsyncDbCall.ExecuteCallback updateDeviceCallback = new 
     AsyncDbCall.ExecuteCallback()
        {
            @Override
            public Device execute(Device device)
            {
                deviceDao.updateDevice(device);
                return device;
            }
        };
    

    And finally execution of the async task:

     new AsyncDbCall<>(addDeviceCallback, resultCallback).execute(device);
    

提交回复
热议问题