讀取短信須要的權限android
<uses-permission android:name="android.permission.READ_SMS"/>
讀取數據庫短信方法數據庫
public static List<Map<String, String>> getSmsCode() { String lastTime = "1534228493681"; // 時間 Log.i("SMSUtil", "開始獲取短信"); Cursor cursor = null; // 添加異常捕捉 try { //第一種, 查詢全部短信 cursor = App.mContext.getContentResolver().query( Uri.parse("content://sms"), new String[]{"_id", "address", "body", "date", "person", "type"}, null, null, "date desc"); //第二種, 經過查詢條件, 例如:date > lastTime, 過濾數據 /*cursor = App.mContext.getContentResolver().query( Uri.parse("content://sms"), new String[]{"_id", "address", "body", "date", "person", "type"}, "date > ?", new String[]{lastTime}, "date desc");*/ if (cursor != null) { List<Map<String, String>> smsList = new ArrayList<>(); while (cursor.moveToNext()) { String body = cursor.getString(cursor.getColumnIndex("body"));// 在這裏獲取短信信息 String person = cursor.getString(cursor.getColumnIndex("person")); // 陌生人爲null String address = cursor.getString(cursor.getColumnIndex("address")); String _id = cursor.getString(cursor.getColumnIndex("_id")); String date = cursor.getString(cursor.getColumnIndex("date")); String type = cursor.getString(cursor.getColumnIndex("type")); HashMap<String, String> smsMap = new HashMap<>(); 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); } // 返回全部的短信 return smsList; } } catch (Exception e) { e.printStackTrace(); Log.i("test_sms", "e = " + e.getMessage()); } finally { if (cursor != null) { cursor.close(); } } return null; }
URI 主要有:code