从AsyncTaskLoader
中的游标中获取数据时出现性能问题。在android API级别10中进行测试。例如,2个带有游标的类 - TestFragmentUI
在UI线程中获取数据,TestFragment
在无UI thread
中获取数据。
public class TestFragment extends Fragment implements LoaderManager.LoaderCallbacks<Object> {
...
@Override
public void onActivityCreated(Bundle savedInstanceState) {
...
getLoaderManager().initLoader(0, null, this);
...
}
public android.support.v4.content.Loader<Object> onCreateLoader(
int id, Bundle args) {
return new Loader(getActivity());
}
class Loader extends AsyncTaskLoader<Object> {
public Loader(Context context) {
super(context);
}
public Object loadInBackground() {
...
DataBaseHelper helper = new DataBaseHelper(getContext());
SQLiteDatabase database = helper.getReadableDatabase();
long start = System.currentTimeMillis();
Cursor data = database.rawQuery(String.format(SQL_LOAD, parametr), null);
while (data.moveToNext()) {
String number = data.getString(data.getColumnIndex("number"));
}
data.close();
Log.i(TAG, "load: " + (System.currentTimeMillis() - start));
...
}
}
...
}
和
public class TestFragmentUI extends Fragment {
...
@Override
public void onActivityCreated(Bundle savedInstanceState) {
...
DataBaseHelper helper = new DataBaseHelper(getActivity());
SQLiteDatabase database = helper.getReadableDatabase();
...
long start = System.currentTimeMillis();
Cursor data = database.rawQuery(String.format(SQL_LOAD, parametr), null);
while (data.moveToNext()) {
String number = data.getString(data.getColumnIndex("number"));
}
data.close();
Log.i(TAG, "load: " + (System.currentTimeMillis() - start));
...
}
...
}
在模拟器TestFragment
中,类输出时间比输出TestFragmentUI
慢10倍,在视觉上非常明显。
有什么想法吗?
答案 0 :(得分:0)
在真实设备(手机)上使用它进行测试,因为仿真器很慢
答案 1 :(得分:0)
答案是默认情况下更改后台进程优先级(Process.setThreadPriority),因为AsyncTask以后台优先级运行。