Nirmal Prajapat
Nirmal Prajapat

Reputation: 1817

Service in Oreo

I am working on an application(minSDK = 19 & targetSDK = 26) in which there are 20 services for e.g. services like MediaPlayer, SyncUpData and SyncDownData etc. As Android O doesn't allow long running background services. I'm quite confused that what to choose between JobScheduler, FirebaseJobDispature, JobIntentService etc. because JobShecduler introduced in API 21 and FirebaseJobDispature in API 14.

Another question is how to check which services are need to be replaced with above framework and which are not.

There are 3 services that should be running even if the application is not visible because these service sends/receives data packets to/from bluetooth device. They will stop running either on application kill or manually disconnects the connection.

I know there are lots of solution online but I'm confused which I should use.

Please suggest the suitable solution for this. TIA

Upvotes: 0

Views: 287

Answers (1)

Perraco
Perraco

Reputation: 17360

The best thing to use is the new WorkManager library. It wraps all the possible API level scenarios:

  • Uses JobScheduler for API 23+
  • For API 14-22 If using Firebase JobDispatcher in the app and the optional Firebase dependency, uses Firebase JobDispatcher
  • Otherwise, uses a custom AlarmManager + BroadcastReceiver implementation

In addition, here some literature and usage examples for it.

The WorkManager use case is only for background jobs which require guaranteed execution, even after the app gets killed.

If instead you need a Foreground service, then is as simple as creating it yourself by extending the Service class. For Oreo you will need to show a UI notificaiton. Then the service can be started as foreground with the next call:

ContextCompat.startForegroundService(context, yourService);

Though if the service lives only while the app is active, and stopped manually through the app or whenever the app exists, then instead you should consider using a Thread and not a service.

Quote from the android documentation:

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

Upvotes: 2

Related Questions