匕首AppComponent在应用被杀后还能用吗?

问题描述 投票:0回答:1

我刚刚开始使用Dagger库。我创建了一个AppComponent,在这个AppComponent中,我持有一个房间数据库的单人实例。我有一个前台服务,当它的通知按钮被点击时,它需要向房间数据库写入一些东西。如你所知,即使用户关闭应用程序,前台服务的通知对用户始终可见,我想如果我的应用程序被杀死,AppComponent将不再可用。但是现在,当服务通知按钮被点击时,我可以访问它并获得数据库实例,即使我的应用程序已经从最近的应用程序中被清除。这是我的代码。

Dagger应用模块:

@Module
class AppModule {

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

}

Dagger App Component:

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

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

    fun getDatabase(): MyDatabase

}

应用类:

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()

BroadcastReceiver:

class MyBroadcastReceiver : BroadcastReceiver() {

    @Inject
    lateinit var database: MyDatabase

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

之前的代码即使在应用被完全杀死的情况下也能完美地工作,但现在我想知道如何在应用被杀死后访问appComponent?我现在只想知道如何在应用被杀死后访问appComponent?我使用的是标准的解决方案吗?我的代码有什么问题吗?有什么更好的方法吗?

android android-service android-room dagger-2 dagger
1个回答
2
投票

正如EpicPandaForce在评论中提到的那样,在recents中刷走应用只能杀死任务,而不是应用进程。 无论任务是否被销毁,你的应用进程都可以被杀死。 此外,如果你有一个前台服务在运行,你就知道应用还没有被销毁。

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

如果你的广播接收器正在运行,那么你的应用程序已经被创建了。

假设你只是有一个通知,没有前台服务。 有可能你的应用会在后台被杀掉,而通知还在。 如果你现在点击通知上的按钮会发生什么?

正如文档中所说的 Application.onCreate():

在应用程序启动时,在任何活动、服务或接收器对象(不包括内容提供者)被创建之前调用。

实现应该尽可能快(例如使用状态的懒惰初始化),因为在这个函数中花费的时间直接影响到启动进程中第一个活动、服务或接收器的性能。

当Android实例化你的 BroadcastReceiverజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ 新造 申请过程中已经调用 App.onCreate()因此,您将可以通过新的 AppComponent.

© www.soinside.com 2019 - 2024. All rights reserved.