- Closing All Activities and Launching Any Specific Activity
- Kotlin
- Go to Code Line from Logcat Output Line
- April 28, 2018
- Percentage Width/Height using Constraint Layout
- April 27, 2018
- How to stop activity in Android ?
- 6 Answers 6
- Android destroying activities, killing processes
- 2 Answers 2
- How to stop an activity in android using intent?
- 3 Answers 3
- Android, Finish all activities
- 7 Answers 7
- How to close all activities in Android:
Closing All Activities and Launching Any Specific Activity
Often times, most apps have an option where all the activities of the current app are closed and any new specific activity is launched. For example, on logging out of the application, all the activities are closed and login activity is started to allow user to make any new session.
This can be done using few lines code with power of intents like this:
Kotlin
If you liked this article, you can read my new articles below:
Go to Code Line from Logcat Output Line
Let’s start by looking at our typical good’ol logcat window in Android Studio like this: Now, when you get this kind of logs while coding your awesome apps, then your first question would be: Where is the source code line for this log?
April 28, 2018
Percentage Width/Height using Constraint Layout
UPDATE: I’ve started a new articlw series on ConstraintLayout to discuss tips and tricks regularly. Here’s the first article about it. 📚Learning ConstraintLayout — 🚀Live Templates for Rescue 🚒 Save time and improve productivity by using Live Templates for ConstraintLayout
April 27, 2018
7 years experience. 💻 Creator of various Open Source libraries on Android . 📝 Author of two technical books and 100+ articles on Android. 🎤 A passionate Public Speaker giving talks all over the world.
Источник
How to stop activity in Android ?
I have created an activity which includes media player in it.When I start activity, the music begins to play.But when the song is complete and when i click on back button on the emulator, it displays an error of ( IllegellStateException ).
Here is my code.
Thanks in advanced.
6 Answers 6
use finish(); in Activity class to stop Activity and return
I think the problem is here:
For more info read here.
Here’s an implementation of onStop() that saves the contents of a draft note to persistent storage:
Although the onPause() method is called before onStop() , you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.
The above code snippet inside if ((keyCode == KeyEvent.KEYCODE_BACK)) seems to be the problem. You should check whether the player is playing or not. If it is playing then only pause should be called.
You get (IllegelStateException) on the onPause().
To resolve this problem you need to put,
because when you check mp!=null that time MediaPlayer already release but not null. so, if condition is correct and goto mp.pause() but mp already release that’s why you get error.
Also you need to change name of MediaPlayer instance in onCompletion().
because it is used mp of onCompletion() for stop() and release(). so, change mp to other(like: mp1).
Источник
Android destroying activities, killing processes
Hi I’m wondering how Android is managing memory and I can’t find precise answer anywhere. Let’s assume I have an application with 5 activities on current activity stack (4 are stopped and 1 is resumed), there is no service connected. I press HOME button so that all of my activities are stopped. I start some other memory consuming application and overall device memory is starting to be low. And the question is
. What will happen to my application?
- Can system destroy only one or some of my activities to recover memory?
- Will system kill the whole process of my application? Will all activities be nicely destroyed?
- What will happen when I get back to my application when it was totally killed? Will it start from beggining (like the first start) or will it try to recover activities to previeous state / if yes — is it only the one on the top of the stack or all of them?
UPDATE:
Before asking this question I’ve seen Activity lifecycle a few times but it doesn’t have answers to my questions. I made some tests and I have some answers. «Stop process» in DDMS was a clue for testing.
I haven’t tested answer for question 1, but as guide says:
If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process.
It seems that one or more of the activities can be destroyed gently(with onDestroy method) without killing the process. You will simply get (onCreate + bundle) when getting back to them.
Question 2 answer:
YES. Generally system kills the whole process this means all data including activities and static fields are destroyed. This is NOT done nicely — you won’t get onDestroy or finialize() for any of your paused/stopped activities. This is why saveInstanceState() is called just before onPause method. onPause is basically the last method where you should save something because after this method you could never see onStop or onDestroy. System can just kill the process destroying all of your objects whatever they hold and whatever they are doing.
Question 3 answer:
What will happen when you get back to a killed application?
- Prior to Android 2.2 — application will start from the beggining, with launcher activity.
- Starting from 2.2 — system will restore the previous application state. What does it mean? It means that last visible activity will be recreated (onCreate + bundle). What will happen with activity stack? Stack is fine but all activities on it are dead. Each of them will be recreated (onCreate + bundle) when you get back to it with back button. There is one more thing about that:
Normally, the system clears a task (removes all activities from the stack above the root activity) in certain situations when the user re-selects that task from the home screen. Typically, this is done if the user hasn’t visited the task for a certain amount of time, such as 30 minutes.
Conclusion?
- Don’t think that handling activity rotation problems can be solved by android:configChanges=»orientation». When you do that you will get many other problems that you are not even aware of.
- Test your application with DDMS — Stop process button. See This
- Be careful when using static variables. Don’t think that when you initialized them in activity 1 — you will have them initialized in activity 2. The only safe place to initialize global statics would be Application class.
- Remember that you may never see onStop or onDestroy. Close files/databases, stop downloaders in onPause. When you want app to do something in BG — use foreground Service.
That would be it . Hope I helped with my essey 🙂
2 Answers 2
First please have a look at this:
onPause() Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
onStop() Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
So, when you press «HOME» button on your device, your current foreground activity is put onto onPause() then onStop() , the other 4 should remain onStop()
According to Google’s Documents:
- If an activity in the foreground of the screen (at the top of the stack), it is active or running.
- If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
- If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.
- If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
And, for the process lifecycle:
Process Lifecycle 3. A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.
It is confirmed that the system can destroy non-acitve activities and recycle memories when you launched some memory consuming applications. And you can implement like: isFinishing() in your activity and then using «kill» button in DDMS to detect which of your activities is being dropped by system. But I guess the system will destroy the oldest one first. However it is no point to keep other activities when the «Launch Activity» has been recycled.
UPDATE
Here’s some opinions I found from here:
When an activity is not visible, but still in memory, we say it’s in a stopped state. Stopped activity could be brought back to the front to become a Running activity again. Or, it could be destroyed and removed from memory.
The system keeps activities around in a stopped state because it is likely that the user will still want to get back to those activities some time soon, and restarting a stopped activity is far cheaper than starting an activity from scratch. That is because we already have all the objects loaded in memory and simply have to bring it all up to the foreground.
Stopped activities can be removed from memory at any point.
Источник
How to stop an activity in android using intent?
I think this is a basic question. Is there any option to stop an activity by using intent.
This is my code. I would like to stop this activity (That means, i want to drop this call) if the user is busy or something. What can I do for that? I tried this:
But of no use. Does anybody have a suggestion?
3 Answers 3
I had this problem a few days ago, and I’m happy to tell you I’ve found a way around this.
First of all, to the activity you want to stop add this in the AndroidManifest.xml :
I’m going to use a CheckBox example. When it’s checked the activity is started and when unchecked will kill the activity.
Example Activity A is calling Activity B and then killing it using an intent.
Code to be put in A:
Code to be put into B:
Explanation : What this basically does is, when the checkbox is checked it calls the activity and passes a boolean value, if it’s true the activity is kept alive and is brought to the foreground. Now, if you don’t pass the flag singleTop then many instances of this activity will be created. singleTop makes sure only the same instance is called. Now, when the checkbox is unchecked a new value for keep is passed which is verified in B. If unchecked, the Activity A will be passing false, and hence B terminates itself from within the onNewIntent() function.
P.S — You can close Activity B from another Activity too. Just use If the other activity is C:
Источник
Android, Finish all activities
I need to finish all the activities running in an Android application when an exit button is clicked. How can I do that?
- An option menu on screen with an EXIT option.
- When I click the Exit menu, the application should close.
7 Answers 7
How to make a button for the user to immediately finish all Activities
When the user wishes to exit all open activities, have them press a button which loads the first Activity (passing in an intent to clear out all the other activities) that runs when your app starts. Then inside the one remaining activity (LoginActivity), place some code in onCreate to have it choose to self destruct.
Details:
Create a button and call it «exit», make a buttonlistener for that button, and put the following code in there. What it does is load the activity, makes it the only remaining activity by clearing all activities underneath it.
The above code clears all the activities under LoginActivity. The LoginActivity must be the first activity your app runs. So now we are left with only LoginActivity activated. Now we have to get LoginActivity to check the putExtra parameter, and if it has the value «EXIT» then destroy itself as well.
Put the following code inside the LoginActivity’s onCreate and onResume, to check the «EXIT» parameter and finish when it is seen:
Why is this so hard, why isn’t there just an exitAllActivites() function?
Android OS Developers make this hard because they don’t want you to give the user an Exit button. They want the user never to care if their App is running or not. If they want it, they run it, if they don’t want it, they stop using it. There are benefits to this model, because then an app can be destroyed to make room for a phone call and heavy map-usage, and then they re-run your app, they pick up right where they left off, rather than having to restart from scratch.
So if you use this code, try to cooperate with the Android Developers vision for Android and make it so that the App can be destroyed/recreated at any point, and the user always picks up where they left off. Requiring a user to ‘exit’ is a hassle.
use StartActivityForResult function for starting a new Activity and when user presses EXIT button, send a unique value as a resultcode . Check for this resultcode in onActivityForResult func and if you find the same unique code then finish the activity.
I don’t understand the people who say that this should not be done. Closing an activity can be done quite easily using the built in method to do so.
There is no place in the official documentation that says this should not be done.
For those who think it should not be done for any purpose, maybe you can’t think of a reason to do so. There are plenty of legitimate reasons to do this. And since it is a method built in to the Android code.. Google has also decided that you might need to depending on your use. Not all of us only create consumer applications for Android.
So to accomplish this task..shutting down all of the activities in your stack
I created a kiosk app that was run as the default launcher. So I needed a way to exit the app to get to settings or other apps on the device. So in an admin Activity, I placed a pin number pad.. after the user inputs the correct pin, the app needed to exit to the original launcher. I used above code.
You should not implement an Exit button in an Android application.
How to close all activities in Android:
Why are the Android OS devs telling me not to create an Exit button?
If you give developers a hammer, they will use it, and everything becomes a nail, so don’t give them a hammer. This is why there is no one-liner to exit all activities.
Why is an Exit button so bad?
You may be frustrated wondering why killing all activities in Android is so difficult. It’s hard to do because you’ve got to bite the bullet and understand how you created the stack, and what it looks like. In what order should the Activities be destroyed? What if the user gets a phone call and needs to nuke your app ASAP? You NEED to have a plan for unwinding. It can’t rely on the Activity Manager to babysit your app. If you want to kill your app, the OS devs are twisting your arm to create a unwinding plan because they don’t want your application to have any errors when the Activity Manager nukes it.
This self destruct mechanism I go on to describe cooperates with the Activity Manager and causes a cascade effect that causes all activities to finish themselves no matter how they are organized.
To add this cascading self destruct to your app, do these three things:
If you are newbie to android and have never done this before, I suggest you create a brand new bare bones android project to test this out and get a feel for how it behaves. Only when you get the «aha» moment of understanding why this works, then can you extract the usefulness of the code below to delight the user.
Put this override method inside each one of your activities:
If you have more than 3 activities, consider having each activity extending a «MyAppActivity» with the above code in there. If you catch yourself copy/pasting the above method into 15 different activities, slap yourself once, and take a class on good Object Oriented Programming. Then read this.
Whenever you have the user start a new activity, you must do it exactly this way:
If you don’t use startActivityForResult , then the self destruct unravelling won’t work.
When you want to exit your application, initiate self destruct like this:
Then the activity stack unwinding plan cascades through the entire app.
Источник