电池电量永远不会更新

Battery level is never updated

我想在我的表盘上显示当前手表电池电量。虽然该值只确定一次,然后正确显示在我的表盘上,但该值永远不会更新。显示新值的唯一方法是通过 Android Studio 重新安装 APK 或先选择另一个表盘。

我想我严格按照教程代码进行了操作。这是我的 CanvasWatchFaceService.Engine class:

的相关部分
inner class Engine : CanvasWatchFaceService.Engine() {
    private lateinit var batteryBroadcastReceiver: BroadcastReceiver
    private lateinit var batteryStatus: Intent
    private var watchBatteryLevel: Int = -1

    override fun onCreate(holder: SurfaceHolder) {
        super.onCreate(holder)
        setWatchFaceStyle(WatchFaceStyle.Builder(this@MyWatchFaceService)
                .setAcceptsTapEvents(true)
                .build())
        val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        batteryBroadcastReceiver = object: BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                watchBatteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                invalidate()
            }
        }
        batteryStatus = registerReceiver(batteryBroadcastReceiver, intentFilter)
    }

    override fun onDestroy() {
        mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME)
        unregisterReceiver(batteryBroadcastReceiver)
        super.onDestroy()
    }

    override fun onDraw(canvas: Canvas, bounds: Rect) {
        val batteryText = String.format("%d %%", watchBatteryLevel)
        canvas.drawText(batteryText, width * 0.5f, width * 0.15f, mBatteryPaint)
    }
}

电池电量取自batteryStatus,仅设置一次。从onReceiveintent参数中取而代之。