1

So im making an app that uses sms to send data between two devices and am trying to get one to automaticly respond to the other. But the string getMessageBody() is returning isnt setting of the if statment to send the automatic message even tho the log output "(test)" seems to match the condition. I have added extra text to either side of the string in the log message to check for whitespace. Thanks in advance.

The code sending the message to be received.

SendSMS(inputNum.getText().toString(),"test");

The receiver code

public void onReceive(Context context, Intent intent)
        {
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            if(bundle != null)
            {
                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]);
                    originNumber = msgs[i].getOriginatingAddress();
                    messages = msgs[i].getMessageBody();
                    Log.e("Received Text", messages);

                }
                if(messages == "test")
                    SendSMS(originNumber, "auto send");
                else
                    Log.e("else Text", "("+messages+")");
            }
4

1 回答 1

2
   if(messages == "test")

java中的字符串比较需要equals方法。与==您将比较消息的地址和“测试”的地址。由于这些是不同的 String 对象,因此结果将是错误的。将其更改为:

   if(messages.equals("test"))
于 2013-05-18T13:34:42.273 回答