一、在配置清单添加须要的权限java
<uses-permission android:name="android.permission.READ_SMS"/>android
二、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>
.net
================server
item_activity.xml布局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类
代码
/**
*
* @author Administrator
* 自定义CursorLoader要实现LoaderCallbacks类观察者的原理
*
*/
public class MainActivity extends Activity {
private String uri_sms = "content://sms";
private ListView listView;
private SimpleCursorAdapter adapter;
private Cursor cursor;
private boolean issameObject;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.listView = (ListView) this.findViewById(R.id.listview);
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);
new MyAsynTask().execute();
}
class MyAsynTask extends AsyncTask<Void, Void, Cursor> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Cursor doInBackground(Void... params) {
ContentResolver resolver = getContentResolver();
// 查询数据库
cursor = resolver.query(Uri.parse(uri_sms), new String[] { "_id",
"body", "address" }, null, null, "date desc");
return cursor;
}
@Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
// 注册一个观察者
result.registerContentObserver(new Observer(null));
//交换数据
adapter.swapCursor(result);
issameObject = false;
}
// 观察者类 要继承ContentObserver类
class Observer extends ContentObserver {
public Observer(Handler handler) {
super(handler);
}
@Override//注册对象发生改变 都要触发该方法
public void onChange(boolean selfChange) {
if (issameObject) {//若是注册的对象 是同一个 什么都不作
return;
}
new MyAsynTask().execute();//若是注册对象改变了 就从新启动MyAsynTask类
issameObject = true;//改变标志
}
}
}}