Android - Asyntask doInBackground滞后和卡住UI

时间:2017-03-03 02:55:00

标签: android for-loop android-asynctask

我尝试在后台执行繁重的过程以避免UI延迟。当我在UI线程中执行此操作时,我没有响应,但是当我在asyntask中执行它时,没有任何响应,但UI仍然滞后并停留一段时间。这是我的代码。

private class GenerateTask extends AsyncTask<String, Integer, Void> {
        @Override
        protected final Void doInBackground(String... lists) {
            for (int j = 0; j < 9000; j++) {
                final Keyword newKeyword = new Keyword();
                newKeyword.setId(j);
                newKeyword.setQuestion_answer_id(j);
                newKeyword.setKeyword("Keyword ke " + j + " " + UtilHelper.getLocation(j % 9));
                newKeyword.setUpdated_at(UtilHelper.getDateTime());
                //i think this is the one who causes the lag, but i still need this run on ui thread
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UtilDB db = new UtilDB(getActivity().getApplicationContext());
                        db.replaceKeyword(newKeyword);
                    }
                });
            }
            progressDialog.dismiss();
            return null;
        }
    }

2 个答案:

答案 0 :(得分:2)

你做错了就是滥用AsyncTask。您可以阅读链接的文档,以便学习使用它(以及为什么和何时使用)。

卸下:

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        UtilDB db = new UtilDB(getActivity().getApplicationContext());
        db.replaceKeyword(newKeyword);
    }
});

并替换为AsyncTask中的另一种方法:

public void onPostExecute(String newKeyword) {
    super.onPostExecute(newKeyword);
    UtilDB db = new UtilDB(getActivity().getApplicationContext());
    db.replaceKeyword(newKeyword);
}

这需要更改为:

AsyncTask<String, Integer, String>

答案 1 :(得分:-1)

很抱歉,如果可以的话,我会评论(声望较低)...如果我说得对,你想在Loop中写入数据库,稍后更新用户界面?

  

是的,我实际上我需要稍后更新一些UI,这就是为什么我需要在ui线程上运行

是否有可能将两者分开?首先在HandlerThread中写入DataBase,然后通过UiThread通知你的UI更新?

目前,您正在UiThread队列中放置9000个元素,等待处理。这很多工作;)

相关问题