*异步获取短信记录
*/public class MainActivity extends Activity implements LoaderCallbacks{
private LoaderManager manager;
private ContentResolver resolver;
private Uri uri;
private ListView listView;
private SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
null,
new String[]{Sms.Draft.ADDRESS,Sms.Draft.BODY},
new int[]{android.R.id.text1,android.R.id.text2},
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
resolver = getContentResolver();
uri = Sms.CONTENT_URI;//Uri.parse("content://sms");
manager = getLoaderManager();
//如果是v4包,那么activity首先要是属于v4,获取方式不同
// manager = getSupportLoaderManager();
manager.initLoader(2, null, this);
}
@Override
public Loader onCreateLoader(int id, Bundle args) {
//Log.i("info", "======="+id +args);
//创建一个loader对象
AsyncTaskLoader loader = new AsyncTaskLoader(this) {
@Override
protected void onStartLoading() {
super.onStartLoading();
//如果是第一次加载loader,必须强制加载数据
forceLoad();
}
//在子线程中调用,在这个方法中就去执行查询数据库的操作
@Override
public Cursor loadInBackground() {
//发起查询动作
Cursor cursor = resolver.query(uri, null, null, null, null);
//必须要返回游标,返回到创建loader里面
return cursor;
}
};
//这个loader中就有携带cursor游标
return loader;
}
@Override
public void onLoadFinished(Loader loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader loader) {
adapter.swapCursor(null);
}
}