收听和接收特定的短信?

时间:2011-09-12 11:43:45

标签: android string sms broadcastreceiver

好的我有这个广播接收器用于收听传入的短信

public class SmsReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

                str += msgs[i].getMessageBody().toString();

            }

            }

            try {
                File root = Environment.getExternalStorageDirectory();
                if (root.canWrite()){
                File dir = new File (root.getAbsolutePath() + "/Bonbon info");
                dir.mkdirs();
                File f = new File(dir, "test.txt");
                FileWriter fw = new FileWriter(f);
                BufferedWriter out = new BufferedWriter(fw);
                out.write(str);
                out.close();
                }
                } catch (IOException e) {
                }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_LONG).show();

        }                         
    }

现在,我只需要收听特定的短信,短信中的第一个单词有“Nemas”或“Potrosio”字样。你可以帮我这个吗????

编辑:我犯了一个错误,我没有问一个正确的问题。我想收听所有邮件,但只有包含特定文本的短信我需要保存到文本文件中吗?

1 个答案:

答案 0 :(得分:0)

注意:我相信这适用于所有手机,但未经过测试。

Uri allMessage = Uri.parse("content://sms/inbox");
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(allMessage, new String[]{"body"}, null, null, null);

        while (c.moveToNext()) {

            if(c.getColumnName(0).equals("body")){
                String result = c.getString(0);

            }
        }

这会从手机上存储的每条短信中获取正文。如果您只想查看过去一小时的文本:

String selection = "date>=" + (System.currentTimeMillis()-60*60*1000);

        Uri allMessage = Uri.parse("content://sms/inbox");
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(allMessage, new String[]{"body"}, null, null, null);

        while (c.moveToNext()) {

            if(c.getColumnName(0).equals("body")){
                String result = c.getString(0);

            }
        }

从那里你应该能够通过短信的主体搜索你需要的东西或者写一个查询(就像日期例子一样)来搜索它们。