So I'm not sure where/how to implement this method to make my service run in the foreground. Currently I start my service by the following in another activity:
Intent i = new Intent(context, myService.class);
context.startService(i);
And then in myServices' onCreate() I try the startForeground()...?
Notification notification = new Notification();
startForeground(1, notification);
So yeah I'm a bit lost and unsure of how to implement this.
Solution for Oreo 8.1
I've encountered some problems such as RemoteServiceException because of invalid channel id with most recent versions of Android. This is how i solved it:
Activity:
BackgroundService:
JAVA EQUIVALENT
Handle intent on startCommand of service by using.
This call will remove the service from foreground state, allowing it to be killed if more memory is needed. This does not stop the service from running. For that, you need to call stopSelf() or related methods.
Passing value true or false indicated if you want to remove the notification or not.
Handle your task when on destroy is called by stopSelf().
Create a notification to keep the service running in foreground.
Give a stop button on notification to stop the service when user needs.
In my case It was totally different since I was not having activity to launch the service in Oreo.
Below are the steps which I used to resolve this foreground service issue -
And after that to initiate this service I triggered below cmd -
adb -s " + serial_id + " shell am startforegroundservice -n com.test.socket.sample/.SocketService
So this helps me to start service without activity on Oreo devices :)
From your main activity, start the service with the following code:
Then in your service for
onCreate()
you would build your notification and set it as foreground like so:This is my code to set the service to foreground:
I need to build a notification using PendingIntent, so that I can start my main activity from the notification.
To remove the notification, just call the stopForeground(true);
It is called in the onStartCommand(). Please refer to my code at : https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java
I'd start by completely filling in the
Notification
. Here is a sample project demonstrating the use ofstartForeground()
.