android component that never gets destroyed by the system - android

I am developing android application right now, which sends requests to the server every 4 seconds. I need to make sure that app will keep sending them even if it goes to background (by pressing home button, opening another app or receiving phone call). As far as I know, the best solution for this is to use services. The question is, does service guarantee that it will never get destroyed by the operating system? And if it does get destroyed how can I handle this situation (restart the service)?
Or may be there is a better solution than android service?
App can have any permission over device or operating system, but it must not be rooted. So we can easily update it through google play store.
Thank you very much in advance!
PS. Please don't hesitate to ask me questions if something is unclear.

A Service is indeed what you're looking for, however bear in mind the following things:
1) Services can and will eat up battery life if left unchecked. In your case specifically every one of those 4 second calls will cost you a little more battery life.
I feel like this will absolutely demolish battery life and data usage for most individuals. – CollinD
2) Services will NOT be destroyed by the android OS unless they fail/error out (which you can set conditions for in the service), or they are paused/destroyed by the application.
3) The last chance a user has to change/modify a service before their application closes is in the OnPause() or on Destroy() method. After these are called the application is closed and the service cant be modified without reopening the app so make sure you call anything you need to to make sure the service persists in one of those methods.
I'm not sure if this completely answered your question so let me know if theres anything else I can clarify but it seems like you are using the proper android component for what you're trying to accomplish.

Related

Start two services in foreground?

In an effort to keep my services alive, can I have more than one service in foreground?
I am starting two services at once, and I don't want any of them to be destroyed. So, after reading for hours, I found the solution is to return START_STICKY and use startForeground(...) on my service. But, I have two services, so can I have them both be in the foreground, and both never be destroyed?
There are several aspects to consider.
First of all: if you have two services in foreground, you have to have two notifications as well. This is considered as a security feature (check for instance this post). Having two icons in the status bar for one app might be quite confusing to the user and is IMHO reason enough to drop this idea.
As stated in the comments: even if starting in foreground, a service might be destroyed anyway. Just keep this in mind. However, in my experience this happens rather rarely, almost never - except with ...
... devices that are shipped with pre-installed start managers or energy savers (many Huawei devices for instance). If your app is not configured appropriately your services will be killed several seconds/minutes after the screen turns off - or it will not automatically be started after reboot.
So, as always it depends on what exact you want to achieve ;) But to me it looks like as if you could simply implement two threads in one sticky service - I can't any see disadvantages here.
If your app gets inactivated by any kind of start manager, crash, or force close, your users might have to start the app again (see this post including app states).
Hope this helps!

How to determine when android application has been started and when has been stopped

I have android application with several services.
This application should send reports to remote server when this application has been started and when has been stopped.
But I don't know how to determine that application was stopped, because application may be stopped (crushed for example), but services still running.
I think that the algorithm should be like this:
Check the mark with last date from storage (and if this mark exists - send "stop" time to the server)
Send "start" message to the server, when application was started
Every 10 minutes application should writes current date and time mark on disk
If I will create service with this check - android can kill this single service when there is low memory, but application can be running. If I will create ScheduledExecutorService in Application class - application can stop, but services can be still running.
Can you help me with solution?
There's really not a single answer to this question. It has been asked many, many times here at SO, but all we can say is it really depends on our app's behavior.
You want to put some Log messages in onPause(), onStop(), onDestroy() in your Activity, and onDestroy() in your Service. Watch the the flow of the app carefully by looking at the Log printed out in the Logcat.
Lots of people try to rely on onDestroy() method because it looks like it is called when the app is completely terminated, but that's not always the case. Sometimes app crashes (force closes) or some people just manually force close it in the app information in settings. In that case, app does not follow the lifecycle of the activities.
One of the suggestions would be creating a thread that runs in background and send a UDP packet to a server saying that the app is alive in every few seconds.
PRO: You don't need to make a handshake with the server so it saves time/resources getting response back from the server.
CON: Thread running background does use battery. UDP can be only used in WiFi environment for recent Android OS.
Hope you find a good way. You may want to comment to your post when you found a good solution, because people would like to know how to solve it, too.
Why not try to trust standard methods Activity?
You should approach onDestroy and / or onPause. It depends on your logic.
In addition, you can try to override Application.onTerminate(). You can read about it (Application) lifecycle here.

Activity destroyed after 1 hour

I'm new to Android development. I'v developed an android application which needs to store the connection/data even after 1 hour. Currently I have all the data and the connections(chromecast mediaplayer) in a singleton class. But, when the user puts the app into the background for about an hour, the activity is destroyed so the connections,data etc are lost causing my app to crash when re-launched.
I've read up on the android services, Can I use these services to hold the singletons so even when the activities are destroyed I can have data binded back to the views when re-launched?
Or is there a way to make sure that the activities are not destroyed when android decides to do a cleanup?
Please advise
Thanks.
I think you might misunderstand what an Android application is.
Your application is a bunch of components that run in a single Linux process. Components come and go, within that process. You have absolutely no control over the lifecycle of the process itself.
The answer to part of your question is that "yes" a Service will stick around after an invisible activity is destroyed.
When an Activity becomes invisible, it gets destroyed. If your process is not doing anything else, then the process is likely to be killed too.
If your process is also running a Service, it is less likely that it will be killed. It is just less likely, though. The process will eventually get killed. When it does, your singletons will be gone. There is nothing you can do to prevent that. So the answer to the second part of your question is "no". You cannot depend on singletons in your service to be around when the process is relaunched
You might look into using the Application object. Its lifecycle is roughly the same as that of your process. It will not live forever but it will be around whenever any other component of your application is around (except ContentProviders).
It sounds like you want to keep connectivity to a chromecast device around when your application is in the background. Obviously services can be helpful but I have a few comments that may come handy:
Services can be killed by system but based on how you have set them up (e.g. the return value of onStartCommand()), they can be restarted by the system. When that happens, you cannot expect that your dynamic data is still there (for example your singleton). You need to include logic to recreate what you need again (for example, rebuild your singleton)
Phone can go to sleep when left for a little while (or user can lock his/her phone), so when phone goes to sleep, wifi may drop after a little while, based on the phone settings and the build on your phone; some do this more aggressively and some not (even if you hold a lock, it can still happen). The point is that you have to assume that it may happen. Even if you have a service, your Cast connection will go down due to wifi loss, so the proper way to handle things is not to try to keep the connection up all the time (since you can't) but is to have logic to re-establish connection when circumstances is right. In order to do that, you need to preserve enough information to be able to bring things to the state that they were. Your logic should also be intelligent enough not to reconnect if it shouldn't.
Android O.S can destroy any activity , when it is low at resources it destroys any activities to make more space for other apps.
But you can use background service to hold your singleton
You can use this link to create your background service

Can I keep Android App alive in background?

I currently have programmed a normal Andorid-App (no Service). It contains a timer for periodic checks. To avoid hassle with a service and communication between Service and App I ask myself whether there is a way to keep an App that is no longer in foreground alive.
Currently when I "close" the App, it is still alive until Android OS decides to kill it. Is there a way to avoid this kill - e.g. by a certain command in "onDestroy" or a certain App-flag?
My App is quite complex and I do not want to implement a Service as this -especially the communication/binding- increases the complexity. Is there an "easy way" or am I really forced to use Service+App? Maybe there is a trick to register the App for sth. special that has the side-effect that Android OS does not kill it when it is in the background.
Edit for better understanding: It is ok that the GUI can go into the background (vanish) when the user wants it, so my question is not how to let the GUI of my App permanently in the foreground. All I want is that the timer stays intact without the need for an additional Service.
Thank you all for ideas in advance!
Android is very unpredictable by the nature of the OS's killing selection and by the market fragmentation. I would not count 100% on anything being kept alive if it is crucial. However you can gamble and be pretty successful. This is what would help you:
Use very good "Best Practices" to keep your string pool and heap at a minimum as Android looks to kill memory hogs first off (and because you love what you do).
Add the persistent attribute to your application manifest tag.
To really help yourself out, run as a, or run a service because they are long running processes, are very light (if implemented well), and Android looks to kill these off lastly.
Give your service priority by running it as a foreground service.
Doing these things will increase the likely-hood that Android will not kill your application.
I don't think there is anything like that available. I suggest looking at AlarmManager for periodic tasks - this may mean you won't need to use a service.
The apps being available in the background is simply a caching measure by the android OS to avoid having to relaunch a frequenly used app from scratch. If you want to be able to count on your app running in the background, a Service is the correct solution. Its not the answer you are looking for, but I am not aware of any tricks to staying alive in the cache, and if there were any, I would not feel good about recommending them.

Why dont Android applications provide an "Exit" option?

Is there something in the Android developer guidelines that disuades developers from providing the option to "exit" (stop running) an application from within the application itself?
I love multitasking and all but it's not clear to me why:
the vast majority of apps don't have their own Exit functions and hence just keep running forever
don't give you a choice about running when you turn on the phone - they just do by default
Both of these things lead to memory usage constantly increasing and your device running with this performance burden all of the time despite the fact that you may only want certain apps to run some of the time.
Am I missing something?
Is there something in the Android
developer guidelines that disuadea
developers from providing the option
to "exit" (stop running) an
application from within the
application itself?
Yes. It is generally not needed, just as it is generally not needed to restart a Web server because some user with a browser decided (s)he is done with a Web app.
the vast majority of apps don't have
their own Exit functions and hence
just keep running forever
They don't keep running forever. Android will close things up as needed.
don't give you a choice about running
when you turn on the phone - they just
do by default
Those developers aren't paying attention to me.
Both of these things lead to memory
usage constantly increasing
Generally, it doesn't. If you find specific apps that do this, uninstall them.
and your device running with this
performance burden all of the time
Generally, it doesn't. If you find specific apps that do this, uninstall them.
Also, this question is a duplicate of this one.
"Both of these things lead to memory usage constantly increasing"
Which doesn't matter since Android apps are limited to a fixed amount of RAM. Freeing RAM won't give more RAM to other apps.
Essentially, there's no need for a quit button as long as the developer does a good job of designing their app. Android activities are stopped when they aren't visible and resources are needed elsewhere, so the are no longer consuming resources. You can read about the lifecycle here:
Here's a related question:
From Google's Android Application Fundamentals page:
Shutting down components
A content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components.
Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for a long time. So Android has methods to shut down activities and services in an orderly way:
An activity can be shut down by calling its finish() method. One activity can shut down another activity (one it started with startActivityForResult()) by calling finishActivity().
A service can be stopped by calling its stopSelf() method, or by calling Context.stopService().
Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section, Component Lifecycles, discusses this possibility and its ramifications in more detail.
So it seems like Content Providers and Broadcast receivers should never be explicitly shut down, as they are inert while not handling their specific events.
As for Activities, I would argue in favor of having an end to it, but in certain cases. If your app has a finite state in which the user is done using it, why keep it alive until GC gets it? The activity manager still needs to keep track of that Activity while the user has finished their task. My best example for this is the Calculator. You open it, you have it solve a problem for you, and then you close it. If the onCreate function is so expensive that it's more effective to do onCreate once and then onRestart whenever the user moseys back to your application then you're probably doing something wrong. Maybe I'm misinterpreting how Android handles Activities, and if so I'm always interested in learning more :)
It all comes back to the answer that users want total control of their running and auto-start list and what they do and don't want installed, example: google maps, etc etc. there are no two ways about this.

Categories

Resources