Android 应用程序启动时如何启动服务?

How to start a Service when the Android application is started?

我有背景Service。我希望它的生命周期独立于应用程序的 Activitys.

是的,我知道我必须手动关闭该服务作为应用程序逻辑的一部分。

How to start a Started Service together with the first activity of the Application?

在第一个ActivityonCreate()方法中调用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 class:

在应用程序启动时自动启动 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 class 是应用启动时首先创建的实体之一。这将启动 Service,而不管启动 Activity 是什么。