2 MainActivities after Broadcast receiver

My app should be opened after the broadcast receiver operation. But if my app opens at the current moment I need to delete the previous MainActivity and create a new MainActivity. How to start MainActivity from broadcast receiver and delete the previous MainActivity if the activity starts before?

Broadcast:

Intent initialIntent = context.getPackageManager().getLaunchIntentForPackage("com.cc.dd");
    initialIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    initialIntent.putExtra(Constants.NUMBER,getIncomingNumber(mCallState));
    context.startActivity(initialIntent);

I tried to use flags but I have strange logs:

D/CallReceiver: main: [RINGING]
D/CallReceiver: main: [Incoming call true]
D/MainActivity: main: [ON_PAUSE]
D/MainActivity: main: [ON_CREATE]
D/MainActivity: main: [ON_START]
D/MainActivity: main: [ON_RESUME]

I see the MainActivity previous version goes to onPause and the new version starts. Why the previous version doesn't delete?


You need to call finish() if you want to end an activity's life-cycle. Following code will simply restart the current activity:

Intent intent = getIntent();
finish();
startActivity(intent);

or

Intent intent = new Intent(YourActivity.this,YourActivity.class);
startActivity(intent);
finish();

References:

  • How do I restart an Android Activity
  • How to restart an Android Activity?