CursorLoader:java
CursorLoader实现异步加载数据,为了不同步查询数据库时阻塞UI线程的问题。CursorLoader是Loader的子类,Loader能够移步加载数据;loader本身会监视数据源的变化而且会主动上报;当发生配置上的变化,从新生成的loader会自动链接到变化前的cursor,这样就避免再查一次数据库。android
一、在配置清单里添加查询信息的权限web
<uses-permission android:name="android.permission.READ_SMS"/>数据库
二、res/layout下2个布局文件activity_main.xml和item_activity.xml布局异步
activity_main.xml布局ide
代码布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >this
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>spa
</RelativeLayout>
线程
======================
item_activity.xml布局
代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/text_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
=======================================
三、MainActivity.java类
代码
//须要实现接口LoaderCallbacks而后重写接口里的方法
public class MainActivity extends FragmentActivity implements
LoaderCallbacks<Cursor> {
private ListView listView;
private SimpleCursorAdapter adapter;
private String uri_sms = "content://sms";//访问信息数据库的uri
private LoaderManager loaderManager;
private Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.listView = (ListView) this.findViewById(R.id.listview);
// 最后一个参数 标志 能够用CursorAdapter.出来
//若是是FLAG_REGISTER_CONTENT_OBSERVER标志 则适配器会在Cursor上注册一个内容观察者
//该观察者会时时刻刻观察内容的变更 若是通知到达时就调用onContentChanged()方法
adapter = new SimpleCursorAdapter(this, R.layout.item_activity, cursor,
new String[] {"body","address"},
new int[] { R.id.text_phone, R.id.text_content },
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
loaderManager = getSupportLoaderManager();//获取加载管理器
// initLoader -- 若是当前没有加载器就调用onCreateLoader建立一个 有就根据第一个参数标志重复利用
// 第一个参数 -- 加载器的标志 随便写
// 第二个参数 -- Bundle -- 用来传递数据 没有能够写null
// 第三个参数 -- LoaderCallbacks 对象
loaderManager.initLoader(1, null, this);
}
// ----------继承LoaderCallbacks接口要重写的方法---------------
@Override// 建立一个Loade
public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
return new CursorLoader(this, Uri.parse(uri_sms), null, null, null, "date desc");
}
@Override// Loader建立完成
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
adapter.changeCursor(cursor);
}
@Override// 当一个加载器给重置时 调用 public void onLoaderReset(Loader<Cursor> arg0) { adapter.changeCursor(null); }}