How to keep thread alive when use close application via swiping - android

I have a thread in my application's result page. And it's calculating the values every minute.
My problem is when user close application via swiping from recent applications, thread is stopping. But it must work.
I know i could create a service-intentservice for it, but that is my first application and i wrote lots of code about that tread, also that thread changes the values at result activity page. So that will be a togh operation for me.
I looked for it so much but i couldnt find an answer. Can you please give me an advise if i can keep that thread alive easily?
Thanks

Put your thread in a foreground Service
Normally, the entire VM is killed when a user swipes your app out of recents. But in recent versions of Android, foreground services are not killed. (Thanks to Steve M for bringing this change to my attention.) On older versions of Android, even foreground services were killed. This was considered a bug. Unfortunately, Google is notorious for inappropriately closing issues as "obsolete," so there's no way to know when it was actually fixed except by testing different devices. (Or even whether it was deliberately fixed at all, or accidentally fixed as a result of some other change.) I'm fairly certain that foreground services were killed in Android 4.4. They are not killed in Android 5.1, at least on my devices, including one that used to be running 4.4. But note the comments on that bug report about foreground services being killed in 5.1 and 6.0. It may be that this was never truly fixed, and it's still hit or miss.
Note that regardless of whether the VM is killed, the foreground service's onTaskRemoved(...) will always be called. (At least in my testing.)
You can test whether the VM is being killed by putting this code in an activity:
private static final long vmInitTime = System.currentTimeMillis();
// in onCreate(...)
((TextView) findViewById(R.id.timeView)).setText(new Date(vmInitTime).toString());
The displayed time will not change as long as the same VM is running. (Or to be more precise, as long as the same definition of your activity class exists. In practice, the ClassLoader has the same lifetime as the VM.)

You could run the thread in a foreground service, if it makes sense to be displaying a notification to the user. In this case the service will continue to you run on many devices, as long as the device is not force-stopping the app.

Related

Clarification on android app running in background

Im a bit confused on background limitations of apps, and I could use an explanation. So, starting from android 8 we have limitations on services and sending broadcasts. As for now, we can only make service run in background if it has the foreground notification, otherwise it will be killed. The app is considered to be in background if none of it's activities are visible, and my questions are: 1. For how long can the app-process itself live without foreground service? For instance, if I go to home screen, thereby putting app in background my app can still play sounds for hours, but I expected it will be killed by system in a couple of minutes. 2. Is foreground service somehow related to application lifecycle? For instance,maybe if I start the foreground service then my app won't get killed or less likely to be killed by the system.
I'm asking all this because my app is using c++ libs to make VOIP calls and do other stuff in background and I'm wondering what would happen if I just open the home screen and leave my app working, so far I've never seen the system kill the app while the call is active.
For how long can the app-process itself live without foreground service?
Android low memory killer daemon monitors the system constantly. If there is high memory pressure, least essential process gets killed. If there is not a memory problem, your app might live in the background for a long time. However vendors might limit the number of background processes. If this limit is 3 and your app falls to 4th place, it gets killed even if there is no memory pressure. And some vendors just kill the unvisible apps and there is nothing you can do about it. You can check this answer for a similar problem on OnePlus devices.
Is foreground service somehow related to application lifecycle? For instance,maybe if I start the foreground service then my app won't get killed or less likely to be killed by the system.
According to Android Processes and Application Lifecycle documentation foreground services have the 2nd highest priority in the system. So the answer is yes, if you are running a foreground service, your app is less likely to be killed even if you do not have a visible Activity.

Can a manifest-registered BroadcastReceiver + Service combo operate when its parent application is closed?

I have been trying to get an Android service to take pictures in the background using the action.USER_PRESENT trigger. Suprisingly enough, it works.
I am confused about the mechanisms involved however. Going to list some points below, please correct where I am wrong.
When an intent filter is registered in the BroadCastRecevier via manifest, it will be triggerred even if the app is closed, correct?
The created service runs its methods on a newly created thread, and will execute until end, no matter what.
What are the mechanistic differences in how the service behaves when the app is open, in the background (or stopped in some devices), or destroyed?
action.USER_PRESENT triggers when the user passes his lockscreen?
In addition, I would invite suggestions to alternative triggers to USER_PRESENT, when my condition is that the service be triggered whenever the user is using his device.
When an intent filter is registered in the BroadCastRecevier via manifest, it will be triggerred even if the app is closed, correct?
Android developers do not use "app is closed", as that is not a specific description. Many things might qualify as "app is closed". In this particular case, your receiver will work even if your process is terminated, which is my guess for what you mean by "app is closed".
The created service runs its methods on a newly created thread, and will execute until end, no matter what.
No.
First, in Java, objects do not run on threads. Methods run on threads.
Second, there is no requirement that any work done by a service "will execute until end".
All a service means is that you are telling the OS that you are doing work that is not tied to the foreground UI, and that will hint to the OS to try to keep your process around a little bit longer. How long "a little bit longer" is depends on Android OS version, system RAM, what the other apps on the device are doing, etc.
What are the mechanistic differences in how the service behaves when the app is open, in the background (or stopped in some devices), or destroyed?
Apps are not "destroyed". An app's process being terminated is the closest thing that I can think of to what you might mean.
Once an app's process is terminated, all running code is gone, including any running service code.
There is no difference in the behavior of the service itself whether the app has foreground UI or not. Having foreground UI means that the app's process is very unlikely to be terminated, assuming that your code does not crash.
action.USER_PRESENT triggers when the user passes his lockscreen?
Yes, IIRC.

Android Application dies after couple of hours

I made an android application with a runnable that checks something ever minute.
But the problem is the application goes [DEAD] after a couple hours without an error messages or anything.
Anybody have any idea what the problem could be?
That is not a problem, that is actually expected behaviour.
The lifecycle of all apps is managed by the Android OS. It decides whether to terminate an app in order to free resources and keep the system responsive. Apps that are currently is use have priority over paused and background ones. I think in your case the OS just decides to shut down the app because it thinks it's not needed anymore.
There are ways to get around this, but it all depends on what your app actually does. I don't know your implementation details, but may want to look into sticky Services or the JobScheduler in order to achieve what you want. Keep in mind that there is no such thing as a perpetually running background task that comes out of the box in Android (not should there be one) and usually implementations have certain limitations.
It could be the Android OS itself closing the app. If the OS requires more memory it will start to kill of other processes that have not been used for a long time (i.e. interacted with). You haven't stated how the check happens but it shouldn't be done directly within the app, but it sounds like it is something that a background service should be doing the work which would likely prevent this from happening.
You should NOT use Runnables for background processes, as they get suspended/killed by the OS as soon as your app goes off-screen.
If you want to let some processes run regularly, you have to stick with AlarmManager / BroadcastReceiver combination

android: how to make sure my app doesnt get paused when running in the background

Android app that I am working on reads from near by beacons(devices) using bluetooth. It works fine when the app is in the foreground (tested it for 20 minutes). However, few minutes after app goes to background it stops reading.
I notice when app goes to background, onpause() method is executed; still my app reads for few minutes and then simply stops reading anything (when I manually bring the app to foreground, oncreate method is executed and app continuous normally).
Why is my app stopped reading few minutes after it went to background. My app is an activity and not service.
should convert the activity to service or
should I create intentservice or
should I create foregroundserive
I donot understand the difference between above 3 types of services and if any of them would help me.
Though slightly older threads, I reviewed Prevent that the app get stopped or paused by the OS and How can we prevent a Service from being killed by OS? and my app killed by android system when it running in background
But I am lost. Any discussion is appreciated
EDIT
As I understand from #davidgyoung answer, I have to write a service. I assume GUI portion of my app goes into mainactivity; then how I can ensure my mainactivity/GUI is still active in memory and was not killed by Android by the time service tries to broadcast/notify GUI
/EDIT
An Activity is not designed to run for long periods in the background. The Android OS will destroy activities that are not visible as memory is needed for other functions. While a Service is the proper alternative, even a service will be destroyed under memory pressure by the OS, so you still need to restart the service if it is killed by the OS and you continue to want to do beacon scanning.
All of these issues came up when we built the Android Beacon Library, and we settled on these solutions to keep scanning going:
Use a Service to scan for beacons in the background. It does not have to be an IntentService, but that is a reasonable option.
Use an AlarmManager to restart the scanning service 5 minutes in the future in case it gets killed. (This delay allows the OS to time to recover from a temporary need for extra memory.) If the scanning service is still running, just reschedule the alarm.
Register for OS level events (boot, power connect/disconnect) to restart the scanning service at a later time if the user kills the app with the task switcher.
All of this is built for you if you decide to use the Android Beacon Library (and we welcome contributions, too!) If you want to roll your own, you may want to look at the source code to see how these things were built. Feel free to copy and modify, too. That's the beauty of open source!
Full disclosure: I am the lead developer on the Android Beacon Library open source project.

An application stops by itself (or by Android OS)

I have an Android application which supposed to be active in the background all the time. I've built it as normal Android application. It works pretty fine, however, sometimes it stops by itself (or by Android OS) and have to re-run it. It's not because of an error caused, this is because it's a normal application, perhaps.
How do I make work all the time in the background?
UPDATE:
the application has GUI.
Android OS may terminate a process at any given time due to memory constraints, you can learn how Android manages memory here. As #Karakuri mentioned starting a service would make it much less likely to be terminated, another plus for using service is that even in the event that it is killed the OS would try to resurrect at a later time when memory constraints permits:
Note this means that most of the time your service is running, it may
be killed by the system if it is under heavy memory pressure. If this
happens, the system will later try to restart the service.
You can learn more detail on Services from the Android dev site.
Create a Service and call startForeground() to make it a foreground service. It doesn't prevent it from being killed, just makes it less likely as Android will try to keep it alive longer than non-foreground services. Note that you need to place an ongoing notification with an icon on the status bar when using a foreground service.
Assuming you are using a Service. If you return START_STICKY from onStartCommand() of service, then even if android has to terminate that service, it will be re-started as soon as the resources are free.

Categories

Resources