Search code examples
androidandroid-activitysmslaunching

Can't launch the activity again if it's already open


I'am working on SMS manager like app. Now when an SMS is received a new Dialog Activity like a pop-up which shows the user the Sender's number and message. It's OK but if another SMS comes before the user press Back button (the Pop-Up activity still there on the Top), then the new SMS can't be shown to the user. Every new SMS should show up on the pop-up activity diminish any older SMS if on foreground.

I tried in and out the onReceive method of the Broadcast Receiver class. By digging deeper I found that if the pop-up with an SMS is on foreground, the Pop-up Activity cannot gets called. It just don't come to the OnCreate method.

BroadcastReceiver class:

public class SmsBroadcastReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";
    public static String latestSMSnumber, latestSMScontent;
    SmsMessage[] msgs = null;
    String str = "";

    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; ++i) {
                // Convert Object array
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                               // Fetch the text message
                str += msgs[i].getMessageBody().toString();
                str += "\n";
                latestSMSnumber = msgs[i].getOriginatingAddress();
                latestSMScontent = str;

            }
            // Display the entire SMS Message
            Log.e("TAG1 number: ", latestSMSnumber);
            Log.e("TAG2 content: ", str);
            latestSMScontent = str;
//            Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

            Intent i=new Intent(context.getApplicationContext(),NewSMS.class);
//            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.putExtra("Number", latestSMSnumber);
            i.putExtra("MsgBody", latestSMScontent);
            context.startActivity(i);
        }
    }
}

I like to show any new SMS with number and msg text in the pop-up window.


Solution

  • Write This in you manifest.xml file in activity tag NewSMS Activity

    android:launchMode=”singleTop”

    For more information Please read the bellow link

    https://android.jlelse.eu/android-activity-launch-mode-e0df1aa72242