Android - Asyntask doInBackground滞后和卡住的UI
问题描述:
我试图在后台执行繁重的过程以避免UI滞后。当我在UI线程中执行它时,我没有响应,但是当我在asyntask中执行时,没有任何响应,但UI仍然滞后并停留了一段时间。这是我的代码。Android - Asyntask doInBackground滞后和卡住的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;
}
}
答
你在做什么错是滥用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>
答
对不起,我想如果我可以(发表评论我要少声望)...如果我有你的权利,你想写入一个循环到一个数据库和后更新用户界面?
是啊,我其实我需要在以后更新一些UI,这就是为什么我需要在UI线程运行
是否有可能分裂两者兼而有之?首先在HandlerThread的DataBase中写入,然后通知你的UI通过UiThread更新?
目前您正在将9000个元素放入UiThread队列中,等待处理。这是很多工作;)
尝试使用后台线程,而在数据库中更新。使用处理程序线程 –
你假设它正在运行一些针对数据库的东西...但是如果他觉得需要在UI线程上运行它(指示触摸视图等),那么有可能假设是错误的 –
是的,其实我需要稍后更新一些用户界面,这就是为什么我需要在UI线程上运行 – huzain07