Search code examples
androidsms

Android broadcastreceiver creates new instances


Well, I have a class extending broadcastreceiver which is listening for messages. Now whenever it receives a message I creates a new instance of my app. So when I am closing it I have to tap back button 2 times.

public class SMSReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
    Bundle myBundle = intent.getExtras();
    SmsMessage [] messages = null;
    String strMessage = "";
    String phoneNumber = "";

    if (myBundle != null) {
        Object [] pdus = (Object[]) myBundle.get("pdus");
        messages = new SmsMessage[pdus.length];

        for (int i = 0; i < messages.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            strMessage += "SMS From: " + messages[i].getOriginatingAddress();
            strMessage += " : ";
            strMessage += messages[i].getMessageBody();
            strMessage += "\n";
            
            phoneNumber = messages[i].getDisplayOriginatingAddress();
        }
        
        if (phoneNumber.equals("T-Mobile")) {
            Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
            abortBroadcast();
        }

    }
}
}

Solution

  • First of all, I don't really think it is creating a new instance of your app. What is more likely happening is that an activity is being brought to the front. I think you should look at the manifest or post it so we can see how the broadcasts are being directed. It could be that the target of the broadcast also has the effect of starting the activity. So check the manifest, there is nothing in the broadcast receiver that will cause this. Having said that its really up to the Android OS what gets shown when. But as far as two instances. Thats just not happening.

    PS. I don't know the exact reason but I would say probably don't issue Toast from a broadcast reeiver, instead communicate to an activity using startActivity().