Dagger AppComponent 是否在应用程序被杀死后可用

Is Dagger AppComponent available even after app get killed

我刚开始使用 Dagger 库。我创建了一个 AppComponent,其中包含我的房间数据库的一个单例实例。我有一个前台服务,当它的通知按钮被点击时需要向房间数据库写入一些东西。如您所知,即使用户关闭应用程序,用户也始终可以看到前台服务通知,我认为如果我的应用程序被终止,AppComponent 将不再可用。但是现在我可以访问它并在单击服务通知按钮时获取数据库实例,即使我的应用程序已从最近的应用程序中清除。这是我的代码:

Dagger 应用模块:

@Module
class AppModule {

    @Provides
    @Singleton
    fun database(context: Context) = Room
         .databaseBuilder(context, MyDatabase::class.java, "my_db.db").build()

}

Dagger 应用程序组件:

@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance context: Context): AppComponent
    }

    fun getDatabase(): MyDatabase

}

申请class:

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        appComponent = DaggerAppComponent.factory().create(applicationContext)
    }

    companion object {
        lateinit var appComponent: AppComponent
    }
}

前台服务通知:

val intent = Intent(applicationContext, MyBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
    applicationContext,
    0,
    stopIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
)

val notification = NotificationCompat
    .Builder(applicationContext, "channel_id")
    ......
    .addAction(0, "button text", pendingIntent)
    ......
    .build()

广播接收器:

class MyBroadcastReceiver : BroadcastReceiver() {

    @Inject
    lateinit var database: MyDatabase

    override fun onReceive(context: Context?, intent: Intent?) {
        database = App.appComponent.getDatabase()
        //Write something to database
    }
}

即使应用程序被完全杀死,以前的代码也能正常工作。我现在只想知道在应用程序被杀死后我怎么可能访问 appComponent?我使用的是标准溶液吗?我的代码有什么问题吗?有一个更好的方法吗?

正如 EpicPandaForce 在评论中提到的,最近将应用程序刷掉只会杀死任务,不会杀死应用程序进程。无论任务是否被销毁,您的应用程序进程都可以被终止。此外,如果您有前台服务 运行,您就知道该应用尚未被销毁。

这不是您可以访问 Room 数据库的唯一原因。

如果您的广播接收器是运行,那么您的应用已经创建

假设您只有一个没有前台服务的通知。您的应用程序可能会在后台被杀死,但通知仍然存在。如果您现在点击通知上的按钮会发生什么?

Application.onCreate() 的文档所述:

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

Implementations should be as quick as possible (for example using lazy initialization of state) since the time spent in this function directly impacts the performance of starting the first activity, service, or receiver in a process.

当 Android 实例化您的 BroadcastReceiver 时,新创建的 应用程序进程已经调用 App.onCreate(),因此您将可以访问通过 AppComponent.

的新实例到 Room 数据库