I am using AlarmManager for repeated background process. My app repeatedly requests data from server in 5 sec interval. But after some long time, when I open my app it crashes. I can't figure out why.
How should I execute a background process repeatedly? Should I use AlarmManager,Timer` or something else?
My background process should run always even when the app does not have focus or isn't active.
My app repeatedly request server for data 5 sec interval.
Users with mobile devices, like phones and tablets, will not appreciate your behavior. They will not appreciate your consumption of battery life and your consumption of bandwidth. Device manufacturers and Google are continuing to take aggressive steps to prevent applications like yours from behaving this way, both automatically and by giving users the tools to find ill-behaving apps like yours and get rid of them.
But After some long time when i open my app its crash
Most likely, you have a bug in your app. You will need to fix the bug. Since you have provided no details of your crash, such as source code and a stack trace, nobody can really help you with that.
Which is the best for repeated background process, AlarmManager, Timer or something else?
Switch to a user-configurable and less-crazy polling period (e.g., every 15 minutes by default), then use AlarmManager in conjunction with an IntentService, so that your process can cleanly go away
Or, switch to having the server send messages to the device when the data of interest changes, such as via Google Cloud Messaging. This will allow you to drop the polling period to something infrequent (e.g., every hour by default), as a fallback mechanism in case you miss a push message for some reason.
My background process should run always though the app is not on focus or active
Your users will disagree with you. They do not want apps running all of the time, tying up system RAM. They really do not want apps that consume battery and bandwidth the way that you are proposing. The users will get rid of your background process, either by:
swiping your app off the recent-tasks list
using a third-party task manager
force-stopping your app via its entry in the application list in Settings
uninstalling your app
Related
I believe you all are already familiar with "background service limitations" imposed on Android 8.0 and up (https://developer.android.com/about/versions/oreo/background.html#services).
I'm having a very particular problem right now. My application is meant for a very specific use case. App checks for certain data on the server every minute and in case of some wrong value, user is being alerted immediately. Obviously so far application was running in a form of background service and my customers never cared about (obvious) battery consumption coming from complex calculations that are being performed every minute.
Now, whole idea is that app needs to stay alive, working and in background (even with permanent notification, i don't have anything to hide) regardless of anything! If phone is in a deepest possible sleep state - service needs to keep running. If there's 2% battery left - service needs to keep running. So far, i managed to achieve that using alarms and "guardian services" which prevented any way of stopping the background service while app is installed. But now, with Android "0" - what's the way to go? Is there a JobScheduler that will guarantee execution at given rate (every minute) regardless of anything?
How SMS / Phone, WhatsApp and similar apps achieve that "awake no matter what" state?
That's what Google tells us.
A process is not forever.
If you feel you need your foreground service to stay alive
permanently, then this is an indicator that a foreground service is
not the right answer.
Effective foreground services on Android
I think you could use repetitive tasks with WorkManager or change the architecture and use FCM. In any case, Google will not let us work as it did before.
I am developing multiplayer game using Socket.io library. it Works Well.
But, in android 7.0 and above, system automatically suspend all network work when my app is in background. (And I must need to keep alive my socket connection).
I research about it as described here.
but, i can't understand. So, Please provide solution for that.
Unfortunately there's bad news and some good news for you on this.
Bad:
Since android marshmallow and above, there's a concept of a doze mode. If the device stays put for some time (can't confirm the duration for this and not disclosed by google), the device will go into doze mode and will suspend all network activity. There will be short maintenance windows where in you will be able to do syncs and stuff. Small workaround, do not target 23+ apis, i say small because i have observed this to not work on some phones. Another way to potentially bypass this would be to whitelist your app from battery restrictions but according to google guidelines, i don't think your app will qualify for that.
Worse news is that start from API 26, background services will also get suspended completely when app is totally backgrounded and has no visible component (a notification or a foreground service etc...). So oreo will be worse.
Good:
You might not really want to constantly keep the socket open. Instead opt for bursts of syncs. I personally have a job run every 30 - 60 mins or so to try and sync up.
You can leverage the JobScheduler apis and it will automatically handle the doze modes and stuff and you can make them run periodically when there is internet connection. While the job is running, you can connect to your server, do your thing and shut the socket. This is what google wants and is pushing all devs towards.
UPDATE 19-Apr-2021
WorkManager is the new and the best way to deal with doze mode and background limit restrictions.
Another alternative would be to have a foreground service with an active notification displayed which would constantly be connected via your socket. This will be visible to the user and it will not only annoy them that you are constantly using their data, it can also be bad for the battery. Alternative to this again is using the job scheduler to schedule and run a foreground service periodically so as to be transparent while also syncing your data every once in a while. The latter approach is what WhatsApp does, they have a job running which syncs all incoming messages with a foreground service once in a while.
In Short:
You will not be able to keep it alive always. You can try doing it in bursts using one of the methods that i described and know currently (maybe there are other alternatives that i don't know, i have tested these and they work) You will have to compromise, sorry.
I'm trying to develop an Android app that among other things, uses location services to get user location and sends it to a remote server. The user can turn this feature on and off according to his own will, but as long as it's turned on, it will get user location periodically (maybe each 30 seconds, don't know it for sure yet). Also, while it is turned on, it must keep tracking the user even if the application is closed.
So far I've considered 2 options:
Option 1 - Use Service, call startForeground to make sure Android don't kill it (the sticky notification is not an issue to me) and use a LocationListener with the said interval, but this seems rather inefficient as the service would be doing nothing most of the time, I mean, the listener would be called each 30 seconds, send the location to the server and the service itself would spend the next 29.9 seconds or whatever just waiting for the next location.
Option 2 - Doing some research, I've seen some approaches using AlarmManager to trigger some background service (like seen in this post), but I'm concerned that using alarms that often (every 30 seconds) might not be good for the battery and system general performance (in a code snippet in this page of Android's Developer guide there's a comment saying that "hopefully your alarm will have a frequency lower than 30 MINUTES").
Maybe there's another option that I still haven't thought about, or maybe there's a way to put the service from option 1 to sleep for some time or something like that. Bottom line, I'm looking for the approach that doesn't impacts on performance, consumes the minimum amount of battery and has the least chance of being killed by Android.
Any help and/or suggestions are welcome.
I want to perform action/event when application killed from task manager or any other app. Is there any to perform action when application killed. My application is running in background like service. If i terminate the application then main service stop . I want to start it again.
No, there's no reliable way to know if your application was killed by a another process. The whole point of "killing" an app is to terminate it as soon as possible, without letting it run any code.
== Do not actually use the following suggestions in production application. They are here purely as potential technical solutions, but in general are not a good idea for apps running on end user devices. ==
It might be possible to use IBinder.linkToDeath() from a secondary application, which acts as a monitor for your primary one. However, you will have to convince the user to install the secondary app as well. If you can do it, you could establish two-side monitoring between the two apps, and have one of them restart the other if the second is killed.
You could also attempt to set an alarm through the AlarmManager that fires every so often, to restart your application if it happens to be killed. However, if your alarm period is too big, you risk having certain period of time where your app is not running. And if your time period is too small, most likely your app will not be allowed by Google in the Google Play Store, and the malware app analysis on the phone (JB+) might kick in. Also, alarms that kick in too often will keep the device awaken, and drain the battery very fast.
If you kill some process, you just kill it, so it stops working immediately. There is no event sent to the application.
I looked for the same thing and the answer that i found is : NO, the application does not go to OnDestroy() or anything like that.
My company has, in essence, undertaken a project to replace some of its pagers with stock smartphones running Android. As long as they are signed in, the device should be listening on a particular socket to receive "pages" from a server. My naive implementation was to create a foreground service that 1) kicked off a listening thread, and 2) holds a PARTIAL_WAKE_LOCK.
This works fine unless the device has a long period of inactivity, 1+ hours. Then, it appears that the OS shuts down my app's process, understandably believing it to be not in use.
I completely understand their reasons for doing so, but I'm wondering if I can somehow get around this restriction. Are there ways to signal Android that my process really is important enough to keep alive/the device awake? I learned both Java and the Android API for this project, so there are plenty of areas where my knowledge is incomplete.
Failing that, given the description of my business needs, how would you suggest implementing this functionality? While the user is signed in to our custom app, the device should always be listening.
Thanks to everyone for reading this question.
The OS won't kill your process if you are using Service.startForground(). This is what things like music playback use, and you wouldn't want those to be killed after some amount of time.
That said, for this kind of thing you generally wouldn't need to make your service foreground -- when the system does kill your process because it has been sitting around or needs the memory, it still knows the service wants to remaining running so will restart the service shortly after that. This is how Google's own services work, they have one .apk that has a background service running that keeps a network connection open to a Google service which reports back when interesting things should be done like sync new e-mail, retrieve and deliver a C2DM Intent, etc.
Also you should not hold a wake lock during all of that time. You will kill the battery, especially on some devices like those with Samsung's Hummingbird processor. The right way to do this is to just leave the socket open and let the device fall asleep. If data is delivered to the socket, the CPU will wake up to deliver that data and at that point you should acquire a partial wake lock just for the time you need to read and process the data.
What you describe sounds like a job for Android Cloud to Device Messaging Framework.
It's currently not completely open but there is a signup link on that page. I signed up and was accepted within 20 minutes of my application. Worth a look IMO.