1

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?

Delphian
  • 1,650
  • 3
  • 15
  • 31
  • 1
    you can add `android:launchMode = "singleInstance"` to your activity tag in manifest. That ensures that your activity is only opened once.... – Opiatefuchs Jun 21 '16 at 08:00
  • what is the issue you are facing – JAAD Jun 21 '16 at 08:00
  • So if you want to kill all the previous activities, just follow these methods. In API level 11 or greater, use FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK flag on Intent to clear all the activity stack. initialIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent. FLAG_ACTIVITY_NEW_TASK); Another way is android:launchMode= "singleInstance" how Opiatefuchs said. – YLS Jun 21 '16 at 08:04

3 Answers3

3

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:

Community
  • 1
  • 1
1

You can simply add:

android:launchMode = "singleInstance"

to your activity tag in manifest. That ensures that your activity is only opened once. Example:

<activity
android:name=".YourActivity"
android:label="@string/your_activity_name"
android:launchMode = "singleInstance" />
Opiatefuchs
  • 9,800
  • 2
  • 36
  • 49
0

I think you cannot delete previous activity.You can add flag singleInstance for your activity.

asdcvf
  • 199
  • 3
  • 13