0

I need to write AsyncTask that will get reference on new object instances after the screen rotation. I wrote Callback interface and in JukeTask declared weak reference to this field.
JukeTask:

public abstract class JukeTask<Params, Progress, Result>
        extends AsyncTask<Params, Progress, Result> {
    private WeakReference<Callback<Progress, Result>> mWRCallback;

    public void setCallback(Callback<Progress, Result> callback) {
        mWRCallback = new WeakReference<>(callback);
    }

    @Override
    protected void onPreExecute() {
        Callback<Progress, Result> callback = mWRCallback.get();

        if(callback != null) {
            callback.onPreExecute();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onProgressUpdate(Progress... values) {
        Callback<Progress, Result> callback = mWRCallback.get();

        if(callback != null) {
            callback.onProgressUpdate(values);
        }
    }

    @Override
    protected void onPostExecute(Result result) {
        Callback<Progress, Result> callback = mWRCallback.get();

        if(callback != null) {
            callback.onPostExecute(result);
        }
    }

    public interface Callback<P, R> {
        void onPreExecute();
        @SuppressWarnings("unchecked")
        void onProgressUpdate(P... values);
        void onPostExecute(R result);
    }
}

Example of using:

    public class TestActivity extends AppCompatActivity implements JukeTask.Callback<Integer, Integer> {
    private static final String TAG = TestActivity.class.getSimpleName();
    private TextView mTextView;
    JukeTask<Void, Integer, Integer> mTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTextView = new TextView(this);
        setContentView(mTextView);
        mTextView.setText("Started");
        //...

        if(mTask == null) {
            mTextView.setText("Task is null!");
            mTask = new JukeTask<Void, Integer, Integer>() {
                @Override
                protected Integer doInBackground(Void[] params) {
                    int i = 0;
                    for (; i < 100000; ++i) {
                        Log.d(TAG, "Tick " + i);
                    }
                    //Do smth
                    return i;
                }
            };
            mTask.setCallback(this);
            mTask.execute();
        }
    }

    @Override
    public void onPreExecute() {

    }

    @Override
    public void onProgressUpdate(Integer... values) {

    }

    @Override
    public void onPostExecute(Integer result) {
        mTextView.setText(result.toString());
    }
}


Should I use WeakReference in JukeTask for Callback to not block a garbage collector?
How to save a reference to JukeTask? Because after the screen rotation it re-executes JukeTask.

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123

0 Answers0