Back Button is not Resulting in onDestroy for Android 12 - android

I have just started insuring my apps work with Android 12. What I notice is that for (I believe) all of them when the back button is pressed, then onPause() is called, but not onDestroy(). This means the app is still running.
Previously, onDestroy() was called after onPause() when the back button was pressed.
It is a definite problem for ones running a background service that has (actually, must have) a notification. Stopping the service is typically done in onDestroy() and certainly not in onPause(). Since onDestroy() is not called, the service continues running and the notification remains up. If you select the notification, it brings up the [running] app again. There is no way to stop the service and hence the notification, except by killing the process via the overview (left) button.
I also notice that if an app with a service crashes, then the notification stays up. This is surely not desired behavior.
You can, and apparently have to, kill the process with the overiew (left) soft button).
I can get around this by implementing onBackPressed:
#Override
public void onBackPressed() {
// This seems to be necessary with Android 12
// Otherwise onDestroy is not called
Log.d(TAG, this.getClass().getSimpleName() + ": onBackPressed");
finish();
super.onBackPressed();
}
but that seems like a kludge.
For other apps maybe it doesn't matter they are still running or not. However, it is unexpected behavior.
Added later: This is apparently intentional and is a change from previous behavior. It is mentioned in this article (curtesy of #ianhanniballake):
https://developer.android.com/about/versions/12/behavior-changes-all#back-press
I have several apps, and I have verified it is happening with all of them on Android 12. It is causing problems with those that have services.
The implied question for this issue is what to do about it. I personally am implementing onBackPressed for those and leaving the others be.

I am not sure if this should be an answer or a comment, so, given the size of the text, I decided to go with answer.
The solution I came up with was forcing onDestroy() to be called, by finishing the activity from within onStop() in some circumstances.
In my case, I use onDestroy() to persist a few things. I know there are better ways of doing this, but that is how the code was, and this quick workaround fixed the issue, at least temporarily:
#Override
protected void onStop() {
// Try to differentiate a home button press from the screen being turned off
final PowerManager powerManager = (PowerManager)getSystemService(POWER_SERVICE);
if (powerManager != null && powerManager.isInteractive()) {
if (webViewHost != null && !webViewHost.isPaused()) {
// My old/existing logic (for Android < 12)
finish();
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
// New workaround for Android 12 onwards
finish();
}
}
super.onStop();
}
This is the project's repo, already pointing at the line where the workaround has been created.

As per the new changes in Android 12, back button on root/home activity is now minimize the app instead of close entirely. Hence it calls only onPause() and onStop() functions not onDestroy(). So I called finish() function from inside onBackPressed() function like this.
override fun onBackPressed() {
super.onBackPressed()
finish()
}
This could be a simple and quick workaround to match the behaviour with below Android 12. However the good practice is to optimise the app as per the Android 12 guidelines mentioned here

Related

Managing background download : Android

I'm designing a news app where I need to download fresh articles and their detailed stories whenever user opens my app. I'm doing all of this a background thread. My prime focus was that the background thread should stop as soon as user exits the app so as to prevent user for incurring extra download charges.
To achieve this, I initiate background download in my splash screen and I keep on checking for flag variable that lets the background process know if the app is still running.
Now my question is: I'm very clear about initialization of this flag variable. I've initialized it in onCreate() of Application subclass since it is the point where application starts. But I've no idea where to clear it. I tried doing it in onDestroy() of my MainActivity. However, I found that onDestroy() is often called on transition between one activity to another if system needs to free memory. So, doing so there would stop my background thread even when I'm switching across screens and not actually closing the app. How should I deal with this scenario ? Is there a smarter way of handling this ?
I don't think you have to do that : either the user is pressing the "Home" button (which most people do) and then it's common for apps to keep running in background, and as so to still be easily accessible to the user in the state they left it. Either you provide a "close app" button which really kills the app, which will also kill every kind of thread created by the app and you don't have to worry.
If you really want, you could capture the "Home" clicks, and use those to kill the app before returning to home, which is a nice thing to do if your app has 0 initialization time.
But I've no idea where to clear it. I tried doing it in onDestroy() of my MainActivity.
In order to know if the activity is destroyed because the user finished it (with Back) or Android will re-create it, you could use isFinishing();
Something like:
protected void onDestroy() {
super.onDestroy();
if(isFinishing()) {
// stop the news feed download
}
}
Or better, stop the feed download in finish():
public void finish() {
// stop the news feed download
super.finish();
}
To go back to what you said above with:
I'm very clear about initialization of this flag variable. I've initialized it in onCreate() of Application subclass since it is the point where application starts.
Even if the activity is finished, the application is very probable to still live. The Android OS will decide when to kill it. So you will initialize the download once the app starts, then you will stop it on onDestroy() or on finish() within Activity, depending on your desire, but if the application doesn't stop (most probable) and you're re-entering again in the news activity you should be starting the news download.
I would rather initiate the download in the background in onCreate(Bundle savedInstance), but when savedInstance is null (so I know this is the first create of this activity) and stop it (if hasn't stopped already by itself) in finish();
Hope it helps!
To begin with for downloading datas from webservice (json or xml) you should use AsyncTask (easy to use)
so what i mean was, to clear your flag with ondestroy(), for when the application is exited, and maybe you can catch when the home button is pressed
Override the below method in your Activity,
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
And now handle the key event like this,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_HOME)
{
//do something
}
if(keyCode==KeyEvent.KEYCODE_BACK)
{
//do something
finish();
}
return false;
}

Android app doesn't call "onDestroy()" when killed (ICS)

I'm developing an android app using bluetooth communication (using a propetary protocol) and I need to catch the moment when the app is killed.
I wanted to use the "onDestroy()" method but it isn't called every time the app is killed.
I noticed that it is called when I press the back button and, only sometimes, when I kill the app from the task manager.
The question is: How can I catch the moment before the app is killed?
Here is the code I tried to use:
#Override
public void onDestroy() {
sendMessage(msg);
Log.d("SampleApp", "destroy");
super.onDestroy();
}
#Override
public void finish(){
sendMessage(msg);
Log.d("SampleApp", "finish");
super.finish();
}
Unfortunately finish() is never called and onDestroy isn't called every time I close the app from the task manager.
How can I handle this?
As stated in the documentation here, there is no guarantee that onDestroy() will ever be called. Instead, use onPause() to do the things you want to do whenever the app moves into the background, and leave only that code in onDestroy() that you want run when your app is killed.
EDIT:
From your comments, it seems that you want to run some code whenever your app goes into the background, but not if it went into the background because you launched an intent. AFAIK, there is no method in Android that handles this by default, but you can use something like this:
Have a boolean like:
boolean usedIntent = false;
Now before using an intent, set the boolean to true. Now in your onPause(), move the code for the intent case into an if block like this one:
if(usedIntent)
{
//Your code
}
Finally, in your onResume(), set the boolean to false again so that it can deal with your app being moved into the background by a non intent means properly.
Your application will not receive any additional callbacks if the process it terminated by external means (i.e. killed for memory reasons or the user Force Stops the application). You will have to make do with the callbacks you received when you app went into the background for your application cleanup.
finish() is only called by the system when the user presses the BACK button from your Activity, although it is often called directly by applications to leave an Activity and return to the previous one. This is not technically a lifecycle callback.
onDestroy() only gets called on an Activity as a result of a call to finish(), so mainly only when the user hits the BACK button. When the user hits the HOME button, the foreground Activity only goes through onPause() and onStop().
This means that Android doesn't provide much feedback to an Activity to differentiate a user going Home versus moving to another Activity (from your app or any other); the Activity itself simply knows it's no longer in the foreground. An Android application is more a loose collection of Activities than it is a tightly integrated singular concept (like you may be used to on other platforms) so there are no real system callbacks to know when your application as a whole has been brought forward or moved backward.
Ultimately, I would urge you to reconsider your application architecture if it relies on the knowledge of whether ANY Activity in your application is in the foreground, but depending on your needs, there may be other ways more friendly to the framework to accomplish this. One option is to implement a bound Service inside of your application that every Activity binds to while active (i.e. between onStart() and onStop()). What this provides you is the ability to leverage the fact that a bound Service only lives as long as clients are bound to it, so you can monitor the onCreate() and onDestroy() methods of the Service to know when the current foreground task is not part of your application.
You might also find this article written by Dianne Hackborn to be interesting covering in more detail the Android architecture and how Google thinks it ought to be used.
I just resolved a similar kind of issue.
Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.
Inside your Manifest file, keep flag stopWithTask as true for Service. Like:
<service
android:name="com.myapp.MyService"
android:stopWithTask="true" />
But as you say you want to unregister listeners and stop notification etc, I would suggest this approach:
Inside your Manifest file, keep flag stopWithTask as false for Service. Like:
<service
android:name="com.myapp.MyService"
android:stopWithTask="false" />
Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).
public void onTaskRemoved(Intent rootIntent) {
//unregister listeners
//do any other cleanup if required
//stop service
stopSelf();
}
Refer this question for more details, which contains other part of code, too.
Start service like below
startService(new Intent(this, MyService.class));
Hope this helps.

What does "visibility" refer to in the Activity Lifecycle? onPause vs onStop?

The Activity Lifecycle is giving me headaches.
The documentation at http://developer.android.com/reference/android/app/Activity.html is so darn ambiguous when it describes the concept of visibility, that I can't figure out when onStop() is called vs onPause().
Compare the following two statements from the documentation:
(taken from right beneath the lifecycle diagram)
The onStart() and onStop() methods can be called multiple times, as
the activity becomes visible and hidden to the user.
vs
(further down in the blue table with the "killable" columns)
onPause() Called when the system is about to start resuming a previous activity.
What I'd understand from the first quote, is that onStop() is called on activity A when A is "hidden". "Hidden" I'd guess is referring to when another activity B has been resumed and is completely covering actvity A.
But the second quote then states that onPause() is called when another activity is about to start resuming. Wouldn't that completely hide activity A as well? Both cases seem to imply that that activity A becomes "hidden", no? According to my likely faulty interpretation, onPause() and onStop() are called in identical situations.
The documentation also seems to differ between being hidden (onStop() gets called) and being partial visibility (onPause() gets called). But when is an activity still partially visible? Do they mean literally? Or can an activity still be deemed "partially visible" when it has started up a new activity (activity calls startActivityForResult and starts a date picker activity) that covers the entire screen? Surely the activity is not going get onStop invoked? Its supposed to receive a result any moment!
So I'm trying to figure out what I'm not getting.
I understand that a call to onPause is guaranteed. That would be when activity A loses focus (device enters sleep mode, screenlock, etc), a different activity B takes the foreground (where activity B may or may not have been initiated by activity A).
But at which point is the onStop() invoked on activity A?
Is it matter of how many activities have been piled ontop of activity A on the activity stack? Are there two different definitions of "visiblity" at play?
Sorry about the wall of text, but I'm really frustrated :S
So the question stands: Precisely in which situations is an activity deemed "hidden" such that onStop() is called on it?
EDIT:
I inserted Toast notifications in each onX method, and discovered some additional weirdness:
Pressing the Home button will always call onStop(). But starting up the application won't call onRestart(). Instead it calls onCreate(). This seems strange to me, but ok...
When the "USB Mass Storage" activity is started on top of the main activity, onStop() is called. And when exiting the usb storage activity, returning to the main activity, onRestart() is called, instead of onCreate().
When the device goes into Sleep mode and is waken up, the activity only goes through the onPause() and onResume() cycle.
The last point was expected (although I can't get it to fit in the lifecycle diagram). But whats up with 1. and 2. ?
In the first point, I was expecting a call to onRestart() when starting the activity again. Why did it deallocate the activity and call onCreate() instead?
And take a look at point nr 2:
According to the documentation: when "another activity comes in front of the activity", onPaused() should be called. Isn't that what happened when the USB Storage activity came up? It didn't call onPause(), it went through the onStop() - OnRestart() cycle! Obviously, the documentation doesn't consider that a case where "another activity comes in front of the activity". So what really happened?
Ok, I think I've got this now.
1.
The key to the first point was this link:
http://code.google.com/p/android/issues/detail?id=2373
Its a bug. Theres some code in the link that has completely solved the problem with new root activity instances being created, instead of just restarting the last active activity (before the home button was pressed).
I put the code at the top of the onCreate method, just below the super.onCreate call:
if (!isTaskRoot()) {
final Intent intent = getIntent();
final String intentAction = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) &&
intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
finish(); return;
}
}
Note that I added the return statement after finish so the rest of the onCreate method doesn't run in the case that the bug is detected.
2.& 3.
The key to the second and third points was these two links:
http://answers.oreilly.com/topic/2692-android-programming-understanding-the-activity-life-cycle/
How to make Activity, not covering full screen
It turns out that "visibility" really is literally! So when the documentation says "another activity comes in front of the activity", the activity behind the bumped activity is still partially visible. This means that the Android Activity manager must check whether the bumped Activity is a full-screen activity or not: If it is, onStop() is called on the previous activity. If not, then onPaused() is called on the previous activity instead.
This trivially explains why the USB Storage manager caused the onStop() to be called.
This also means that when device goes into sleep mode, the Activity Manager considers it a non-fullscreen activity, even though technically the main activity is completely hidden behind it.
(See the second link on how to make non-fullscreen activities )
Interestingly, the pull-down window (with the notifications) doesn't call onPause() (nor does it call onStop()), even though it would have made sense as a non-fullscreen activity. This must be some kind of exception that I'll be investigating on my own.
This also means that the onStop()-onRestart() cycle is probably more common than the onPause()-onResume() cycle (although both must still be accounted for), since activities probably more often than not are full-screen activities (personally, I thought the documentation indicated the opposite: that onPause-onResume was more commmon, but maybe thats just me).
Additionally, this must mean that when the main activity starts a new fullscreen activity for a result, the main activity will be first stopped and later restarted when the result-retrieveing activity is done.
So the only question now is how to best deal with a paused activity (meaning, it is covered by a non-fullscreen activity) that gets deallocated (although this case would be rare). What challenges may there be?
But thats outside the scope of this question.
Finally tracked this down: you can detect the status bar pulldown using onWindowFocusChanged()
how to use OnWindowFocusChanged method

Android -- How to properly handle onPause/onResume methods?

I have an app that starts playing sounds and begins/resumes gameplay in the onResume() method, but what I'm noticing is that if my app was the last run application when I put the phone into standby (screen off), and I just press the Menu button to check the time, then the phone starts playing the game and sounds in the background (the app isn't actually visible, only the screen with the date/time is, yet onResume must have been called in my app). What am I to do here? Is there a way to discern what is reactivating the app, and then add a conditional statement that only starts the game when the app is actually visible?
Here is a snippet from my onResume:
#Override
protected void onResume()
{
mySaveGame = Utilities.loadSavegame(this);
//check the savegame
if(mySaveGame!=null)
{
//start game using savegame values
this.startFromSavedGame(mySaveGame.getIsLevelComplete());
}
else
{
//run the 1st-run components
this.startFirstRun();
}
super.onResume();
}
The only thing I can think of doing to prevent the game from starting whenever the screen gets turned on (even when the app isn't visible) is to put this.finish() as the last line in onPause()... but that forces you to restart the app every time you want to go back to it because the precess itself was killed (which is fine because my onPause saves persistent data, but it's not an elegant solution).
Please help.
Have you considered switching to onStart() and onStop(), rather than onResume() and onPause()?
I was having the same problem (I had my music player resume/pause at onResume()/onPause()) and the best solution I found is to pause and resume my activity when it is on the foreground which you can get with public void onWindowFocusChanged (boolean hasFocus) callback.
Edit: This in an old and slightly incorrect answer - correct response is described in the Android Developers Blog: making android games that play nice

Killing android application on pause

I have an application which I would like to be fully disabled/closed when it is paused (IE. When the user presses the Home, End (call) and Back button I would like the application to be closed, instead of being saved in the history stack).
How do I do this....?
Thanks.
Implement onPause() in your activity and call finish() on your activity. Bear in mind, though, that this will occur on every pause, including dialogs, incoming calls, users activating a Notification. You might want to consider doing finish() in onStop(), which would at least solve the dialog problem.
Also, bear in mind that users will may get confused when using your app, thinking it has crashed since it is gone when they try to get back to it.
you can easily do that by setting true the "noHistory" attribute in to your activity element, in the manifest
http://developer.android.com/guide/topics/manifest/activity-element.html#nohist
You know how you have an OnCreate() method in your activity which performs actions when you start. You need to add something like:
#Override
protected void onPause(){
finish();
super.onPause();
}
in your activity to add actions before it starts
in this case the
finish();
command is what you want to execute before your activity pauses.

Categories

Resources