开发者

Can't compare received SMS text to value in Android

开发者 https://www.devze.com 2023-01-24 10:57 出处:网络
Im new to programming, so bear with me. After following a co开发者_开发知识库uple of tutorials i made an SMS application, i want to do an specific task when a specific text is received, i do this by c

Im new to programming, so bear with me. After following a co开发者_开发知识库uple of tutorials i made an SMS application, i want to do an specific task when a specific text is received, i do this by comparing the text received to a value(code) that i already declared. The problem is that this condition never ocurrs.


public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";
        String code = "blue";
        String conf = "Ok";
        String inv = "Invalid";


    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();
            //n = Integer.parseInt(str);

        }

        if (str == code)
          Toast.makeText(context, conf, Toast.LENGTH_SHORT).show();
         else 
            //str = Integer.toString(n);
            //Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
          Toast.makeText(context, inv, Toast.LENGTH_SHORT).show();


    } 

  }

}

When I send the message it always displays the inv variable (Invalid). I tried to change the "code" variable to an integer, and then parse the string so I could compare it; in this scenario it did work, but whenever I received a string message the application crashes. I think it should be a simple thing, but since i don't fully understand java i can't figure it out. I hope you could provide me with some guidelines or suggestions about what could i do. Thanks in advance.


When comparing two strings, you should be using:

if (str.equals(code))

Java does not override the equals operator for string equality testing like it does for concatenation.

The test str == code only evaluates to true if the two String variables both refer to the EXACT same object in memory.


String str1 = "hello";

String str2 = "world";

if (str1 == str2) // not applicable for strings, can be use for integers

if (str1.equals(str2)) // applicable for strings

if (str1.compareTo(str2) > 0) // applicable for strings

0

精彩评论

暂无评论...
验证码 换一张
取 消