我使用图像设置为所有活动的背景,但它导致内存溢出问题并使应用程序崩溃。现在,我在活动中的暂停()和销毁()上解除绑定我的可绘制对象,现在按后退按钮时显示空白屏幕。那么如何在不使用额外内存的情况下避免这种情况呢?
protected void onPause(){
super.onPause();
unbindDrawables(findViewById(R.id.login_root));
}
protected void onDestroy() {
unbindDrawables(findViewById(R.id.login_root));
super.onDestroy();
}
private void unbindDrawables(View view) {
System.gc();
Runtime.getRuntime().gc();
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
最初我使用 android:background="@drawable/" 来膨胀我的布局,这总是导致内存溢出错误,说 VM 不会让我们分配 10MB (应用程序)。现在我从该可绘制对象中获取位图,而无需缩小和绑定它在运行时。现在它说 VM 不会让我们在不使用 unbindDrawables(..) 的情况下分配 5MB (app.)
显然,显示的背景图像的质量有所下降,但我无法理解,如果我使用 13KB 的 png 文件,JVM 如何需要 5 或 10MB 的空间来处理请求?
我已将布局语句从 onCreate() 转移到 onResume() 方法,但应用程序在按后退按钮时再次耗尽内存。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onResume(){
setContentView(R.layout.home);
Bitmap bmp;
ImageView background = (ImageView)findViewById(R.id.iv_home_background);
InputStream is = getResources().openRawResource(R.drawable.background);
bmp = BitmapFactory.decodeStream(is);
background.setImageBitmap(bmp);
super.onResume();
}
protected void onPause(){
super.onPause();
unbindDrawables(findViewById(R.id.home_root));
}
private void unbindDrawables(View view) {
System.gc();
Runtime.getRuntime().gc();
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
我已经找到解决这个问题的方法。现在,我在运行时将位图缩放到非常小的尺寸,然后将它们存储在内部存储中。程序在运行时从存储中调用缩放后的位图,如果存储中不存在该位图,则会从可绘制文件夹中调用它,缩放它,将其写入存储中,然后将其绑定到视图。
通过这种方式,无需在任何时间点调用 unbindDrawables 方法,并且应用程序始终保持响应。
我现在唯一关心的是位图的质量,我认为我需要调整缩放尺寸以找出具有最高质量的最小可能尺寸。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)