游标在非UI线程中获取性能

时间:2012-01-04 13:34:46

标签: android

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倍,在视觉上非常明显。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

在真实设备(手机)上使用它进行测试,因为仿真器很慢

答案 1 :(得分:0)

答案是默认情况下更改后台进程优先级(Process.setThreadPriority),因为AsyncTask以后台优先级运行。