Android利用ContentProvider读取短信内容

【Android利用ContentProvider读取短信内容】本文实例为大家分享了Android利用ContentProvider读取短信内容的具体代码,供大家参考,具体内容如下
首先,我们来看下运行效果
运行效果如下:
Android利用ContentProvider读取短信内容
文章图片

展示短信内容的效果如下:
Android利用ContentProvider读取短信内容
文章图片

布局文件(activity_sms.xml)


一个简单的读取短信内容的例子(SMSActivity)
package com.example.administrator.myapplication; 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.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class SMSActivity extends AppCompatActivity {private ListView lv_sms_list; private List data; private SimpleAdapter simpleAdapter; private ContentResolver contentResolver; @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_sms); //获取访问者contentResolver = getContentResolver(); lv_sms_list = (ListView) findViewById(R.id.lv_sms_list); data = https://www.it610.com/article/new ArrayList(); //适配器simpleAdapter = new SimpleAdapter(this,data,android.R.layout.simple_list_item_2,new String[]{"names","note"},new int[]{android.R.id.text1,android.R.id.text2}); lv_sms_list.setAdapter(simpleAdapter); }public void getContactsSms(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()){Mapmap=new HashMap(); _id=cursor.getInt(0); address=cursor.getString(1); body=cursor.getString(2); date=cursor.getString(3); type=cursor.getInt(4); map.put("names",body); data.add(map); Log.i("test","_id="+_id+" address="+address+" body="+body+" date="+date+" type="+type); //通知适配器发生改变simpleAdapter.notifyDataSetChanged(); }}}}

最后需要在清单文件上配置读取短信的权限即可(AndroidManifest.xml)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读