Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a background service in Oreo for longer period?

Android Oreo has imposed many restrictions on running background service. Services now don't behave like normal in Oreo as they used to before.

But what if I have to run a service in background for long periods of time.

I am developing an application to launch the flashlight when user shakes the phone. To achieve this I will have to put the Sensor listener code inside a service.

How do I prevent android system to not kill the service.

PS: I don't want to start a foreground service with a notification.

like image 468
Gurleen Sethi Avatar asked Feb 26 '18 20:02

Gurleen Sethi


People also ask

How do you run background services in Android Oreo?

By using startForegroundService() method you grant that permission to run the service in background even when the activity isn't running. Must also once the service has been created, the service must call its startForeground() method within five seconds. Show activity on this post.

How do I create a service that runs in the background?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user click on text view, it will start service and stop service.


1 Answers

I discovered that we can run forground service without showing notification for android oreo and above, here is the solution first create notification with notification Channel also set channel id for notifications then start forground service with notification. now it's time to cancel notification Channel with id after 1 or 2 second that's means the notification will remove and the service will run alwayes . that's all

like image 174
Nhatty Birhanu Avatar answered Sep 20 '22 17:09

Nhatty Birhanu