Possible Duplicate:
Can I startService from Application#onCreate()?
我们可以从应用程序类启动服务吗?
我想在我的应用程序启动时启动一个服务。因此,我可以为此使用我的应用程序类,而不是从启动 Activity 启动服务吗?谢谢。
我尝试的是内部应用程序类:
public void onCreate() {
super.onCreate();
Log.i("Logger", "Service Starting");
Intent errorLoggerService = new Intent(getApplicationContext(),
ErrorLoggerService.class);
getApplicationContext().startService(errorLoggerService);
}
是的,您可以在 API 标签 26 之前这样做,但现在不行了。
如果你的API版本低于26
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
startService(new Intent(this, MyService.class));
}
}
编辑
不要调用 getApplicationContext(),只调用 startService()。此外,请确保您已在 list 中声明该服务。
API 标签 26 及以上
编辑 2
来自官方谷歌文档:https://developer.android.com/guide/components/services.html#StartingAService
注意:如果您的应用以 API 级别 26 或更高级别为目标,除非应用本身位于前台,否则系统会对使用或创建后台服务施加限制。如果应用程序需要创建前台服务,则应用程序应调用 startForegroundService()。该方法创建了一个后台服务,但该方法向系统发出信号,表明该服务会将自己提升到前台。创建服务后,服务必须在五秒内调用其 startForeground() 方法。
因此,现在您无法从应用程序启动后台服务。只有 GUI 组件能够启动后台服务。
或者,您可以从应用程序等后台组件启动前台服务。