//效果图:
package com.example.android25_readnote;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 利用内容访问者读取短信内容
*
*/
public class MainActivity extends AppCompatActivity {
private ContentResolver cr;
private ListView main_lv;
private Cursor cursor;
private List<Map<String, Object>> data;
private SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取内容访问者
cr = getContentResolver();
main_lv = (ListView) findViewById(R.id.main_lv);
data = new ArrayList<Map<String, Object>>();
simpleAdapter = new SimpleAdapter(this,data, R.layout.item_listview,new String[]{"address","body"},new int[]{R.id.item_tv,R.id.item_tv3});
//给listview设置适配器
main_lv.setAdapter(simpleAdapter);
}
public void readnote(View view){
cursor = cr.query(Uri.parse("content://sms"),null,null,null,null);
while(cursor.moveToNext()){
Map<String,Object> map=new HashMap<>();
//电话号码
String address= cursor.getString(cursor.getColumnIndex("address"));
//短信内容
String body= cursor.getString(cursor.getColumnIndex("body"));
map.put("address",address);
map.put("body",body);
//添加到集合
data.add(map);
Log.i("test","电话号码:"+address+"内容"+body);
}
//通知适配器发生改变
simpleAdapter.notifyDataSetChanged();
}
}
//需在清单文件中获取短信的权限