0

I have an if statement that should trigger if the sms is coming from a specific number, however it never triggers. here is my SMSReceiver.java:

public String SMSMessage;
public String incomingNumber;

public void onReceive(Context context, Intent intent) 
{
    if (intent.getAction().equals(SMS_RECEIVED)) 
    {
        abortBroadcast();
        Bundle bundle = intent.getExtras();
        if (bundle != null) 
        {
            Object[] pdus = (Object[])bundle.get("pdus");
            final SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++)
            {
                messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            }
            SMSMessage = messages[0].getMessageBody();
            incomingNumber = messages[0].getOriginatingAddress();
            MainActivity.updatePowerUsageTitle(SMSMessage);
            MainActivity.updatePowerUsageSummary(incomingNumber);
            if (incomingNumber == "XXXXXXXXX" || incomingNumber == "XXXXXXXXXX")
            {  
                Toast.makeText(context, messages[0].getMessageBody(), Toast.LENGTH_SHORT).show();
                if (SMSMessage.contains("Turn"))
                {
                    //TODO: Set toast for incoming message
                    Toast.makeText(context, messages[0].getMessageBody(), Toast.LENGTH_SHORT).show();
                }
                else if (SMSMessage.contains("ref"))
                {
                    //TODO: Set refresh for switches
                }
                else if (SMSMessage.contains("power"))
                {
                    //Refresh power stats
                    int END = SMSMessage.length();
                    SMSMessage = SMSMessage.substring(6 , END);
                    MainActivity.updatePowerUsageTitle(SMSMessage);
                }
            }
        }
    }
}

This is the part that matters:

incomingNumber = messages[0].getOriginatingAddress();
if (incomingNumber == "XXXXXXXXX" || incomingNumber == "XXXXXXXXXX")
{
Toast.makeText(context, messages[0].getMessageBody(), Toast.LENGTH_SHORT).show();
}

Obviously, I didn't put the phone numbers on here, but I know that the numbers are correct. Any clue as to why the if statement is not triggering?

xAtaxia
  • 5
  • 3

1 Answers1

2

Try to compare your Strings with .equals() since that is the proper way to compare Strings in Java. == will compare the references instead. This SO question explains the difference.

if ("XXXXXXXXX".equals(incomingNumber) || "XYZ".equals(incomingNumber))

And as usual, make sure you have the proper permissions in the manifest. Also if this still doesn't work, put a print statement at the root of onReceive() to check if the method is being called at all.

Community
  • 1
  • 1
A--C
  • 36,351
  • 10
  • 106
  • 92