Starting a service from application class

Yes, you could do this before API Label 26 but not anymore.

If your API version is less than 26

public class MyApplication extends Application {
    public void onCreate() {
        super.onCreate();
        startService(new Intent(this, MyService.class));
    }
}

EDIT Don't call getApplicationContext(), just call startService(). Also, make sure you've declared the service in your manifest.

For API label 26 and above

EDIT 2 From official Google Docs: https://developer.android.com/guide/components/services.html#StartingAService

Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground. Once the service has been created, the service must call its startForeground() method within five seconds.

So, these days, you can't start a background service from Application. Only GUI components are able to start background service.

Or, you can start a foreground service from background components like Application.

Tags:

Android