电池电量永远不会更新

时间:2018-03-18 22:43:11

标签: android kotlin wear-os batterylevel

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

我认为我严格遵循了教程代码。这是我CanvasWatchFaceService.Engine课程的相关部分:

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

1 个答案:

答案 0 :(得分:1)

电池电量取自batteryStatus,仅设置一次。从intent的{​​{1}}参数中取而代之。