我需要在用户终止应用程序并建立网络连接时显示通知。到目前为止,我正在使用此代码,并且效果很好!
class MyJobService : JobService() {
override fun onStartJob(job: JobParameters): Boolean {
Log.w("This loggs out when user receives network", "I want to show notification")
return false // Answers the question: "Is there still work going on?"
}
override fun onStopJob(job: JobParameters): Boolean {
return false // Answers the question: "Should this job be retried?"
}
这是调度员
val dispatcher = FirebaseJobDispatcher(GooglePlayDriver(context))
val myJob = dispatcher.newJobBuilder()
.setService(MyJobService::class.java)
.setLifetime(Lifetime.FOREVER)
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
.setTag("UniqueTagForYourJob")
.setReplaceCurrent(true)
.setRecurring(false)
.setTrigger(Trigger.executionWindow(0, 10)) .setRetryStrategy(RetryStrategy.DEFAULT_LINEAR) .setConstraints(Constraint.ON_ANY_NETWORK)
.setExtras(myExtrasBundle)
.build()
dispatcher.mustSchedule(myJob)
现在此代码将打开应用程序。我认为主要情况之一是onStartJob在主线程上工作。但是我只需要在网络恢复时显示通知,而无需打开应用程序。 如果您还有其他解决方案,那么我很乐意知道:)