Android SMS(一) —— 读取短信

分类:Android 9440人阅读 评论(9) 收藏 举报 sms android integer string date 数据库

Android SMS Read

[java] view plain copy print ?
  1. packagecom.homer.sms;
  2. importjava.sql.Date;
  3. importjava.text.SimpleDateFormat;
  4. importandroid.app.Activity;
  5. importandroid.database.Cursor;
  6. importandroid.database.sqlite.SQLiteException;
  7. importandroid.net.Uri;
  8. importandroid.os.Bundle;
  9. importandroid.util.Log;
  10. importandroid.widget.ScrollView;
  11. importandroid.widget.TableLayout;
  12. importandroid.widget.TextView;
  13. /**
  14. *读取手机短信
  15. *
  16. *@authorsunboy_2050
  17. *@sincehttp://blog.csdn.net/sunboy_2050
  18. *@date2012.03.06
  19. */
  20. publicclasssmsReadextendsActivity{
  21. @Override
  22. publicvoidonCreate(BundlesavedInstanceState){
  23. super.onCreate(savedInstanceState);
  24. TextViewtv=newTextView(this);
  25. tv.setText(getSmsInPhone());
  26. ScrollViewsv=newScrollView(this);
  27. sv.addView(tv);
  28. setContentView(sv);
  29. }
  30. publicStringgetSmsInPhone(){
  31. finalStringSMS_URI_ALL="content://sms/";
  32. finalStringSMS_URI_INBOX="content://sms/inbox";
  33. finalStringSMS_URI_SEND="content://sms/sent";
  34. finalStringSMS_URI_DRAFT="content://sms/draft";
  35. finalStringSMS_URI_OUTBOX="content://sms/outbox";
  36. finalStringSMS_URI_FAILED="content://sms/failed";
  37. finalStringSMS_URI_QUEUED="content://sms/queued";
  38. StringBuildersmsBuilder=newStringBuilder();
  39. try{
  40. Uriuri=Uri.parse(SMS_URI_ALL);
  41. String[]projection=newString[]{"_id","address","person","body","date","type"};
  42. Cursorcur=getContentResolver().query(uri,projection,null,null,"datedesc");//获取手机内部短信
  43. if(cur.moveToFirst()){
  44. intindex_Address=cur.getColumnIndex("address");
  45. intindex_Person=cur.getColumnIndex("person");
  46. intindex_Body=cur.getColumnIndex("body");
  47. intindex_Date=cur.getColumnIndex("date");
  48. intindex_Type=cur.getColumnIndex("type");
  49. do{
  50. StringstrAddress=cur.getString(index_Address);
  51. intintPerson=cur.getInt(index_Person);
  52. Stringstrbody=cur.getString(index_Body);
  53. longlongDate=cur.getLong(index_Date);
  54. intintType=cur.getInt(index_Type);
  55. SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss");
  56. Dated=newDate(longDate);
  57. StringstrDate=dateFormat.format(d);
  58. StringstrType="";
  59. if(intType==1){
  60. strType="接收";
  61. }elseif(intType==2){
  62. strType="发送";
  63. }else{
  64. strType="null";
  65. }
  66. smsBuilder.append("[");
  67. smsBuilder.append(strAddress+",");
  68. smsBuilder.append(intPerson+",");
  69. smsBuilder.append(strbody+",");
  70. smsBuilder.append(strDate+",");
  71. smsBuilder.append(strType);
  72. smsBuilder.append("]\n\n");
  73. }while(cur.moveToNext());
  74. if(!cur.isClosed()){
  75. cur.close();
  76. cur=null;
  77. }
  78. }else{
  79. smsBuilder.append("noresult!");
  80. }//endif
  81. smsBuilder.append("getSmsInPhonehasexecuted!");
  82. }catch(SQLiteExceptionex){
  83. Log.d("SQLiteExceptioningetSmsInPhone",ex.getMessage());
  84. }
  85. returnsmsBuilder.toString();
  86. }
  87. }

AndroidManifest.xml 权限

记得在AndroidManifest.xml中加入android.permission.READ_SMS这个permission

<uses-permissionandroid:name="android.permission.READ_SMS"/>


运行结果:

SMS_第1张图片


代码示例



URI主要有:

content://sms/ 所有短信
content://sms/inbox 收件箱
content://sms/sent 已发送
content://sms/draft 草稿
content://sms/outbox 发件箱
content://sms/failed 发送失败
content://sms/queued 待发送列表


sms主要结构:
  1. _id => 短消息序号 如100
  2. thread_id => 对话的序号 如100
  3. address => 发件人地址,手机号.如+8613811810000
  4. person => 发件人,返回一个数字就是联系人列表里的序号,陌生人为null
  5. date => 日期long型。如1256539465022
  6. protocol => 协议0SMS_RPOTO,1MMS_PROTO
  7. read => 是否阅读0未读,1已读
  8. status => 状态 -1接收,0complete,64pending,128failed
  9. type => 类型1是接收到的,2是已发出
  10. body => 短消息内容
  11. service_center => 短信服务中心号码编号。如+8613800755500
String[] projection = new String[]{"address", "body"};
Cursor cursor = getContentResolver().query(uri, projection, "where .." new String[]{"", ""}, "order by ..")


Android短信存储数据库

偶然发现了Android源码中的一个类MmsSmsDatabaseHelper.java,原来android将所有的短信信息都存入了mmssms.db中。

公开的SDK中没有这个类,不能直接使用。于是自己写了一个SQLiteOpenHelper,但是查询的时候发生SQL异常。看来不能为所欲为了,不过据网上资料介绍可以拷贝db文件来实现短信数据备份。

MmsSmsDatabaseHelper.java在Android源码中的路径:

packages/providers/TelephonyProvider/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java


sms数据库中的字段如下:

_id 一个自增字段,从1开始
thread_id 序号,同一发信人的id相同
address 发件人手机号码
person 联系人列表里的序号,陌生人为null
date 发件日期
protocol 协议,分为:0SMS_RPOTO,1MMS_PROTO
read 是否阅读0未读,1已读
status 状态-1接收,0complete,64pending,128failed
type
ALL = 0;
INBOX = 1;
SENT = 2;
DRAFT = 3;
OUTBOX = 4;
FAILED = 5;
QUEUED = 6;

body 短信内容
service_center 短信服务中心号码编号
subject 短信的主题
reply_path_present TP-Reply-Path
locked


sms数据库表字段类型的源码:

[java] view plain copy print ?
  1. privatevoidcreateSmsTables(SQLiteDatabasedb){
  2. //N.B.:Wheneverthecolumnsherearechanged,thecolumnsin
  3. //{@refMmsSmsProvider}mustbechangedtomatch.
  4. db.execSQL("CREATETABLEsms("+
  5. "_idINTEGERPRIMARYKEY,"+
  6. "thread_idINTEGER,"+
  7. "addressTEXT,"+
  8. "personINTEGER,"+
  9. "dateINTEGER,"+
  10. "date_sentINTEGERDEFAULT0,"+
  11. "protocolINTEGER,"+
  12. "readINTEGERDEFAULT0,"+
  13. "statusINTEGERDEFAULT-1,"+//aTP-Statusvalue
  14. //or-1ifit
  15. //statushasn't
  16. //beenreceived
  17. "typeINTEGER,"+
  18. "reply_path_presentINTEGER,"+
  19. "subjectTEXT,"+
  20. "bodyTEXT,"+
  21. "service_centerTEXT,"+
  22. "lockedINTEGERDEFAULT0,"+
  23. "error_codeINTEGERDEFAULT0,"+
  24. "seenINTEGERDEFAULT0"+
  25. ");");
  26. ....
  27. }

packages/providers/TelephonyProvider/src/com/android/providers/telephony/MmsSmsDatabaseHelper.java


联系人为空

短信数据库里面如果你是先受到陌生短信之后再把陌生人添加到联系人列表的话,短信数据库里面的person字段就为null,如果你是先添加联系人再发短信的话,短信数据库里面的person字段就不为空了,所以你要是想通过短信数据库里的字段取得联系人的其他信息的话,只能通过地址来取。


Android SMS(二)—— 读取短信保存到 SQLite

分类:Android 3895人阅读 评论(12) 收藏 举报 sms sqlite android date 数据库 string

Android 之 SMS 短信在Android系统中是保存在SQLite数据库中的,但不让其它程序访问(Android系统的安全机制)

现在我们在读取手机内的SMS短信,先保存在我们自己定义的SQLite数据库中,然后读取SQLite数据库提取短信,并显示


SMS短信SQLite存取代码:

[java] view plain copy print ?
  1. packagecom.homer.sms;
  2. importjava.sql.Date;
  3. importjava.text.SimpleDateFormat;
  4. importorg.loon.wsi.R;
  5. importandroid.app.Activity;
  6. importandroid.content.Context;
  7. importandroid.database.Cursor;
  8. importandroid.database.sqlite.SQLiteDatabase;
  9. importandroid.graphics.Color;
  10. importandroid.net.Uri;
  11. importandroid.os.Bundle;
  12. importandroid.util.Log;
  13. importandroid.widget.TableLayout;
  14. importandroid.widget.TableRow;
  15. importandroid.widget.TableRow.LayoutParams;
  16. importandroid.widget.TextView;
  17. /**
  18. *读取手机短信,先保存到SQLite数据,然后再读取数据库显示
  19. *
  20. *@authorsunboy_2050
  21. *@sincehttp://blog.csdn.net/sunboy_2050
  22. *@date2012.03.06
  23. */
  24. publicclasssmsRead4extendsActivity{
  25. TableLayouttableLayout;
  26. intindex=0;
  27. @Override
  28. publicvoidonCreate(BundlesavedInstanceState){
  29. super.onCreate(savedInstanceState);
  30. setContentView(R.layout.main);
  31. tableLayout=(TableLayout)findViewById(R.id.tableLayout);
  32. showSMS();
  33. }
  34. privatevoidshowSMS(){
  35. SmsHandersmsHander=newSmsHander(this);
  36. smsHander.createSMSDatabase();//创建SQLite数据库
  37. smsHander.insertSMSToDatabase();//读取手机短信,插入SQLite数据库
  38. Cursorcursor=smsHander.querySMSInDatabase(100);//获取前100条短信(日期排序)
  39. cursor.moveToPosition(-1);
  40. while(cursor.moveToNext()){
  41. StringstrAddress=cursor.getString(cursor.getColumnIndex("address"));
  42. StringstrDate=cursor.getString(cursor.getColumnIndex("date"));
  43. StringstrBody=cursor.getString(cursor.getColumnIndex("body"));
  44. SimpleDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
  45. Datedate=newDate(Long.parseLong(strDate));
  46. strDate=dateFormat.format(date);
  47. StringsmsTitle=strAddress+"\t\t"+strDate;
  48. StringsmsBody=strBody+"\n";
  49. Log.i("tableRow",smsTitle+smsBody);
  50. //titleRow
  51. TableRowtrTitle=newTableRow(this);
  52. trTitle.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
  53. TextViewtvTitle=newTextView(this);
  54. tvTitle.setText(smsTitle);
  55. tvTitle.getPaint().setFakeBoldText(true);//加粗字体
  56. tvTitle.setTextColor(Color.RED);
  57. tvTitle.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
  58. trTitle.addView(tvTitle);
  59. tableLayout.addView(trTitle,newTableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
  60. //bodyRow
  61. TableRowtrBody=newTableRow(this);
  62. trBody.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
  63. TextViewtvBody=newTextView(this);
  64. tvBody.setText(smsBody);
  65. tvBody.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
  66. trBody.addView(tvBody);
  67. tableLayout.addView(trBody,newTableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
  68. }
  69. if(!cursor.isClosed()){
  70. cursor.close();
  71. cursor=null;
  72. }
  73. smsHander.closeSMSDatabase();
  74. index=0;
  75. }
  76. publicclassSmsHander{
  77. SQLiteDatabasedb;
  78. Contextcontext;
  79. publicSmsHander(Contextcontext){
  80. this.context=context;
  81. }
  82. publicvoidcreateSMSDatabase(){
  83. Stringsql="createtableifnotexistssms("
  84. +"_idintegerprimarykeyautoincrement,"
  85. +"addressvarchar(255),"+"personvarchar(255),"
  86. +"bodyvarchar(1024),"+"datevarchar(255),"
  87. +"typeinteger)";
  88. db=SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString()+"/data.db3",null);//创建数据库
  89. db.execSQL(sql);
  90. }
  91. //获取手机短信
  92. privateCursorgetSMSInPhone(){
  93. UriSMS_CONTENT=Uri.parse("content://sms/");
  94. String[]projection=newString[]{"_id","address","person","body","date","type"};
  95. Cursorcursor=context.getContentResolver().query(SMS_CONTENT,projection,null,null,"datedesc");//获取手机短信
  96. while(cursor.moveToNext()){
  97. System.out.println("--sms--:"+cursor.getString(cursor.getColumnIndex("body")));
  98. }
  99. returncursor;
  100. }
  101. //保存手机短信到SQLite数据库
  102. publicvoidinsertSMSToDatabase(){
  103. LonglastTime;
  104. CursordbCount=db.rawQuery("selectcount(*)fromsms",null);
  105. dbCount.moveToFirst();
  106. if(dbCount.getInt(0)>0){
  107. Cursordbcur=db.rawQuery("select*fromsmsorderbydatedesclimit1",null);
  108. dbcur.moveToFirst();
  109. lastTime=Long.parseLong(dbcur.getString(dbcur.getColumnIndex("date")));
  110. }else{
  111. lastTime=newLong(0);
  112. }
  113. dbCount.close();
  114. dbCount=null;
  115. Cursorcur=getSMSInPhone();//获取短信(游标)
  116. db.beginTransaction();//开始事务处理
  117. if(cur.moveToFirst()){
  118. Stringaddress;
  119. Stringperson;
  120. Stringbody;
  121. Stringdate;
  122. inttype;
  123. intiAddress=cur.getColumnIndex("address");
  124. intiPerson=cur.getColumnIndex("person");
  125. intiBody=cur.getColumnIndex("body");
  126. intiDate=cur.getColumnIndex("date");
  127. intiType=cur.getColumnIndex("type");
  128. do{
  129. address=cur.getString(iAddress);
  130. person=cur.getString(iPerson);
  131. body=cur.getString(iBody);
  132. date=cur.getString(iDate);
  133. type=cur.getInt(iType);
  134. if(Long.parseLong(date)>lastTime){
  135. Stringsql="insertintosmsvalues(null,?,?,?,?,?)";
  136. Object[]bindArgs=newObject[]{address,person,body,date,type};
  137. db.execSQL(sql,bindArgs);
  138. }else{
  139. break;
  140. }
  141. }while(cur.moveToNext());
  142. cur.close();
  143. cur=null;
  144. db.setTransactionSuccessful();//设置事务处理成功,不设置会自动回滚不提交
  145. db.endTransaction();//结束事务处理
  146. }
  147. }
  148. //获取SQLite数据库中的全部短信
  149. publicCursorquerySMSFromDatabase(){
  150. Stringsql="select*fromsmsorderbydatedesc";
  151. returndb.rawQuery(sql,null);
  152. }
  153. //获取SQLite数据库中的最新size条短信
  154. publicCursorquerySMSInDatabase(intsize){
  155. Stringsql;
  156. CursordbCount=db.rawQuery("selectcount(*)fromsms",null);
  157. dbCount.moveToFirst();
  158. if(size<dbCount.getInt(0)){//不足size条短信,则取前size条
  159. sql="select*fromsmsorderbydatedesclimit"+size;
  160. }else{
  161. sql="select*fromsmsorderbydatedesc";
  162. }
  163. dbCount.close();
  164. dbCount=null;
  165. returndb.rawQuery(sql,null);
  166. }
  167. //获取SQLite数据库的前second秒短信
  168. publicCursorgetSMSInDatabaseFrom(longsecond){
  169. longtime=System.currentTimeMillis()/1000-second;
  170. Stringsql="select*fromsmsorderbydatedescwheredate>"+time;
  171. returndb.rawQuery(sql,null);
  172. }
  173. //关闭数据库
  174. publicvoidcloseSMSDatabase(){
  175. if(db!=null&&db.isOpen()){
  176. db.close();
  177. db=null;
  178. }
  179. }
  180. }
  181. }
运行结果:

SMS_第2张图片


代码示例


推荐参考:

Android 之 SMS 短信读取



更多相关文章

  1. android最简单的发送文本短信的demo
  2. android 拨打电话与发送短信
  3. Android中短信拦截的实现
  4. 关于 SQLiteOpenHelper 的自创建数据库目录文件
  5. Android 拦截 接收 短信
  6. android 读取短信内容
  7. Android 数据库事务操作

随机推荐

  1. android 遍历安装过的包名
  2. 横向 纵向结合的ScrollView
  3. android 内核添加tourch screen
  4. Android 一些常用的但是记不住的设置
  5. android 版 双色球号码生成
  6. android实现左右滑动菜单
  7. Android 自定义滚动视图
  8. android 按钮的点击缩放
  9. Android API之android.content.AsyncQuer
  10. android studio 与gradle的版本对应