Android recommended and reliable API for periodic background work? - android

I've been using WorkManager to create notifications for my app. For my purposes I figured PeriodicWorkRequest is the most fitting, but after a bit of testing and reading online it's seems extremely unreliable. Using the minimal interval (15 minutes), and the app being closed, the worker woke up 5-6 times and then seems to be killed.
So how does one go about creating background work that wakes up in reasonable time intervals? What is the best approach for creating event-based notification? My idea was checking for the event (for example, checking for something new in the database) in small time intervals (with 15 minutes also being less than ideal), but seeing as it doesn't work well with PeriodicWorkRequest and is also the recommended approach as per the documentation, what exactly are my options?

Basically, the idea of Android is for you not to be able to do what you want to do because we as developers try to kill the battery.
You need to see how the evolution of the restrictions goes:
Version 6 - Doze:
https://developer.android.com/training/monitoring-device-state/doze-standby
https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-power
Version 7 Another state of Doze with even more restrictions:
https://developer.android.com/about/versions/nougat/android-7.0-changes#perf
Broadcast Restrictions:
https://developer.android.com/guide/components/broadcasts
https://developer.android.com/about/versions/nougat/android-7.0-changes#bg-opt
Version 8.0 Background execution limits:
https://developer.android.com/about/versions/oreo/background#services
Version 9 StandBy Buckets - where depending on how the app is used you have different resources to use - like time to wake up the app, time to use the Network, etc
https://developer.android.com/about/versions/pie/power#buckets
https://developer.android.com/about/versions/12/behavior-changes-all#restrictive-app-standby-bucket
https://developer.android.com/topic/performance/appstandby
Battery Save improvements:
https://developer.android.com/about/versions/pie/power#battery-saver
Power Management Restrictions - really important.
https://developer.android.com/topic/performance/power/power-details
Version 11 and 12 App hibernation
https://developer.android.com/topic/performance/app-hibernation
Long story short - you need to prevent all these restrictions to harm your work. But you need to comply because it is better for the user.
But there is no API that will just say - "f**k all these restrictions and do whatever the dev wants to do."
If you need exact timing - you need AlarmManager.
If you do not know when you need to do your work and depend on the outside - Push Notifications which then can transfer the work to the WorkManager.
If you need periodic work that is not time-critical - you might not use the AlarmMangaer and be sure that the work is finished, but you can't be sure when, because there are many restrictions and the priority will be saving the resources.
Also, you can ask the user to be exempted from Battery Optimization:
https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases
If you want to know why exactly the work is not executed you need to check the JS dump and see what restriction is not satisfied:
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/debugging#use-alb-shell0dumpsys-jobscheduler

Related

Syncing with server in specific interval at non-active hours

I want to sync the data with server between 12 am - 6 am only.
I have solutions like WorkManager and sync adapter at my disposal.
But some manufactures put restrictions on these work managers and syncadapter also.
What is a sure shot solution that a network request will can be made between these non active hours(most users are not using the app) ?
There is no sure solution. This is Android. Every vendor can do whatever they like.
What restrictions you are talking about? Because you are saying "some vendors"? In general Android applies restrictions related to how much time you can be executed per 24 hours period and how much network you can use. It is dependant on the Power Bucket you are in. And the Power Bucket itself depends on how often the user interacts with your app. Check here:
https://developer.android.com/topic/performance/power/power-details
You can implement a dialog asking the user to exempt you from Battery Optimization. This will fix the restrictions on most vendors. Check here:
https://developer.android.com/training/monitoring-device-state/doze-standby#support_for_other_use_cases

How to perform background service while battery optimization is active

I currently use the Firebase JobDipatcher to perform a periodic task in the background. The problem is the background service only gets executed when battery optimization is disabled and standby state of the app is manually set to ACTIVE under developer options. Is there a way to do the background task without manually changing all this, because i cannot ask every user of the app to do so. And saw many posts that google will suspend the app if the power management permissions are requested within the app. Any help would be much appreciated.
In one word answer is BIG NO
As developers remains unhappy with such small answers, so i am starting the HUGE theory, here we go -
STRATEGY NO - 1 :
Use AlarmManager
All alarms are forgotten by the android on Reboot, so keep all alarms in app Sqlite database, implement BOOT_COMPLETED broadcastreceiver, which is still allowed to define statically & re-schedule all alarms by taking from apps database.
All your project & hard work will work as per your plan, but only on emulators
Because in real world, 99% devices are with chinese ROMs like MIUI, OxygenOs, ColorOs, FunTouchOs, .. which never triggers your apps BOOT_COMPLETED broadcastreceiver.
Because they all are ahead in saving battery life, by stopping all apps background services..!!
Nice question,:- Then why whatsapp, facebook, tiktok, twitter processes are getting executed normally...?? And why not mine...??
Nice answer,:- If Chinese ROMs disallowed above apps background services then no one will buy their devices..!! And lets do not talk about your application as it does not affect the world in any way, your app is useless ( as per chinese ROMs ) , so they disallows all other packages background tasks..!!
All Chinese ROMs never triggers AlarmManagers if the app is not in foreground. Never triggers if app is removed from recents
In short & sweet treat Alarmmanager as depriciated.
STRATEGY NO - 2 :
Use FirebaseJobScedular as you stated
If user updates Google Play Services , then system forgets all jobs..!!
Again FirebaseJobScedular was developed to run all jobs on every device in market, but as chinese ROMs never allows any processes / classes / Jobs from their own wishlist, this makes no sense again.
This library is depriciated by google now.
STRATEGY NO - 3 :
Use WorkManager, the new library which is taking place over the FireBaseJobScedular officially.
Again the same thing, WorkManager is still in development, you can use it, but the case is same that many chinese ROMs discard this libraries jobs too..!!
STRATEGY NO - 4 :
Run all time foreground service.
BOOT_COMPLETED from your broadcastreceiver start it again.
But even if you use START_STICKY, many chinese ROMs used to suspend its tasks, you can see it in foreground, but works gets suspended.
STRATEGY NO - 5 :
Use WakeLocks
But as the android version changes, it has changed to the newer newer implementational strategies in every versions
STRATEGY NO - 6 :
Programatically make battery optimisation off for your app, but google discontinues your app from app store in such case
Navigate user to battery optimisation settings intent, by opening it programatically & let him choose battery optimisations on his own, is allowed by google
But as no user is in market, who knows it, as even many developers dont know this yet, how end users can understand it..??
Again if power saving mode ( it is different than battery optimisation okay ) is made ON by user then, no way your battery optimisations is never considered.
What the ***** should i do then ...?
Nothing as developer.
Train your support / sales team to "LOCK" your app in the recents of every phone, after which, users are unable to swipe it away from the recents, even if it is swiped away, your all above strategies will work & your jobs / alarms / tasks will be executed, as it happens on your android emulator or as on stock android
Train your support / sales team how to make battery optimisations to "Do not optimise for this app" too..
It is so out of the box solution..??
Yes, it is. As in the market you will notice 1% stock android devices and 99% chinese modified ROMs
This all knowledge came to me after i lost last 9 to 10 years resolving the same problem, Hussshhhh

Proper way to tackle and resolve "Excessive network usage (background)"

Problem Background
Currently, we have facing "Excessive network usage (background)" from Android Vital report. Last 30 days is 0.04%, but we're only Better than 9%
Last 30 days - 0.04%
Benchmark - Better than 9%
Since only better than 9% looks like a scary thing. We decide to look into this issue seriously.
The app is a note taking app (https://play.google.com/store/apps/details?id=com.yocto.wenote), which provides an optional feature - sync to cloud in background after the app close.
This is how we perform sync to cloud in background.
We use WorkManager.
In Application onPause, Schedule OneTimeWorkRequest, with constraint NetworkType.CONNECTED. The worker is scheduled to start with delay 8 seconds.
In case failure, we retry using BackoffPolicy.LINEAR, with delay time 1.5 hours.
The maximum number of retry is 1 time. That's mean, after the app close till the app re-open again. The maximum number of execution, of sync to cloud process is 2.
The size of data is vary, can be few KB till few hundred MB.
Additional information how we perform sync
We are using Google Drive REST API.
We are performing downloading of a zip file from Google Drive App Data folder, perform data merging in local, then zip, and re-upload the single zip file back to Google Drive App Data folder.
The zip file size can ranged from few KB, to few hundred MB. This is because our note taking app supports image as attachment.
Analysis
The only information we have is https://developer.android.com/topic/performance/vitals/bg-network-usage .
When an app connects to the mobile network in the background, the app
wakes up the CPU and turns on the radio. Doing so repeatedly can run
down a device's battery. An app is considered to be running in the
background if it is in the PROCESS_STATE_BACKGROUND or
PROCESS_STATE_CACHED state.
...
...
... Android vitals considers background network usage excessive when an
app is sending and receiving a combined total of 50 MB per hour while
running in the background in 0.10% of battery sessions.
We start the background sync job, 8 seconds after Application's onPause. During that period, will the app inside or outside PROCESS_STATE_BACKGROUND/PROCESS_STATE_CACHED? How can we avoid running inside PROCESS_STATE_BACKGROUND/PROCESS_STATE_CACHED?
What does it mean by "running in the background in 0.10% of battery sessions."? How can we avoid such?
Another assumption, is sync file is too large, and using too much data. Soon, we notice this assumption might not be true. We notice according to "Hourly mobile network usage (background)", the data size is from 0MB to 5MB.
Questions
My questions are
What is the actual root cause for such "Excessive network usage (background)" warning? How can we accurately find out the root cause.
How does other apps (Like Google Photo, Google Keep, Google Doc, ...) which perform background sync, tackle this problem?
For your first question, "Excessive network usage (background)" is triggered when:
... an app is sending and receiving a combined total of 50 MB per hour while running in the background in 0.10% of battery sessions. A battery session refers to the interval between two full battery charges.
Source
To identify what is causing this, try using Battery Historian to analyse your app's battery usage over time. For us, it helped identify a repeating wakelock we didn't intend to introduce.
Here's an example of the output, showing us that excessive BLE scanning is causing a major battery impact:
For your second question, WorkManager is likely what you are after, as you correctly identified. This allows you to schedule a task, as well as a window you'd like it to occur in. Using this allows the OS to optimise task scheduling for you, along with other app's jobs. For example, instead of 6 apps all waking the device up every 10 minutes for their hourly task, it can be scheduled to happen for all 6 apps at the same time, increasing the time spent in doze mode.
Notice the screenshot above includes a "JobScheduler Jobs" tab. After running an analysis you'll be able to see how your jobs are actually performing:
I've previously used Firebase JobDispatcher with great success (tutorial I wrote), which extends the OS' JobScheduler API and is ultimately similar.
I see you're using WorkManager now (Jetpack's version of JobDispatcher), but with 8 seconds there's no chance for the OS to optimise your jobs. Is there any capacity of scheduling them with a minimum of a few seconds, and as large a maximum as possible?
Further improvements
However, your current task scheduling setup may not be the root cause. Here's a few additional ideas that may provide the battery improvement you need. The usefulness of them will become clearer after you've run Battery Historian and identified the root cause:
Consider whether wifi-only is a feasible default / option for data syncing. You'll experience better battery usage, fewer network issues, and likely better customer satisfaction.
Why does a note taking app need to sync a few hundred MB? Can you perhaps just sync the note that has changed, instead of the entire list of notes every time?

Long network operation on Oreo

In my Android application the user has an option of using the application in offline mode. When the user opts to enter the offline mode, I download all the content from the server(which might take even upto 7 minutes) for offline usage. The usage of the application henceforth is dependent on the download of offline content.
I am using a service to download the offline content. But the service may not work in Android 8 if the app goes to the background. So what is the best approach to download the offline content for Android 8? Is it a foreground service or JobIntentService or a WorkManager?
Anything that is backed by JobScheduler — which includes JobIntentService and WorkManager — has a 10-minute limit. You indicate that your work may take up to 7 minutes, which makes me somewhat nervous.
In the short term, make your existing service be a foreground service, as that will keep your code working (other than any problems that Doze mode might impose).
If your 7-minute download work is really a series of smaller things that add up to 7 minutes, you might eventually migrate to WorkManager. Divide your work into smaller chunks and set up chained work with WorkManager, so you are certain to not go over the 10-minute limit for any of those chunks of work. Plus, WorkManager lets you establish constraints to say that your work should only be performed if you have an Internet connection. Right now (late August 2018), though, WorkManager is only 1.0.0-alpha07, so I would not ship a product based on WorkManager until it at least reaches a 1.0.0 final version.
The best approach would be to use WorkManager. As stated in the docs that:
WorkManager is intended for tasks that require a guarantee that the
system will run them even if the app exits, like uploading app data to
a server, or downloading data from server.
The benefits of using WorkManager over services includes handling of doze, standby, battery optimizations and constraint execution etc.
You can schedule a worker with WorkManager to download data for your app from server, and once data is available, you can go on with your offline mode.

execute periodic network requests in batch

I would like to know about the behavior of android in case of periodic network requests. As of Android Kitkat documentation "Android works with the device hardware to collect and deliver sensor events efficiently in batches, rather than individually as they are detected. This lets the device's application processor remain in a low-power idle state until batches are delivered". This functionality was introduced in android 4.4.
AlarmManager redefined in Kitkat "To improve power efficiency, Android now batches together alarms from all apps that occur at reasonably similar times so the system wakes the device once instead of several times to handle each alarm".
So my question is that, is there any way to do the same in case of network calls or any API available which provides the same functionality.
I searched and found that, there is no simple API available for batch network calls but there is a way to achieve the goal is to use the Google's recommendations about regular updates.
As per documentation "When scheduling updates, use inexact repeating alarms that allow the system to "phase shift" the exact moment each alarm triggers".
Official Documentation

Categories

Resources