一、在配置清單添加須要的權限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;//改變標誌
}
}
}}