原理是通过,contentprovider获取系统短信数据库中的字段信息而达到获取内容目的
示例图片
具体代码如下:
import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.ScrollView; import android.widget.TextView; import java.sql.Date; import java.text.SimpleDateFormat; public class SmsRead2 extends AppCompatActivity{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView textView = new TextView(this); textView.setText(getSms()); ScrollView scrollView = new ScrollView(this); scrollView.addView(textView); setContentView(scrollView); } public String getSms(){ StringBuilder stringBuilder = new StringBuilder(); try{ //全部短信的路径 Uri uri = Uri.parse("content://sms/"); String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" }; //获取手机内部短信 Cursor cur = getContentResolver().query(uri, projection, null, null, "date desc"); if (cur.moveToFirst()) { int index_Address = cur.getColumnIndex("address"); //手机号码 int index_Body = cur.getColumnIndex("body"); //短信内容 int index_Date = cur.getColumnIndex("date"); //发件日期 int index_Type = cur.getColumnIndex("type"); //短信状态 do { String strAddress = cur.getString(index_Address); //得到的手机号码 String strbody = cur.getString(index_Body); //得到的短信内容 long longDate = cur.getLong(index_Date); //得到的发件日期 int intType = cur.getInt(index_Type); //得到的短信状态 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = new Date(longDate); String strDate = dateFormat.format(date); String strType = ""; if (intType == 1) { strType = "接收"; } else if (intType == 2) { strType = "发送"; } else { strType = "草稿"; } stringBuilder.append("[ 发/收件人号码:"); stringBuilder.append(strAddress + "短信内容:"); stringBuilder.append(strbody + "发/收信时间:"); stringBuilder.append(strDate + "信息状态:"); stringBuilder.append(strType); stringBuilder.append(" ]\n\n"); } while (cur.moveToNext()); if (!cur.isClosed()) { cur.close(); cur = null; } } else { stringBuilder.append("no result!"); } stringBuilder.append("getSmsInPhone has executed!"); }catch (SQLiteException ex){ ex.printStackTrace(); } return stringBuilder.toString(); } }