从特定号码读取短信

时间:2013-05-03 19:25:30

标签: android sms android-activity

我想在我的收件箱中阅读特定的短信。我在互联网上找到了如何阅读收件箱中的所有短信。这就是我做的。请帮我只读一个特定号码的短信。感谢

package com.example.liresms;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class ReadSMS extends MainActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      TextView view = new TextView(this);
      Uri uriSMSURI = Uri.parse("content://sms/inbox");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
      String sms = "";
      while (cur.moveToNext()) {
          sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";         
      }
      view.setText(sms);
      setContentView(view);
  }
}

2 个答案:

答案 0 :(得分:1)

试试这个:

StringBuilder smsBuilder = new StringBuilder();
final String SMS_URI_INBOX = "content://sms/inbox"; 
final String SMS_URI_ALL = "content://sms/";  
try 
{  
    Uri uri = Uri.parse(SMS_URI_INBOX);  
    String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };  
    Cursor cur = getContentResolver().query(uri, projection, "address=123456789", null, "date desc");
    if (cur.moveToFirst()) 
    {  
        int index_Address = cur.getColumnIndex("address");  
        int index_Person = cur.getColumnIndex("person");  
        int index_Body = cur.getColumnIndex("body");  
        int index_Date = cur.getColumnIndex("date");  
        int index_Type = cur.getColumnIndex("type");         
        do 
        {  
            String strAddress = cur.getString(index_Address);  
            int intPerson = cur.getInt(index_Person);  
            String strbody = cur.getString(index_Body);  
            long longDate = cur.getLong(index_Date);  
            int int_Type = cur.getInt(index_Type);  

            smsBuilder.append("[ ");  
            smsBuilder.append(strAddress + ", ");  
            smsBuilder.append(intPerson + ", ");  
            smsBuilder.append(strbody + ", ");  
            smsBuilder.append(longDate + ", ");  
            smsBuilder.append(int_Type);  
            smsBuilder.append(" ]\n\n");  
        }while (cur.moveToNext());  
        if (!cur.isClosed()) 
        {  
            cur.close();  
            cur = null;  
        }  
    } 
    else 
    {  
        smsBuilder.append("no result!");  
    }  
} 
catch (SQLiteException ex) 
{  
    Log.d("SQLiteException", ex.getMessage());  
}  

在AndroidManifest.xml中包含此权限:

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

答案 1 :(得分:0)

你已经非常接近已经做到了。我建议您查看ContentResolver.query方法的参数,并特别注意selection参数。您要做的只是选择特定列等于您要查找的数字的消息...

这样的东西
Cursor cur = getContentResolver().query(uriSMSURI, null, "from=6159995555", null,null);

我不知道具体的专栏名称,但这应该让你开始正确的方向......