Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a background service on boot in Oreo

I have a very specific use case. I need to start a background service that runs a web server on boot in Android 8. Can anyone recommend a way to achieve this? (In Android O).

It seems that you can't start a background service on boot anymore... Is there another way of doing it? JobService or running a foreground service instead? My code works on Android below 8 but it doesn't seems to work on O.

Manifest:

<receiver android:name=".ServiceStarter" android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>

ServiceStarter (extends BroadcastReceiver):

@Override
public void onReceive(Context context, Intent intent) {
    HTTPServerService.startService(context);
}

HTTPServerService.startService()

context.startService(new Intent(context, HTTPServerService.class));

I've looked on other similar questions but none seem to answer my specific problem. I appreciate any pointers.

like image 750
lsrom Avatar asked Mar 08 '18 09:03

lsrom


People also ask

How do I run a background service?

This example demonstrates how do I run an android service always in 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.

What the background restriction added in Android 8?

With Android 8.0, there is a complication; the system doesn't allow a background app to create a background service. For this reason, Android 8.0 introduces the new method startForegroundService() to start a new service in the foreground.

How do I keep my service alive android?

But in order to keep a service alive like playing a song in a background. You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section. In this way the app will keep alive in background without any interuption.

What is background service app?

A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.


1 Answers

Answer

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    context.startForegroundService(new Intent(context, HTTPServerService.class));
} else {
    context.startService(new Intent(context, HTTPServerService.class));
}

+ permission in AndroidManifest.xml:

<manifest ...>
     ...
     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
     ...
     <application ...>
     ...
</manifest>
like image 192
user924 Avatar answered Oct 28 '22 01:10

user924