提问人:Peter Horvath 提问时间:4/21/2022 更新时间:4/21/2022 访问量:119
为什么在 Android Widget Kotlin 中将变量设置回初始值?
Why a variable is set back to initial value in Android Widget, Kotlin?
问:
我创建了一个.它被设置为 的警报接收器。警报来了,函数被调用了。AppWidgetProvider
AlarmManager
onReceived
我有一个私有状态变量,它在声明中作为 -1 启动。它在 onEnabled 函数中设置为 0。它将其值保留在下一个函数中,然后更改回初始化值。onReceive
结果如下:
I/System.out: onEnabled - State: 0
I/System.out: onReceive - state: 0
I/System.out: onReceive - state: -1
I/System.out: onReceive - state: -1
何时以及为何重置该值? 我该怎么做才能在 onReceive 调用之间保持状态变量的值?
package com.example.mywidget
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_MUTABLE
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
class MyWidget : AppWidgetProvider() {
private val STATE_A : Int = 0
private val STATE_B : Int = 1
private val STATE_C : Int = 2
private var state : Int = -1
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
println("onReceive - state: $state")
}
override fun onDisabled(context: Context?) {
super.onDisabled(context)
val alarmManager = context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, MyWidget::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, FLAG_MUTABLE)
alarmManager.cancel(pendingIntent)
println("onDisabled ")
}
override fun onEnabled(context: Context?) {
super.onEnabled(context)
val alarmManager = context!!.getSystemService(Context.ALARM_SERVICE) as AlarmManager
var intent = Intent(context, MyWidget::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, FLAG_MUTABLE)
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, 1000, 10000, pendingIntent)
state = STATE_A
println("onEnabled - State: $state")
}
}
答: 暂无答案
评论
AppWidgetProvider
BroadcastReceiver
SharedPreferences