android - 有人可以解释 RemoteViews GC 行为吗?

标签 android memory garbage-collection

我有一个下载任务,会定期向通知报告进度。有一段时间我每次都使用一个RemoveView私有(private)成员来更新。

例如:

private RemoteViews mRemoteView;
protected void onCreate(){
    mRemoteView = new RemoteViews( getPackageName(), R.layout.custom_layout )
    contentView.setImageViewResource(R.id.notification_icon, R.drawable.downloads);
    contentView.setTextViewText(R.id.notification_text, "Downloading A File " + (int)( (double)progress/(double)max * 100 ) + "%");
    contentView.setProgressBar(R.id.mProgress, max, progress, false);

    notification.contentView = contentView;
    mNotificationManager.notify(HELLO_ID, notification);
}

protected void onProgressUpdate(Integer... prog) {
    contentView.setProgressBar(R.id.mProgress, max, progress, false);
    mNotificationManager.notify(HELLO_ID, notification);
}

但是,我发现 GC 会不断清理空间,并在很长一段时间内使该应用程序减慢速度。我尝试在每次更新时创建一个新的 RemoteView,这很有效。我想知道这是为什么。我找到了一个链接here这很有帮助,但我正在寻找更多信息。

这是有效的代码:

protected void onProgressUpdate(Integer... prog) {
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
        contentView.setImageViewResource(R.id.notification_icon, R.drawable.downloads);
        contentView.setTextViewText(R.id.notification_text, "Downloading A File " + (int)( (double)progress/(double)max * 100 ) + "%");
        contentView.setProgressBar(R.id.mProgress, max, progress, false);

        notification.contentView = contentView;
        mNotificationManager.notify(HELLO_ID, notification);
    }

最佳答案

您提供的链接对此进行了解释:

RemoteViews 用于在远程进程中创建 View 。实际上它不是一个 View ,而只是一组排队的命令。然后这个队列被序列化,发送到远程进程,反序列化,然后执行这组 Action 。结果是在远程进程中完全构建 View 。

正如链接所解释的:每次您在 RemoteViews 上调用方法时,都会将一个操作添加到其队列中。不幸的是,没有办法清除队列,因此它会不断增长,直到出现 OOM 异常。

现在,队列在内部由数组支持(所有集合也是如此)。当队列填满其内部数组时,它需要创建一个新的更大的数组并复制所有旧数据。然后 GC 清除旧数组。由于RemoteViews内部队列不断增长,因此会创建新数组,并且GC会不断清除旧数组。

关于android - 有人可以解释 RemoteViews GC 行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5097161/

相关文章:

android - 使用 AsyncTask for Android ListView 更新图像缩略图不正确

c++ - 如何更改malloc.c头内容?

windows - 系统如何定义进程获得的虚拟内存部分?

java - 如何修复 "java.lang.OutOfMemoryError at sun.misc.Unsafe.allocateMemory(Native Method)"?

java - UseConcMarkSweepGC 与 UseParallelGC

go - 1600 万个协程 - "GC assist wait"

c# - 在一段代码中暂停 GC

javascript - 是否可以将我为 Android 编写的应用程序部署到 iOS?

java - 我如何启用/禁用 Android 上的以太网连接?

android - Android Room查询对象具有至少一个存在于另一个列表中的项目