android - 在应用程序关闭并且服务在 bg 中运行后,如何强制执行 Application onCreate?
问题描述
基本上我有一个运行前台服务的应用程序。当我启动应用程序时,我需要在应用程序的onCreate
方法中进行特定于会话的初始化。
当我关闭应用程序时,服务会继续运行(期望的行为),但是,当我从启动器/从我的通知中重新打开应用程序时,应用程序onCreate
不会再次被调用。
我的问题是:
onCreate
即使有服务正在运行,如何强制再次调用应用程序?(服务可能会保留对应用程序对象的引用,对吧?)- 有没有办法在 Application 类中获取应用程序已重新启动但来自服务的指示?
- 您还能想到哪些其他解决方案?
我的服务在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);
解决方案
您可以创建一个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() {
}
}
}
推荐阅读
- javascript - 如何在 JavaScript 中检查对象的值?
- javascript - 让数据在 vue 变量值或 0 如果变量不存在
- python - 有没有办法让python程序打开另一个程序?[Python 3.7 聊天室]
- postgresql - Docker/postgres - 无需密码即可访问 psql 的最简单解决方案?
- java - 有没有办法在其实现的接口之一的默认方法中获取对象的类?
- javascript - 如何循环数组中的许多对象
- algorithm - SMA* 算法与理解基本概念有关
- single-page-application - 单页 webapp 中有多个路径的原因是什么?
- salesforce - Salesforce BulkAPI 会破坏数据完整性?
- r - 在二项式 GLMM 中,如何在模型输出中包含所有级别?