2016-08-04 54 views
0

我想知道如何讀取特定的手機號碼收到某個特定日期過去五年短信接收的最後5 SMS。閱讀從一個特定的號碼在特定日期

我知道如何閱讀特定發件人的所有短信,以及如何閱讀最後一條短信,但我無法讀取和閱讀最近幾個短信。我嘗試用

"date DESC LIMIT 5" 

我的代碼讀取它們就像是時間低於

Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox"); 
String[] projection = {"address", "body"}; 
Cursor cursor1 = MainActivity.this.getContentResolver().query(mSmsinboxQueryUri, 
                   null, 
                   "address = ?", 
                   new String[]{phoneNumber}, 
                   "date DESC LIMIT 5"); 

if (cursor1 != null && cursor1.moveToFirst()) { 
    body = cursor1.getString(cursor1.getColumnIndex("body")); 
    totalBody = totalBody + body; 
    Log.d("Registration", totalBody); 
} 

但每次它顯示只有最後一條消息。

回答

0

您只看到一封郵件,因爲您的代碼只處理返回的Cursor中的第一條記錄。您需要遍歷Cursor來處理其餘的問題。例如:

if (cursor != null && cursor.moveToFirst()) { 
    do { 
     body = cursor1.getString(cursor1.getColumnIndex("body")); 
     totalBody = totalBody + body; 
     Log.d("Registration", totalBody); 
    } while (cursor.moveToNext()); 
} 

另外,如果你想查詢限制到某一天,你可以使用一個Calendar推測的開始和結束時間爲當天以毫秒爲單位 - 因爲這是日期是如何存儲在SMS表 - 並將相應的比較添加到where子句中。例如:

private static final int DAY_MILLISECONDS = 24 * 60 * 60 * 1000; 
private static final Uri inboxUri = Uri.parse("content://sms/inbox"); 

// Months are zero-based; i.e., JANUARY == 0 
// Phone number must be exact in this example 
private void listMessages(String phoneNumber, int year, int month, int day) { 
    Calendar cal = Calendar.getInstance(); 
    cal.set(Calendar.YEAR, year); 
    cal.set(Calendar.MONTH, month); 
    cal.set(Calendar.DATE, day); 
    cal.set(Calendar.HOUR_OF_DAY, 0); 
    cal.set(Calendar.MINUTE, 0); 
    cal.set(Calendar.SECOND, 0); 
    cal.set(Calendar.MILLISECOND, 0); 

    String[] projection = {"address", "body"}; 
    String whereAddress = "address = ?"; 
    String whereDate = "date BETWEEN " + cal.getTimeInMillis() + 
         " AND " + (cal.getTimeInMillis() + DAY_MILLISECONDS); 
    String where = DatabaseUtils.concatenateWhere(whereAddress, whereDate); 

    Cursor cursor = null; 
    try { 
     cursor = getContentResolver().query(inboxUri, 
              projection, 
              where, 
              new String[]{phoneNumber}, 
              "date DESC LIMIT 5"); 

     if (cursor != null && cursor.moveToFirst()) { 
      do { 
       Log.d("Message", cursor.getString(cursor.getColumnIndex("body"))); 
      } while (cursor.moveToNext()); 
     } 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    finally { 
     if (cursor != null) { 
      cursor.close(); 
     } 
    } 
}