我有一个后台服务
。我希望它的生命周期独立于应用程序的 Activity
的生命周期。
是的,我知道我必须手动关闭服务,作为应用程序逻辑的一部分。
最佳答案
How to start a Started Service together with the first activity of the Application?
在第一个Activity
的onCreate()
方法中调用startService(intent)
。
I have a background service. I want its life cycle to be independent of the application activities.
最好的方法是为 Service
创建一个 PendingIntent
并将其注册到 AlarmManager
:
Intent i = new Intent(this, LocationService.class);
PendingIntent pi = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,0,60*60*1000, pi); /* start Service every hour. */
这将确保 Service
定期启动,无论用户是否将应用程序带到前台。
How to start a Service when the Android application is started?
您可以通过扩展 Application
在应用程序启动时自动启动 Service
类:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
startService(new Intent(this, NetworkService.class));
}
}
并使用
修改manifest
中的application
标签
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:name="com.mycompanydomain.MyApp">
这是有效的,因为 Application
类是应用程序启动时首先创建的实体之一。无论启动的 Activity
是什么,这都会启动 Service
。
关于android - Android应用程序启动时如何启动Service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29457604/