在Android上阅读传入的消息

时间:2013-06-16 14:20:07

标签: android sms message

我最初使用以下代码来阅读接收消息,以便我可以在我的应用程序中使用它来跟踪手机。

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

我在行

中收到一条错误消息“消息无法解析为变量”
for(SmsMessage msg : messages) {

我不知道该怎么做。请帮帮我们。 提前致谢。 :-)

更新#1:

hannanessay的回应起到了作用。但是现在,对于createFromPdu,getMessageBody(),getOriginatingAddress(),getDefault()和sendTextMessage,我收到一条错误,说“呼叫需要API级别4(当前最小值为1)”。对此有何帮助?

1 个答案:

答案 0 :(得分:1)

从代码的下面一行,我们可以看到使用的变量是msgs。

  msgs = new SmsMessage[pdus.length];

您在以下行中使用消息的位置。将其更改为msgs(可能会有效)。

  for (SmsMessage msg : messages)  //Old

  for (SmsMessage msg : msgs)   //New
相关问题