首页 > 解决方案 > 在应用程序关闭并且服务在 bg 中运行后,如何强制执行 Application onCreate?

问题描述

基本上我有一个运行前台服务的应用程序。当我启动应用程序时,我需要在应用程序的onCreate方法中进行特定于会话的初始化。

当我关闭应用程序时,服务会继续运行(期望的行为),但是,当我从启动器/从我的通知中重新打开应用程序时,应用程序onCreate不会再次被调用。

我的问题是:

  1. onCreate即使有服务正在运行,如何强制再次调用应用程序?(服务可能会保留对应用程序对象的引用,对吧?)
  2. 有没有办法在 Application 类中获取应用程序已重新启动但来自服务的指示?
  3. 您还能想到哪些其他解决方案?

我的服务在AndroidManifest.xml

<service android:name=".MyService"
    android:exported="false"/>

我的服务onStartCommand

    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MyActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("My Service")
            .setContentText("Service")
            .setSmallIcon(R.drawable.ic_android)
            .setContentIntent(pendingIntent)
            .build();
    startForeground(1, notification);

标签: androidandroid-serviceandroid-lifecycleandroid-service-bindingandroid-application-class

解决方案


您可以创建一个ProcessLifeCycleOwner内部Application并监听生命周期事件。您可能还需要为一个类设置一个标志并从一个方法中获取该值,以检查用户是否在按下主页按钮或使用通知启动应用程序后返回

class MyApp: Application() {

    override fun onCreate() {
        super.onCreate()

        ProcessLifecycleOwner
            .get()
            .lifecycle
            .addObserver(ApplicationObserver())
    }

    inner class ApplicationObserver : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop() {
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onStart() {

        }

        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate() {

        }


        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy() {

        }
    }
}

推荐阅读