Reputation: 2801
I have been developing the application and I need to process body of text. I try to use BroadcastReceiver
for it:
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);
}
}
But this code returns last sms, not a NEW sms. But I need to receive NEW sms. How can I do it?
Upvotes: 0
Views: 509
Reputation: 29642
Please Change your following lines,
Cursor sms = context.getContentResolver().query(SMS_INBOX_URI, null, null, null, null);
sms.moveToFirst();
to, like below,
Cursor sms = context.getContentResolver().query(SMS_INBOX_URI, null, null, null, null);
sms.moveToLast(); // Moving to newly received SMS
Upvotes: 0
Reputation: 20132
To recieve an sms A very very goood tutorial is 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();
}
}
Upvotes: 1