我试图在后台执行繁重的过程以避免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;
}
}
尝试使用后台线程,而在数据库中更新。使用处理程序线程 –
你假设它正在运行一些针对数据库的东西...但是如果他觉得需要在UI线程上运行它(指示触摸视图等),那么有可能假设是错误的 –
是的,其实我需要稍后更新一些用户界面,这就是为什么我需要在UI线程上运行 – huzain07