使用回调自定义AsyncTask

时间:2016-03-26 14:42:51

标签: android android-asynctask callback android-configchanges

我需要编写AsyncTask,它将在屏幕旋转后获得对新对象实例的引用。我写了Callback接口并在JukeTask中声明了对该字段的弱引用。
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);
    }
}

使用示例:

    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());
    }
}


我是否应该WeakReference JukeTask Callback使用JukeTask来阻止垃圾收集器?
如何保存对JukeTask的引用?因为在屏幕旋转后它会重新执行{{1}}。

0 个答案:

没有答案