如何从设备上获取新的短信?

时间:2012-05-19 09:04:25

标签: java android sms

我一直在开发应用程序,我需要处理文本正文。我尝试使用BroadcastReceiver

private static final Uri SMS_INBOX_URI = Uri.parse("content://sms/inbox");

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(context);

    Cursor sms = context.getContentResolver().query(SMS_INBOX_URI, null, null, null, null);
    sms.moveToFirst();

    String body=sms.getString(sms.getColumnIndex("body"));
    String number=sms.getString(sms.getColumnIndex("address"));
    String key=prefs.getString(context.getString(R.string.acc_key_key), "");
    sms.close();
    Log.e("body", body);
    if (body.trim().equals("#"+key)) {
        Log.e("sms", "sending");
        sendGPSCoordinates(context, number);
    } else if (body.trim().equals("?"+key)){
        Log.e("request", "manual");
        sendResponces(context);
    }
}

但是这段代码会返回最后的短信,而不是新的短信。但我需要收到新的短信。我该怎么做?

2 个答案:

答案 0 :(得分:1)

接收短信非常好的教程是HERE

@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 += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }

答案 1 :(得分:0)

请更改以下内容,

Cursor sms = context.getContentResolver().query(SMS_INBOX_URI, null, null, null, null);
sms.moveToFirst();

to,如下所示,

Cursor sms = context.getContentResolver().query(SMS_INBOX_URI, null, null, null, null);
sms.moveToLast();   // Moving to newly received SMS