转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47785491
今天做到一个小项目,查询手机中短信的信息,当然得去系统暴露出来的数据库中去查询了,后来发现有三种方式可以选择,下面一一写出来。
第一种方式,采用 getContentResolver().query()方法在主线程中查询数据。这种查询方式是不是异步查询的,直接在UI线程中查询数据,代码如下:
Cursor cursor1 = getContentResolver().query(Sms.CONVESATION_URI, CONVERSATION_PROJECTION,null, null," sms.date desc"); while (cursor1.moveToNext()) { Log.i("cursor1", String.valueOf(cursor1.getInt(0))); Log.i("cursor1", cursor1.getString(1)); Log.i("cursor1", cursor1.getString(2)); } cursor1.close();
第二种查询方式,这种查询同样是在UI线程中查询数据,不过这种方式得到的Cursor不用手动去关闭,是Activity自动会去关闭的,cursor由activity去管理,代码如下:
Cursor cursor2 = managedQuery(Sms.CONVESATION_URI, CONVERSATION_PROJECTION, null, null, "sms.date desc"); while (cursor2.moveToNext()) { Log.i("cursor2", String.valueOf(cursor2.getInt(0))); Log.i("cursor2", cursor2.getString(1)); Log.i("cursor2", cursor2.getString(2)); }
第三种查询方式,这种方式是利用Android提供的异步查询框架AsyncQueryHandler,/是一种异步查询方式,当单查询完毕后,会调用onQueryComplete(token, cookie, cursor)通知查询完毕,并且传回cursor。代码如下:
private void startQuery() { Uri uri = Sms.CONVESATION_URI; mQueryHandler.startQuery(0, null, uri, CONVERSATION_PROJECTION, null, null, "sms.date desc"); } // 写一个异步查询类 private final class QueryHandler extends AsyncQueryHandler { public QueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { super.onQueryComplete(token, cookie, cursor); // 更新mAdapter的Cursor mAdapter.changeCursor(cursor); } }