android - Android应用程序启动时如何启动Service?

标签 android android-service android-manifest android-lifecycle

我有一个后台服务。我希望它的生命周期独立于应用程序的 Activity 的生命周期。

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

最佳答案

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 在应用程序启动时自动启动 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/

相关文章:

android - 在 Debug模式下运行时未启动通知监听器服务

android - 如何正确使用android.test.ServiceTestCase?

android studio list 文件问题

android - 库项目是否需要在其 AndroidManifest.xml 中包含包名称?

android图像处理教程?

android - 如何设置 Eclipse 的构建配置以生成正确的、可调试的 NDK 应用程序?

Android XmlPullParser 获取标签之间的值

android - 如何从 BroadcastReceiver API 26+ 取消服务

Android - 安装失败,消息为 : INSTALL_PARSE_FAILED_MANIFEST_MALFORMED

android - MPAndroid 条形图的渐变颜色