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.
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With