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?
-
If you want to call service periodically, Use work manager. If you have tried with Work Manager, please post your code. – Pratik Butani Jan 01 '20 at 12:40
-
check out this answer https://stackoverflow.com/a/51360718/2583021 – Atish Agrawal Jan 01 '20 at 13:00
-
WorkManager is the best solution for your requirements. [Sunflower](https://github.com/android/sunflower), a demo app demonstrating best practices with various architecture components, including WorkManager. – Anoop M Maddasseri Jan 01 '20 at 13:28
-
i have used workManager but i had stoped after a short period of time. what i want is for a job to be done forever. – Dayyan Nili Sani Jan 03 '20 at 20:12
3 Answers
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,424
- 2
- 12
- 18
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

- 1
- 2
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.

- 3,236
- 2
- 26
- 32