效果图如下:是用ListView显示的短信内容
一下是实现代码:
package com.example.android_contentresolver;
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 DuanxinActivity extends AppCompatActivity {
private ListView lv_duanxin;
private List list;
private SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duanxin);
lv_duanxin = (ListView) findViewById(R.id.lv_duanxin);
list = new ArrayList();
simpleAdapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, new String[]{"date", "body"}, new int[]{android.R.id.text1, android.R.id.text2});
lv_duanxin.setAdapter(simpleAdapter);
}
public void getDuanxin(View view){
//读取所有短信
Uri uri=Uri.parse("content://sms/");
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(uri, new String[]{"_id", "address", "body", "date", "type"}, null, null, null);
if(cursor!=null&&cursor.getCount()>0){
int _id;
String address;
String body;
String date;
int type;
while (cursor.moveToNext()){
Map<String,Object> map = new HashMap<>();
_id=cursor.getInt(0);//id
address=cursor.getString(1);//电话号码
body=cursor.getString(2);//短信内容
date=cursor.getString(3);
type=cursor.getInt(4);
Log.i("test","_id="+_id+" address="+address+" body="+body+" date="+date+" type="+type);
map.put("address",address);
map.put("body",body);
list.add(body);
}
}
}
}
清单文件中加的权限:
<!--获取短信权限-->
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_SMS"></uses-permission>