Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting a service from application class [duplicate]

Tags:

android

Possible Duplicate:
Can I startService from Application#onCreate()?

Can we start a service from the application class?

I want to start a service when my application starts. So instead of starting the service from the starting activity, can I use my application class for this? Thanks.

What I tried is Inside application class :

public void onCreate() {
    super.onCreate();


    Log.i("Logger", "Service Starting");
    Intent errorLoggerService = new Intent(getApplicationContext(),
            ErrorLoggerService.class);
    getApplicationContext().startService(errorLoggerService);
}
like image 305
Eldhose M Babu Avatar asked Sep 12 '12 05:09

Eldhose M Babu


1 Answers

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.

like image 153
LuxuryMode Avatar answered Sep 20 '22 11:09

LuxuryMode