【问题标题】:Android: Extreme lag when using high-resolution drawablesAndroid:使用高分辨率绘图时极度滞后
【发布时间】:2016-05-20 00:11:03
【问题描述】:

我决定在我的应用开始时创建一个启动画面。我创建了一个 1600x900 的图像并将其用作可绘制对象。当我运行我的应用程序时,似乎每个动作都有 1 秒的延迟。检查完所有内容后,我意识到这是闪屏以某种方式导致了这种滞后。测试表明,以这种方式制作成可绘制对象的高分辨率图像会导致延迟,我不知道为什么。

我的图像重 100kb,我逐渐降低了分辨率和大小,延迟也逐渐降低。我还制作了一张 5kb 的高分辨率图像,并且延迟仍然存在,这意味着分辨率主要是罪魁祸首。

为什么会发生这种情况,我怎样才能在没有后续影响的情况下创建启动画面?

代码:

风格:

<style name="splashscreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowBackground">@drawable/splashscreen</item>
    </style>

在清单中:

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:fullBackupContent="false"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:label="@string/app_name"
            android:theme="@style/splashscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

【问题讨论】:

  • 您在什么设备上看到此行为?
  • 您应该使用 Glide 库并使用 Glide Glide.with(container.getContext()).load(R.drawable.splashscreen).crossFade().into(imageView); 将图像资源加载到您的 ImageView

标签: android android-studio


【解决方案1】:

您遇到的延迟可能是由于垃圾收集或堆大小增加。

你的头像是1600*900 = 1440000px。每个像素的内存大小为 4 字节——每种颜色一个 (RGB),一个用于透明度 (A)。因此,我们可以计算出:1440000 * 4B = 5760000B,因此在堆上仅为字节数组分配了大约 5.7 MB。但它是可绘制的,并且比字节数组有更多的字段,所以你最终会得到更多。

添加活动、字符串、其他图像和资源,它要高得多。

现在,每当您创建一个新对象时,VM 都会尝试删除一些未使用的对象(垃圾收集),从而导致小的延迟。如果它不能释放足够的内存,堆将会增加(也会导致小的延迟)。

您可能正面临这些问题之一,那么您能做些什么呢?

不是你写的,但我认为闪屏不是你应用的唯一 Activity。问题是启动画面在后台保持活动状态。您对此无能为力,但您至少可以手动删除可绘制对象。

View window = getWindow().getDecorView();
if (window.getBackground() != null) {
    window.getBackground().setCallback(null);
    window.setBackground(null);
}

一般来说,最好不要在 xml 属性中使用大图像。以您真正需要的大小自己创建位图会更节省内存(并非所有设备都具有 1600*900 分辨率)。

Android 为您提供了 BitmapFactory 类来执行此操作。查看Pre-scaling BitmapsMost memory efficient way to resize bitmaps on android? 了解有关整个主题的更多信息。

【讨论】:

  • 虽然我不确定您的尺寸计算(我的图像是压缩的 jpg(也许您在谈论 Android 如何保存它们?))将背景设置为 null 确实可以解决它。非常感谢!
  • @JohanZ。是的,压缩无关紧要。这只是像素。 ARGB 中的一个像素是 4 字节。你对此无能为力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 2014-11-20
相关资源
最近更新 更多