Background task timers on iOS - android

I have an android/winphone application. Small part of app (background broadcastreceiver/task) from time to time (approx 10-15 minutes) checks local file with timestamps and if difference between one of timestamps and current time becomes more than - say - 30 minutes, it shows a notification to a user.
In Android I use AlarmManager.setRepeating(...) to setup periodic check, and to run this setup code I register a BroadcastReceiver on action "android.intent.action.BOOT_COMPLETED" in Manifest. Or call AlarmManager.cancel(...) and AlarmManager.setRepeating(...) on every launch. This way I may ber sure my timers work.
In Windows Universal I use triggers and background tasks. This works the same way with some limitations.
Now I'm porting my app to iOS, and quick look doesn't give me a way to register a function or class to perform quick checks (mostly less than a second) every 10 minutes while the app itself is not launched, and also I would like to register a function on device boot event. Is it possible?
Or should I keep my app running in background? I'd prefer not to do so, as my checks are lightweight and rare.

You can use background fetch for quick executions.
But there are several disadvantages:
Doesn't work in sleep mode.
You cannot catch device-launch event.
It will be dropped in 30 seconds.
I think in common case this is not analog for AlarmManager. Forget about it.
https://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial
https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
Push notification can be used as a trigger. But, nevertheless, this is a server-side implementation.
In the guide above:
Check the box Background fetch in the Background Modes of your app’s Capabilities.
Use setMinimumBackgroundFetchInterval(_:) to set a time interval appropriate for your app.
Implement application(_:performFetchWithCompletionHandler:) in your app delegate to handle the background fetch.
Your callback event is performFetchWithCompletionHandler

Related

executing task in a user defined time interval using work manager

I have a use case, in which I take input from the user of a time interval. For example, the user chooses 10 pm to 4 am. During this time interval, I want to basically track the screen time of the phone using Intent.Action_Screen_On and Intent.Action_Screen_OFF.
How do I approach this problem of taking time interval as input from the user and creating a work manager task which runs in the background during that interval?
This is not what WorkManager is used for. The idea of it is to be used for "persistent work". You give some criteria - constraints that need to be satisfied for the work to be executed and at the right time, based on your constraints(explicit) and the implicit one from the system(based on power management, doze, power buckets, etc) the work will start and some point, the system will ensure that it will finish successfully throughout device restarts, etc.
If you are actively tracking user interactions - you need to use a Service.
Please note that I am not familiar with how exactly Intent.Action_Screen_On and Intent.Action_Screen_OFF works, but I can assure you that WM is not your choice and there is no way for you to incorporate them.

Make an application that starts by itself and executes code in the background

I am developing a flutter application, however I would like a service to be able to run constantly without stopping in order to make an api request every 15 minutes and then send a notification to the user (Android /IOS). I would also like the service to start automatically with the smartphone. I've been stuck on this for more than a week now and I've been browsing the forums looking for a solution but I can't find what I'm looking for. Thank you in advance for any help
You don't do it like that on Android. You cannot count on an application not being killed in the background. Instead, you use JobScheduler or WorkManager to set an alarm and wake you up every so often to perform whatever job you need. These methods can also ensure you're scheduled at startup of the phone.
Also, 15 minutes may or may not happen- Doze mode may cause your app to be delayed and make requests less frequently than that if the phone goes to sleep (although 15 minutes is fairly safe, plus or minus a few).

Making code run continuously

I'm trying to make an app that does certain tasks according to a certain battery level (say a notification when battery level reaches 10%).
The problem is when i launch it the app just checks the event once instead of continuous monitoring.
e.g. (say i launched the app when battery was 11%. Since the notification is scheduled at 10% it wont give any notification. It just check the event a single time instead of continuously monitoring i.e. when battery drains to 10% while running the app,nothing happens)
What is the possible solution to make the code run continuously ?
Try using the Alarm Manager Class: developer.android.com/training/scheduling/alarms.html.
If you pass in your battery check as the pending intent, the trigger time which is when you first want to check (In your case probably the interval time after the current time) and then an interval time (Too often can slow things down a lot, so try to find a time that suits your application, e.g. every few minutes.)
This should then fire on each interval which you could use to trigger your battery check and further functionality.

Android: How to make multiple CountdownTimers work on background?

I have an App where the user can create multiple countdown alarms. Each one has it's own name, time to count, ringtone, etc.
I extended the CountDownTimer to hold each alarm setup and created a Singleton manager to manage all the alarms.
Everything is working fine until I leave the App.
The counters don't actually die. They have a weird behavior. After starting a counter:
1) if I press back key until the home screen and then power off the screen the alarm will trigger as it should.
2) if I press the home button then turn off the screen it will trigger only if I open the app.
3) if I just turn off the screen while still on the app it will trigger as soon as I turn on the screen.
I expected trouble because for that kind of thing I need to use Services, Handlers or other stuff like these.
The problem is, I'm new to Android and after reading a lot about it, I couldn't find a solution.
As far as I understood I should use Services, but it can have only one instance. How would I work with multiple alarms?
Is there other way of doing it?
I need a way to start each alarm and tell the system to keep counting no matter what happens! (and to call an Activity when it finishes)
Any help?
Is there other way of doing it?
If your goal is to alert the user of events in the future, regardless of whether your app is running, dump all your CountdownTimer logic, and switch to AlarmManager. It is specifically designed for this sort of scenario. You can set up an AlarmManager event for each timer, to get control when the end time is reached.
Also note that you will need to maintain information about your registered events in a file or database:
so users can add and remove them, and
so you can set up AlarmManager again if the user reboots their device
and to call an Activity when it finishes
Users may reject your app for that behavior. Not everyone wants to be interrupted in the middle of what they are doing with their device. Please allow this to be configurable, so the user can opt for something less intrusive, like a Notification.
You should replace your CountdownTimers with AlarmManager (as in CommonsWare's answer), after setting it up it will trigger your function to execute on specified time, here is official guide:
http://developer.android.com/training/scheduling/alarms.html
Soon you will find that after device reboot your alarms are lost, you need to restart them by catching android.intent.action.BOOT_COMPLETED broadcast.
Also you should not do a lot of work in your alarm onReceive, you should pass information to some other component like IntentService, to make it safe while device is asleep you should use WakeLock (sample project).
[edit] ---- you should also store your alarm/ringtone related data in some persistant storage, you can use for it shared preferences, or (more work) sqlite database.
I you really want to use timer (i.e. when you want to show countdowns on screen):
You don't have to have multiple timers to show multiple countdowns.
Everything you have to do is just put the target time into some collection, or event put it into the View.setTag().
Then you have timer (let say 1s tick) - on every single tick you have to iterate over all your gauges, check the target time and current time, parse the number and adjust the gauge.
However - as the timers works on separate (non main) threads - you will have to use handler or something like that.
If you want to just set some alarms - take the CommonsWare's answer - it's good one.

Android background service and AlarmManager

I am coding an android application that gets the user position every 5 minutes, stores it in the database and sends it to a server.
I have read many ways of doing it, I was going to do the following:
User starts the application
The main UI activity starts a service.
The service runs in background and keeps turning on and off the gps, and creating new
threads that will save to database,and send the data to the server.
But I have seen that it can be done with a "Remote service" (http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html) or with an AlarmManager that schedules starting this service every 5 minutes.
The service will need to be running always: it is important that after every interval (5 minutes), it is executed.
I think I need some clarity here.
Thank you for your help,
I am coding an android application that gets the user position every 5 minutes, stores it in the database and sends it to a server.
Please allow the user to choose the location provider. Not everybody has GPS on their device. Not everybody has GPS enabled. And, not everybody will want the power hit of GPS being turned on every five minutes.
Please allow the user to choose the polling period, including "never poll -- I'll refresh the information manually from the activity". Also, please honor the background data setting (deprecated as of ICS).
I think I need some clarity here.
If the polling is supposed to go on even if the activity is not in the foreground, use AlarmManager. However, most recipes for using AlarmManager will have the real work (in your case, GPS fix and network I/O) be handled by an IntentService. This will not work in your case, because GPS is asynchronous -- you cannot just get a fix whenever you feel like it. It will take a long time, possibly forever, to get a fix, so you have to deal with the delay and eventually timing out the operation. Writing a Service to do this is possible, but tricky, particularly if you are aiming to collect this information even if the device falls asleep.
If, however, the polling is only supposed to go on while the activity is in the foreground and the device is on, I wouldn't bother with a Service at all. Just have the activity use postDelayed() to set up an every-five-minutes scheduled bit of code to run, then have it do the work.

Categories

Resources