PendingIntent正在填充内存

时间:2019-01-14 03:49:29

标签: android performance

我正在构建一个使用前台服务来显示简单计时器的应用程序,该计时器在通知中递减计数。我将PendingIntent与通知生成器一起使用,以允许用户在点击通知时返回到应用程序。

一切正常,但每次计时器计时结束时,似乎都会向缓存中添加新的PendingIntent,这将占用更多的内存。

D/Notification( 9964): allPendingIntents
D/Notification( 9964): allPendingIntents
D/Notification( 9964): allPendingIntents
D/Notification( 9964): allPendingIntents
I/zygote64( 9964): Do partial code cache collection, code=30KB, data=25KB
I/zygote64( 9964): After code cache collection, code=30KB, data=25KB
I/zygote64( 9964): Increasing code cache capacity to 128KB
D/Notification( 9964): allPendingIntents

我不确定如何使它停止增加缓存的内存分配。随着时间的流逝,它变得越来越高。下面是我的计时器类,这是问题的根源。我在做什么错了?

class TestCountDownTimer(millisInFuture: Long, countDownInterval: Long,
                               private val foregroundService: ForegroundService) : CountDownTimer(millisInFuture, countDownInterval) {


    private val notificationBuilder = NotificationCompat.Builder(foregroundService, Application.CHANNEL_ID).apply {
        val notificationIntent = Intent(foregroundService, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(foregroundService, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT)

        setContentTitle("test")
        setSmallIcon(R.drawable.app_icon)
        setContentIntent(pendingIntent)
        setOngoing(true)
    }

    private val countdownIntent: Intent = Intent().apply { action = KEY_BROADCAST_COUNTDOWN }
    private val notificationManager = foregroundService.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    private var isFirstTick = true


    override fun onTick(millisUntilFinished: Long) {
        val timeLeftSeconds = truncate(millisUntilFinished.toDouble() / 1000)

        val hours = truncate(timeLeftSeconds / 60 / 60).toInt()
        val minutes = (truncate(timeLeftSeconds / 60) % 60).toInt()
        val seconds = (timeLeftSeconds % 60).toInt()

        val timeString = "${hours}h : ${minutes}m : ${seconds}s"


        notificationBuilder.setContentText(timeString)
        foregroundService.startForeground(1, notificationBuilder.build())

        countdownIntent.putExtra(KEY_COUNTDOWN_VALUE, timeString)
        foregroundService.sendBroadcast(countdownIntent)
    }

    override fun onFinish() {

    }
}

0 个答案:

没有答案