为什么在 Android Widget Kotlin 中将变量设置回初始值?

Why a variable is set back to initial value in Android Widget, Kotlin?

提问人:Peter Horvath 提问时间:4/21/2022 更新时间:4/21/2022 访问量:119

问:

我创建了一个.它被设置为 的警报接收器。警报来了,函数被调用了。AppWidgetProviderAlarmManageronReceived

我有一个私有状态变量,它在声明中作为 -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")
    }
}
Android Kotlin 小部件

评论

1赞 Mike M. 4/21/2022
安只是一个专门的.当您在清单中注册一个实例时,系统会处理其实例的创建,并为每个广播创建一个新实例。您无法在实例字段中维护广播之间的状态。你需要一些其他机制;例如,数据库、文件等。AppWidgetProviderBroadcastReceiverSharedPreferences
0赞 Peter Horvath 4/22/2022
谢谢马克的回答。我更改为 Handler-Runnable。它按照我的需要工作

答: 暂无答案