读取在特定日期从特定号码接收的最后5条短信

本教程将介绍读取在特定日期从特定号码接收的最后5条短信的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

读取在特定日期从特定号码接收的最后5条短信 教程 第1张

问题描述

我想知道怎么阅读在特定日期从特定手机号码收到的最后五条短信。

我知道怎么读取来自特定发件人的所有短信,以及怎么读取最后一条短信,但我无法获取和读取最后几条短信。我试着使用

来阅读它们

"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);
}

但每次只显示最后一条消息。

推荐答案

您只看到一条消息,因为您的代码只处理返回的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();
  }
 }
}

好了关于读取在特定日期从特定号码接收的最后5条短信的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。