2

If I want to create a separate thread within a background service(extends Service), will the thread still be able to run when the app is exited(click the home button) or the phone goes to sleep? I want to use the behavior of Service, but my background service is too heavy to on the main thread and is causing frame skips in my UI.

Mike
  • 149
  • 11
  • If your Service extends Android Service then it runs on the main thread by default. How come it's a background service in your case? – Anatolii Jun 20 '18 at 20:13
  • @user8035311 by background service I just mean that it extends Service and has no UI. However, since Service runs on main thread by default it is causing the UI thread to skip frames. I'm asking if there is any way to run Service on a separate thread while still maintaining the properties of continuing to run even if the app is not in the foreground. – Mike Jun 20 '18 at 20:18
  • 1
    If you extend IntentService it will run on a separate thread by default and can continue running if the app is in the background. – Anatolii Jun 20 '18 at 20:23
  • Yes, but IntentService runs the task and exits after it finished. I want the service to run for the entirety of the app lifecycle. – Mike Jun 20 '18 at 22:16

1 Answers1

1

Will the thread still be able to run when the app is exited(click the home button) or the phone goes to sleep?

The Thread can run in the background and also during sleep mode, but the main concern is whether service is allowed to run.

Prior to Android O you could run Service indefinitely in background without any restrictions.

But starting from Android O, X minutes (based on my observations its around 1 - 2 minutes) after your app enters in background all the restrictions for background service will kick in and your Service will be stopped as if you have called Service.stopSelf()

If your intention is:

  • To run the Thread indefinitely, then you should avoid doing it, since it will impact battery life of the device and OS restriction won't permit to do it. You can perform your task periodically using WorkManager which will respect the Doze mode.

  • To ensure one time job started by the app to be executed until finished, then you can create the ForegroundService. Foreground service is Service with notification. You can consider a music player app which can play music even if you dismiss the app and control it through notification.

    You can follow this SO which describes the approach to start ForegroundService in Android O as well as prior versions

Community
  • 1
  • 1
Sagar
  • 23,903
  • 4
  • 62
  • 62