Can Android 'kill' an Activity without killing the application? - android-activity

As we know, the default flow in Android for such scenario is calling the activity's respective onSaveInstanceState, onStop, onDestroy methods before releasing the reference to the Activity object.
However it appears I have a case when my application is on the background, the activity gets killed without those methods being called, but my application itself does not get destroyed.
However I am unable to force-reproduce this. Whenever I use applications on the foreground that require a lot of resources, the whole process gets killed, not just the activity.
Which kind of makes me wonder, because I believe the 'app killing' on low resources is essentially just the old signal way, does the Android system actually 'kill' (release) an activity instantly without calling these methods? Or am I chasing ghosts?

Android app out of memory issues - tried everything and still at a loss
This is not how things work. The only memory management that impacts activity lifecycle is the global memory across all processes, as Android decides that it is running low on memory and so need to kill background processes to get some back
Now the explanation in the official documents is more clear
The system never kills an activity directly to free up memory. Instead, it kills the process in which the activity runs, destroying not only the activity but everything else running in the process, as well. To learn how to preserve and restore your activity's UI state when system-initiated process death occurs, see Saving and restoring activity state.

It is possible Android OS kills only some of your activities even if your app is in foreground. For instance if you have two activities A and B, and when A calls startActivity / startActivityForResult to start activity B then Android may deceide to destroy activity A's instance because it is taking up too much memory space.
You can force killing activities which don't run in the foreground by checking Don't keep activities in developer options menu.

Does the Android system actually 'kill' (release) an activity
instantly without calling these methods?
Yes it does. Here's what the docs say in regards to onStop():
Note that this method may never be called, in low memory situations
where the system does not have enough memory to keep your activity's
process running after its onPause() method is called.
and in regards to onDestroy():
There are situations where the system will simply kill the activity's hosting
process without calling this method (or any others) in it, so it
should not be used to do things that are intended to remain around
after the process goes away.
Do not count on this method being called as a place for
saving data! For example, if an activity is editing data in a content
provider, those edits should be committed in either onPause() or
onSaveInstanceState(Bundle), not here.
"However I am unable to force-reproduce this." - you could reproduce this situation by sending your application in background and then using the DDMS to kill the process manually.

Related

Ensuring Completion of Operations During app Termination in Flutter

Let's say we have a Flutter app where we want to save some persistent data using shared preferences.
(We don't want to save the data persistently every time the user changes it because the UI depends directly on the data, and in order to save it we need to use await async, and that lags the UI), so we use WidgetsBindingObserver to detect when the app goes to the background in order to use that event as an efficient catch-all opportunity to save the data.
So, we have some code like this in the root page of our app:
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (state == AppLifecycleState.paused) {
// went to Background
myPersistentData.instance.write(); // <-------------- this is an async operation
}
if (state == AppLifecycleState.resumed) {
// came back to Foreground
}
}
This seems to work, but I'm concerned that the lifecycle could progress beyond "paused" (pause>stop>finish) so quickly that this "trailing" operation doesn't have time to finish... and thus the data would not be saved.
Is this a legitimate concern?
I would say as much as possible try to avoid calling async operations in the dispose or lifecycle methods of widgets, while you may be concerned that it may/may not complete i would recommend like the dart docs states here: https://api.dart.dev/stable/2.14.1/dart-async/unawaited.html, "Not all futures need to be awaited.", "You should use unawaited to convey the intention of deliberately not waiting for the future.". But generally, i'd avoid calling async functions in these methods.
It should be a concern for sure because the time available for an app to run in background is limited and not defined.
Based on the memory resources needed for the most important app, which is the one in foreground, the system may kill your app faster or at a later point in time. In either scenarios you don't have much time to complete the tasks, this event should be used to do fast clean up like killing tasks that are started, clearing token or maybe saving a token or a session info.
There are also scenarios which will cause problems for this approach, like the pone runs out of battery or the OS crashes, in this case you don't have any notification of app going into bg. Or the user force quits your app.
In your case, I would say you have another concern, saving data in shared preferences shouldn't affect your UI only if:
you save it synchronously which is a no no
you save a huge chunk of data in shared prefs, in this case you should use a database.
and a less likely scenario, you have a race condition while you save in shared prefs which are not thread safe.
I would suggest to rethink a bit your approach on this matter, maybe you can spawn async operations that save the data in certain points of the app (user exits a screen or whatever) while also keeping a copy in memory. Maybe is better to save it using a database. In the end is your decision, but my advice would be, don't rely on the app running in bg time.
For something like this, there is no way you can continue a service purely in Flutter. That's bummer of course but there are work-arounds you can use to do that.
If you want to approach this problem in a more convenient but difficult way, you can always create a service in native (Kotlin/Java in case of Android or Swift/Objective-C for iOS) and call your native functions using MethodChannels. Your native service can be alive even if you kill your app. Think of Push-notifications service where even if you kill your app, Push service is always alive to serve your notification.

Flutter: Will callback supplied to Timer get fired when application goes to background

In Flutter if I create a Timer, will the supplied callback get executed if the application is in background?
I think documentation is not clear on this or I might have missed it (please supply a link if you find it anywhere).
I just tried doing this with a timer set up to 10 seconds and it works fine.
I assume that is approach is not very reliable and other methods* should be used instead. I think if the app is paused/terminated by operating system to preserve battery or due to low memory, nothing will be executed. But for me this situation could be an ok approach.
* I know there are isolates so I guess I could spawn the timer inside one of these. Downside is that the isolate must be regular function (or static method) so no access to application data in my scenario. Then there are different scheduling packages etc but I'm trying to avoid these for now. I know about background tasks but I'm really looking for an answer on code execution using timers.

Android Async Task does not update UI when application is in background

The application I am working on downloads and parses a large xml file to populate UI elements, namely search and a spinner. This is done through an async task. If the user decides to switch out of the application during this, the information is downloaded correctly, but then when the application is resumed, the UI will not be updated.
Is this because the changes can't be made while the application is not active? What is the best way to go about checking whether the UI was not updated on resume? Or instead should I be doing something with the Async task, checking whether the UI thread is available? I'm having a hard time debugging this because it involves leaving the application which ends the debugger.
You can achieve this scenario through the broadcast receive.
Follow the step:
Solution 1:
Step 1;
Register the broadcast receiver before executing the Asyntask.
Step 2:
send Broadcast in onPostExecute method of Asyntask.
step 3:
And then you can able receive your broadcast message in your activity.
and do whatever you want.
Solution 2:
Otherwise you can use Interface Call back for this Scenario.
Hope It will help you.
It should'nt. App being in background means View objects may or may not be there. Actually the entire process may be stopped or just deleted by android.
Use a Service to truly do processing in background. When processing is complete but UI is not there, post a notification to let user know, OR, save the results and provide it to UI the next time it binds to your service and ask for same thing (a.k.a caching).
The application in background may not be live. The O.S may destroy it in case of memory constrains.
The trick is to try an alternate logic.
When the application moves from background to foreground onresume() is called ,you could try saving the data to db and update the content on the resume call.
FYI.onPause() and OnResume() is called when the application goes background and foreground respectively.

Why use the Bundle when you can just use the Application?

I'm reading this article on how to : correctly retain variable state in Android and I'm reminded that I've never gotten a good answer (and can't find one here) for why it's better to tussle with the Bundle (which isn't a HUGE hassle, but definitely has its limitations) rather than just always have an Application overridden in your App, and just store all your persistent data members there. Is there some leakage risk? Is there a way that the memory can be released unexpectedly? I'm just not clear on this... it SEEMS like it's a totally reliable "attic" to all the Activities, and is the perfect place to store anything that you're worried might be reset when the user turns the device or suspends the app.
Am I wrong on this? Would love to get some clarity on what the true life cycle of the memory is in the Application.
Based on the answers below, let me extend my question.
Suppose I have an app that behaves differently based on an XML file that it loads at startup.
Specifically, the app is a user-info gathering app, and depending on the XML settings it will follow an open ended variety of paths (collecting info A, but not J, and offering Survey P, followed by an optional PhotoTaking opportunity etc.)
Ideally I don't have to store the details of this behavior path in a Bundle (god forbid) or a database (also ugly, but less so). I would load the XML, process it, and have the Application hold onto that structure, so I can refer to it for what to do next and how. If the app is paused and the Application is released, it's not *THAT big a hassle to check for null in my CustomFlow object (that is generated as per the XML) and re-instantiate it. It doesn't sound like this would happen all that often, anyway. Would this be a good example of where Application is the *best tool?
The question as to which method is better largely depends upon what information you are storing and need access to and who (which components, packages, etc.) needs access to that information. Additionally, settings like launchMode and configChanges which alter the lifecycle can help you to determine which method is best for you.
First, let me note, that I am a huge advocate for extending the Application object and often extend the Application class, but take everything stated here in its context as it is important to understand that there are circumstances where it simply is not beneficial.
On the Lifecycle of an Application: Chubbard mostly correctly stated that the Application has the same life as a Singleton component. While they are very close, there are some minute differences. The Application itself is TREATED as a Singleton by the OS and is alive for as long as ANY component is alive, including an AppWidget (which may exist in another app) or ContentResolver.
All of your components ultimately access the same object even if they are in multiple Tasks or Processes. However, this is not guaranteed to remain this way forever (as the Application is not ACTUALLY a Singleton), and is only guaranteed in the Google Android, rather than the manufacturer overridden releases. This means that certain things should be handled with care within the Application Object.
Your Application object will not die unless all of your components are killed as well. However, Android has the option to kill any number of components. What this means is that you are never guaranteed to have an Application object, but if any of your components are alive, there IS an Application to associate it to.
Another nice thing about Application is that it is not extricably bound to the components that are running. Your components are bound to it, though, making it extremely useful.
Things to Avoid in Application Object:
As per ususal, avoid static Contexts. In fact, often, you shouldn't store a Context in here at all, because the Application is a Context itself.
Most methods in here should be static, because you are not guaranteed to get the same Application object, even though its extremely likely.
If you override Application, the type of you data and methods store here will help you further determine whether you need to make a Singleton component or not.
Drawables and its derivatives are the most likely to "leak" if not taken care of, so it is also recommended that you avoid references to Drawables here as well.
Runtime State of any single component. This is because, again, you are not guaranteed to get back the same Application object. Additionally, none of the lifecycle events that occur in an Activity are available here.
Things to store in the Application (over Bundle)
The Application is an awesome place to store data and methods that must be shared between components, especially if you have multiple entry points (multiple components that can be started and run aside from a launch activity). In all of my Applications, for instance, I place my DEBUG tags and Log code.
If you have a ContentProvider or BroadcastReceiver, this makes Application even more ideal because these have small lifecycles that are not "renewable" like the Activity or AppWidgetProvider and can now access those data or methods.
Preferences are used to determine, typically, run options over multiple runs, so this can be a great place to handle your SharedPreferences, for instance, with one access rather than one per component. In fact, anything that "persists" across multiple runs is great to access here.
Finally, one major overlooked advantage is that you can store and organize your Constants here without having to load another class or object, because your Application is always running if one of your components is. This is especially useful for Intent Actions and Exception Messages and other similar types of constants.
Things to store in Bundle rather than Application
Run-time state that is dependent upon the presence or state of a single component or single component run. Additionally, anything that is dependant upon the display state, orientation, or similar Android Services is not preferrable here. This is because Application is never notified of these changes. Finally, anything that depends upon notification from that Android System should not be placed here, such as reaction to Lifecycle events.
And.... Elsewhere
In regard to other data that needs to be persisted, you always have databases, network servers, and the File System. Use them as you always would have.
As useful and overlooked as the Application is, a good understanding is important as it is not ideal. Hopefully, these clarifications will give you a little understanding as to why gurus encourage one way over the other. Understand that many developers have similar needs and most instruction is based on what techniques and knowledge a majority of the community has. Nothing that Google says applies to all programmer's needs and there is a reason that the Application was not declared Final.
Remember, there is a reason Android needs to be able to kill your components. And the primary reason is memory, not processing. By utilizing the Application as described above and developing the appropriate methods to persist the appropriate information, you can build stronger apps that are considerate to the System, the User, its sibling components AND other developers. Utilizing the information that everyone here has provided should give you some great guidance as to how and when to extend your Application.
Hope this helps,
FuzzicalLogic
I prefer to subclass Application and point my manifest to that. I think that's the sane way of coding android although the Android architects from Google think you should use Singletons (eek) to do that. Singletons have the same lifetime as Application so everything that applies to them applies to Application except much less dependency mess Singletons create. Essentially they don't even use bundles. I think using subclass Application has dramatically made programming in Android much faster with far less hassle.
Now for the downside. Your application can be shutdown should the phone need more memory or your Application goes into the background. That could mean the user answered the phone or checked their email. So for example, say you have an Activity that forces the user to login to get a token that other Activities will use to make server calls. That's something you might store in your service object (not android service just a class that sends network calls to your server) that you store in your subclass of Application. Well if your Application gets shutdown you'll loose that token, and when the user clicks the back button your user might return to an Activity that assumes you are already authenticated and boom your service class fails to work.
So what can you do? Continue to use Bundle awfulness? Well no you could easily store security tokens into the bundle (although there might be some security issues with that depending on how this works for your app), or you have to code your Activities to not assume a specific state the Application is in. I had to check for a loss of the token and redirect the user back to the login screen when that happens. But, depending on how much state your Application object holds this could be tricky. But keep in mind your Application can know when it's being shutdown and persist it's internal state to a bundle. That at least allows you to keep your Objects in memory for 99% of the time your Application, and only save/restore when it gets shutdown rather than constantly serializing and deserializing with boiler plate code whenever you move between Activities. Using Application lets you centralize how your program can be brought up and shutdown, and since it normally lives longer than any one activity it can reduce the need for the program to reconstitute the guts of your App as the user moves between Activities. That makes your code cleaner by keeping out details of the app from every Activity, reduces overhead if your Application is already built, shares common instances/code, and allows Activities to be reclaimed without loosing your program all together. All good programs need a centralized hub that is the core, and subclassing Application gives you that while allowing you to participate in the Android lifecycle.
My personal favorite is to use http://flexjson.sourceforge.net/ to serialize my Java objects into bundles as JSON if I need to send objects around or save them. Far easier than writing to sqlite DB when all you need to do is persist data. And nice when sending data between two Activities using objects instead of broken apart primitives.
Remember by centralizing your model in the Application you create a place to share code between multiple Activities so you can always delegate an Activities persistence to an object in the Application by hooking the onPause() as well allowing persistence to be centrally located.
The short answer is: use bundles as it makes saving your state out when you're backgrounded easier. Also, it's complicated.
The long answer:
My understanding is, as soon as you Activity's onPause method is called (and onSaveInstanceState which gives you a bundle into which you should store your Activity's data) your process can be terminated without further warning. Later, when the user comes back to your application, your activity is given an onCreate call with that original bundle from which to restore its state. This will happen to all your activitys in what was your original stack.
Being able to restore your state from the bundle (which Android will save for you as your process goes away) is how Android maintain's the myth of multi-tasking. If you don't dump your activity's state out to a bundle each time onSaveInstanceState is called, your app will look like it's been restarted when the user may have just switched out for a second. This can be especially troubling when the system is resource constrained as the system would need to kill off processes more often in order to keep the device running quickly
Why the Application can be Bad
The Application does not actually get a chance to save any of its data if the process is shut down. It does have an onDestroy method but the docs will tell you that this actually never gets called by the system on an actual device. This means that, in the constrained case I mentioned above, any incidental information about what's going on within an Activity (if you've saved it in the Application) will be lost if the process is ended.
Developer's often miss this case (and it can be really annoying for users) because they're either running on a dev phone which never gets hit with using many applications at the same time. We're also never using the app for a while, then switching to another application and, after a while, switching back again.

Application.DoEvents, when it's necessary and when it's not?

What is the necessity of using Application.DoEvents and when we should use it?
Application.DoEvents is usually used to make sure that events get handled periodicaly when you're performing some long-running operation on the UI thread.
A better solution is just not to do that. Perform long-running operations on separate threads, marshalling to the UI thread (either using Control.BeginInvoke/Invoke or with BackgroundWorker) when you need to update the UI.
Application.DoEvents introduces the possibility of re-entrancy, which can lead to very hard-to-understand bugs.
Windows maintains a queue to hold various events like click, resize, close, etc. While a control is responding to an event, all other events are held back in the queue. So if your application is taking unduly long to process a button-click, rest of the application would appear to freeze. Consequently it is possible that your application appears unresponsive while it is doing some heavy processing in response to an event. While you should ideally do heavy processing in an asynchronous manner to ensure that the UI doesn’t freeze, a quick and easy solution is to just call Application.DoEvents() periodically to allow pending events to be sent to your application.
For good windows application, end user doesn’t like when any form of application are freezing out while performing larger/heavyweight operation. User always wants application run smoothly and in responsive manner rather than freezing UI. But after googling i found that Application.DoEvents() is not a good practice to use in application more frequently so instead this events it’s better to use BackGround Worker Thread for performing long running task without freezing windows.
You can get better idea if you practically look it. Just copy following code and check application with and without putting Application.DoEvents().
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 1000
System.Threading.Thread.Sleep(100)
ListBox1.Items.Add(i.ToString())
Application.DoEvents()
Next
End Sub
Imho you should more less never use it, as you might end up with very unexpected behavior.
Just generated code is ok. Things like you are executing again the event handler you are currently in,because the user pressed a key twice etc etc.
If you want to refresh a control to display the current process you should explicitly call .Update on that control in instead of calling Application.DoEvents.