Android:使用高分辨率drawable时极度滞后

时间:2016-02-09 20:36:46

标签: android android-studio

我决定在我的应用程序开头创建一个启动画面。我创建了一个1600x900的图像并将其用作drawable。当我运行我的应用程序时,似乎每个动作都有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>

1 个答案:

答案 0 :(得分:2)

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

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

添加活动,字符串,其他图像和资源,它会更高。

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

您可能正面临其中一个问题,那么您可以做些什么呢?

您没有写它,但我认为启动画面不是您应用的唯一活动。问题是启动画面在后台保持活动状态。你无法真正做任何事情,但你至少可以手动删除drawable。

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?

相关问题