user2295392
user2295392

Reputation: 25

Reading the incoming messages on Android

I initially used the below code to read the receiving messages so that I can use it in my application for tracking a phone.

            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();

                }

                for (SmsMessage msg : messages) {
                        if (msg.getMessageBody().contains("SMSLOCATE:")) {
                                String[] tokens = msg.getMessageBody().split(":");
                                if (tokens.length >= 2) {
                                        String md5hash = PhoneFinder.getMd5Hash(tokens[1]);
                                        if (md5hash.equals(correctMd5)) {
                                                String to = msg.getOriginatingAddress();
                                                LocationManager lm =
                                                        (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

                                                SmsManager sm = SmsManager.getDefault();

                                                sm.sendTextMessage(to, null, lm.getLastKnownLocation("gps").toString(),
                                                                null, null);

                                                Toast.makeText(context, context.getResources().getString(R.string.notify_text) + to,
                                                                Toast.LENGTH_SHORT).show();
                                        }

I get an error message saying "messages cannot be resolved to a variable" in the line

for(SmsMessage msg : messages) {

I do not know what to do here. Please help me out guys. Thanks in advance. :-)

UPDATE #1:

The response from hannanessay did the trick. BUT now, for createFromPdu, getMessageBody() , getOriginatingAddress() , getDefault() and sendTextMessage , I get an error saying "Call requires API level 4 (current min is 1)". Any help on this?

Upvotes: 0

Views: 738

Answers (1)

Hannan Shaik
Hannan Shaik

Reputation: 1306

From the below line in your code, we can see that the variable used is msgs.

  msgs = new SmsMessage[pdus.length];

Where as you are using messages in the below line. Change it to msgs (it might work).

  for (SmsMessage msg : messages)  //Old

  for (SmsMessage msg : msgs)   //New

Upvotes: 1

Related Questions