How to avoid worker to run when app is paused - android - java

I have to implement a periodic request to the server every 15 minutes to update database info, that should be running async while the user is using the app and if the app is closed or paused it shouldn't keep working until the app is resumed
I'm using WorkManager to do that and is already working but I realized that when I minimize my app, the worker keeps calling doWork() every 15 minutes. Killing the app works well because the doWork() is not called.
So the question is how I can disable my worker when app is minimized? Or what I should use instead of WorkManager?

extend Application class (and register it in manifest)
use registerActivityLifecycleCallbacks and inside registered Application.ActivityLifecycleCallbacks set up some value, e.g. activitiesStarted++ in onStart and activitiesStarted-- in onStop
when your WorkManager fire your code just check at first how many your Activities are started, if ==0 then all are "homed" (or killed)
in HERE you have some samples how to do this properly
there is also some clever lib for your purpose - Lifecycle

Related

keeping an android service running for a long time

i want to run an android service for a very long time even when the phone is locked. i have tried job Intent Service and work manager but it doesn't work for long period.
the service is supposed to call an server API periodically.
work manager minimum interval is 15 minutes but i want to call this api every minute
is there any way to do that?
The best option you can use is Workmanager which is part of the Jetpack as in background it runs Jobscheduler or the Alaram manager according to api level.Now regarding long running service to run the service in background first thing you need to do is to show the notification to the user but in my case still it was stopping when device is locked or on sleep mode.So i that case WAKE_LOCK worked for me to awake the device.So i your can look whether it fits for your solution or not also make sure if you use wake lock then once your take finish don't forgot to release wake lock.
1) add Service.START_STICKY
Service is restarted if it gets terminated. It will tell the system to create the newest copy of the service when available memory is sufficient to do after it retains the state and recovers from the low memory.
2) add android:persistent="true"
<service android:name="com.myapplication.MyService" android:persistent="true"></service>
although, you can use WorkManager for persistent works
Since version 2.3.0, work manager has support for long running operations with foreground notification support.
https://developer.android.com/topic/libraries/architecture/workmanager/advanced/long-running
As long as you can foreground api of worker, user will see a notification and during that time your worker can continue working in background.

Android kills my Threads/AsyncTasks

I run my asynctask class of activity, then finish the activity, and asynctask still works. Android after some time killing my asynctask. I tried to add to the function run "Process.setThreadPriority (Process.THREAD_PRIORITY_FOREGROUND);" or "Process.setThreadPriority (Process.THREAD_PRIORITY_BACKGROUND);" but asynctask is still killed.
Yes I know they are Services, but I want the task was completed after the work done, and do not work all the time in the background as Services.
You should use IntentService. This is different from a regular Service. IntentService will result in the service closes it self when it is done. IntentService is not running on the UI thread so you don't need to "handle" it as you need to do with a service..
You start it, it does some work and when it finishes it closes itself, exactly what you need.
There is no way for you to insure that the Asynctask will finish, since it's not build for that purpose.
Also, a service is not "running" as in taking cpu when it has nothing to do even if it's open.

Which concurrency construct to use for running multiple background tasks when the app is paused for Android?

I'm trying to implement multiple tasks in my app that are required to continue running even when the app is paused (when the app loses focus but the user has not completely closed the app).
The first task consists of establishing a connection to a server and receiving updates.
The second task consists of communicating back and forth with a paired Bluetooth device.
Both tasks will not only be ran when the app is paused, they will be required to be run when the app is in focus. When the app is in focus they will be required to update the GUI based on the information they receive. Also both tasks task doesn't really have a set finishing condition except for when the user decides to stop the tasks themselves or when the app is completely closed thus they must be able to be cancelled in mid process. These two tasks will very likely be running for a long time.
In summary:
Two background tasks that can be run when app is not in focus.
Both tasks are required to be able to update the GUI when the app is in focus.
Both tasks must be able to be terminated when the user decides to stop the task inside the app or when the app is completely closed.
I believe that I need to using either a Service, IntentService or AsyncTask.
From my reading I believe that I should be using an AsyncTask but I want to be sure before starting.
Service: Can't manipulate GUI.
IntentService: Can't run tasks in parallel, they will be queued on the same thread.
AsyncTask: Seems fine!
Is this correct or should I be using a combination of things somehow?
You misunderstand the point of Service and IntentService. They are not a concurrency mechanism. They will not run automatically in the background. They run on the same thread as your app. If you need concurrency, you need either AsyncTask or Thread. Please note that if you use AsyncTask to get true concurrency between multiple tasks you still need to use executeOnExecutor().
What Services do is persist even when your Activity is gone, or when it isn't in the foreground anymore (either another activity in your app is, or another app is). So if you need your secondary thread to be running after the Activity is finished, you should have it owned in a Service. If you don't, owning it in the Activity is fine.
An IntentService is basically a Service that does more or less fixed length jobs 1 at a time. There's uses for them, but if they need to do network IO or anything like that they still have to spin off AsyncTasks, because they still are run on the main thread.
You should use a service, the purpose of a service is to have a much lesser restricted lifecycle that can run while the app isn't in the foreground. You can use a BroadcastReceiver or callback/AIDL to send messages back to the calling activity that will manipulate the ui.

Is it possible to have a count down timer continue running even after the user has closed the app

Im thinking of having an android app that has a count down timer. However, i need this timer to be running too even if the user kills the app and once the count down timer reaches 00:00:00, it triggers an action regardless of the application being active. Is there a possible solution to that?
Yes it is possible. Just run on background thread so your thread will continue to run even if app is closed.
Using service is a good idea but you have to work in background thread even in service. Because services work in foreground thread by default.
In your case I think the best way to do that is using AlarmManager. Try it.
In Both case (service and alarm) reboot will kill your thread. However you can recreate it. You can use services that will start again if they get killed. Also you can set a BroadCastReceiver that will be called after reboot is complete. So you can recreate your timer in onReceive method.
*
Yes it is possible. use a service , your service will continue to run even if app is closed.
you should call a service using AlarmManager with in a fix time .
*
using services will be the best option for your requirement. OnFinish of the timer, you can trigger your action.

How can I make my app run as a background process

I want to make my app run in the background like a process that runs always.
I need it because I want to get locations update for GPS every 2 minutes (longitude, latitude) and to use the information in a method.
For that I need for the app to be running when the phone is asleep or not in the UI of the app in other words I need the app will run always.
I'm sure that there is a way to make it , thanks anyway for any answers :)
This was just the first google search result I found:
http://www.vogella.com/articles/AndroidServices/article.html
The answer here is to use a service, if this tutorial is lacking there are 6.4 billion others.
We have something like this, but it is made up of several parts.
Firstly you will want your code to run (and be registered in the manifest) as a Service
You will probably also want to request android.permission.RECEIVE_BOOT_COMPLETED so that you can write and register a BroadcastReceiver that gets notified by android.intent.action.BOOT_COMPLETED action and its onReceive method kicks off the service.
In our case we also have a front-end activity which also pokes the service to make sure it is running, but it's been a while snce I checked to see if this was still required.
Our service is nearly empty and onCreate immediately calls a custom Handler which then manages the 'ticks' which wakes the Handler and fires a Runnable if there is work to do, but this is where my code diverges from yours. In our case we only attempt to update the GPS location when the service 'ticks' (usually every minute) and there is work to do. It usually only performs a couple of dozen operations per client per day so I can't really advise on how it will impact battery usage.

Categories

Resources