如何创建类似AsyncTask的类

时间:2019-07-03 08:11:05

标签: java android android-asynctask

我正在尝试创建一个与AsyncTask类相同的类。

我已经写了这堂课

public abstract class BackgroundProcess<Data, Result> {

    private Activity activity;

    public BackgroundProcess(Activity activity) {
        this.activity = activity;
    }

    @WorkerThread
    abstract Result runProcess(Data data);

    @MainThread
    abstract void onProcessFinished(Result result);

    public void execute(final Data data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("THREAD", "run");
                final Result result = runProcess(data);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onProcessFinished(result);
                    }
                });
            }
        }).start();
    }
}

它可以工作,但问题是我必须为其提供一个Activity才能在主线程上运行onProcessFinished()(AsyncTask不需要活动即可工作)

这是我用来测试的子类的示例。

public class ThreadTest extends BackgroundProcess<Void, List<User>> {

    private Context context;

    public ThreadTest(Context context) {
        super((Activity) context);
        this.context = context;
    }

    @Override
    List<User> runProcess(Void aVoid) {
        Log.d("THREAD", "runProcess");
        return UsersDatabase.Companion.getInstance(context).userDao().getAllUsers();
    }

    @Override
    void onProcessFinished(List<User> users) {
        Log.d("THREAD", users.size() + " finish");
        Toast.makeText(context, users.size() + "", Toast.LENGTH_SHORT).show();
    }

}

onCreate中的实际用法:

ThreadTest threadTest = new ThreadTest(this);
threadTest.execute(null);

一切正常,但问题是AsyncTask类如何在没有活动的情况下在主线程上执行其onPostExecute()

0 个答案:

没有答案