數據庫獲取 Android 簡訊

點擊上方「Android編程精選」,選擇「置頂公眾號」關鍵時刻,第一時間送達!

來源:Android開發中文站

https://mp.weixin.qq.com/s/2nnLB55KnFvpYfgb2XFBFA

Android編程精整理髮布,轉載請聯繫作者獲得授權

讀取簡訊需要的權限
<uses-permissionandroid:name="android.permission.READ_SMS"/>
讀取數據庫簡訊方法
publicstaticList<Map<String,String>>getSmsCode(){StringlastTime="1534228493681";//時間Log.i("SMSUtil","開始獲取簡訊");Cursorcursor=null;//添加異常捕捉try{//第一種,查詢所有簡訊cursor=App.mContext.getContentResolver().query(Uri.parse("content://sms"),newString[]{"_id","address","body","date","person","type"},null,null,"datedesc");//第二種,通過查詢條件,例如:date>lastTime,過濾數據/*cursor=App.mContext.getContentResolver().query(Uri.parse("content://sms"),newString[]{"_id","address","body","date","person","type"},"date>?",newString[]{lastTime},"datedesc");*/if(cursor!=null){List<Map<String,String>>smsList=newArrayList<>();while(cursor.moveToNext()){Stringbody=cursor.getString(cursor.getColumnIndex("body"));//在這里獲取簡訊信息Stringperson=cursor.getString(cursor.getColumnIndex("person"));//陌生人為nullStringaddress=cursor.getString(cursor.getColumnIndex("address"));String_id=cursor.getString(cursor.getColumnIndex("_id"));Stringdate=cursor.getString(cursor.getColumnIndex("date"));Stringtype=cursor.getString(cursor.getColumnIndex("type"));HashMap<String,String>smsMap=newHashMap<>();smsMap.put("body",body);smsMap.put("person",person);smsMap.put("address",address);smsMap.put("_id",_id);smsMap.put("date",date);smsList.add(smsMap);Log.i("test_sms","body="+body+"person="+person+"address="+address+"date="+date+"type="+type);}//返回所有的簡訊returnsmsList;}}catch(Exceptione){e.printStackTrace();Log.i("test_sms","e="+e.getMessage());}finally{if(cursor!=null){cursor.close();}}returnnull;}
URI 主要有:
content://sms/所有簡訊(本示例用的所有)content://sms/inbox收件箱content://sms/sent已發送content://sms/draft草稿content://sms/outbox發件箱content://sms/failed發送失敗content://sms/queued待發送列表
SMS 主要結構:
_id=>短消息序號如100thread_id=>對話的序號如100address=>發件人地址,手機號.如+8613811810000person=>發件人,返回一個數字就是聯繫人列表里的序號,陌生人為nulldate=>日期long型。如1256539465022protocol=>協議0SMS_RPOTO,1MMS_PROTOread=>是否閱讀0未讀,1已讀status=>狀態-1接收,0complete,64pending,128failedtype=>類型1是接收到的,2是已發出(ALL=0;所有INBOX=1;收件箱SENT=2;已發送DRAFT=3;草稿OUTBOX=4;發件箱FAILED=5;失敗QUEUED=6;)待發送body=>短消息內容service_center=>簡訊服務中心號碼編號。如+8613800755500
參考鏈接

https://blog.csdn.net/ithomer/article/details/7328321https://blog.csdn.net/laichao1112/article/details/6436511

【點擊成為Java大神】

[do_widget id=yuzo_widget-4] [do_widget id=yuzo_widget-9] 流行