Completion of all activities begun prior to the start of activities

I want to finish all the actions that are performed in the application, means that you want to remove all the parent actions from the stack.

I want to implement the local exit function locally in my application, so as I was thinking, I will finish all the actions that I started earlier, and the login activity will start again.

+6
source share
3 answers

I must report that this is not recommended behavior in Android, as you must allow yourself to manage the life cycles of actions.

However, if you really need to do this, you can use FLAG_ACTIVITY_CLEAR_TOP

I give you a code example here, where MainActivity is the first activity in the application:

public static void home(Context ctx) { if (!(ctx instanceof MainMenuActivity)) { Intent intent = new Intent(ctx, MainMenuActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ctx.startActivity(intent); } } 

If you want to exit the entire application , you can use the following code and check MainActivity to completely close the application:

  public static void clearAndExit(Context ctx) { if (!(ctx instanceof MainMenuActivity)) { Intent intent = new Intent(ctx, MainMenuActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Bundle bundle = new Bundle(); bundle.putBoolean("exit", true); intent.putExtras(bundle); ctx.startActivity(intent); } else { ((Activity) ctx).finish(); } } 

Hope this helps.

+8
source

Try this if you aim APi Level <11

 Intent intent = new Intent(getApplicationContext(), LoginActivity.class); ComponentName cn = intent.getComponent(); Intent mainIntent = IntentCompat.makeRestartActivityTask(cn); startActivity(mainIntent); 
+3
source

What would you look for, FLAG_ACTIVITY_CLEAR_TOP flag of intent:

If it is set, and the launched activity is already running in the current task, instead of launching a new instance of this action, all other actions on top of it will be closed, and this intention will be delivered to (now above) the old activity as a new intention.

 Intent i = new Intent(..); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

and then run Activity with this intention.

For more information on tasks and the reverse stack, see the documentation: Tasks and Stop File .

However, to implement login / logout into the application (if it does not interact with the online service), you can use SharedPreferences . Thus, when starting the application, you can check whether the user is registered (for example, a certain flag is enabled in the settings) and when the application exits (for example, by clicking a button), you can clear this flag.

Killing / Removing Actions must be left on the system. For system design, the Android OS is responsible for the life of the application.

For example, check the sources of Password Safe . It requires a password every time you open a new instance of the application.

+2
source

Source: https://habr.com/ru/post/889601/


All Articles