我使用图像设置为我所有活动的背景但它导致内存溢出问题并使应用程序崩溃.现在我在我的活动中解除暂停()和Destroy()上的drawables,现在按下后退按钮显示空白屏幕.那么如何在不使用额外内存的情况下避免这种情况
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();
}
Run Code Online (Sandbox Code Playgroud)
最初我使用android:background ="@ drawable /"来夸大我的布局,这总是导致内存溢出错误,说VM不会让我们分配10MB(app.)现在我从那个drawable得到一个位图而不缩小和绑定它在运行时.现在它说VM不会让我们分配5MB(app.)而不使用unbindDrawables(..)显然,显示的背景图像的质量已经下降但是我无法理解如果我使用的是png文件为13KB,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); …Run Code Online (Sandbox Code Playgroud) 我想写一个文件,然后从中读取.在使用openFileOutput(..,..)方法时,我得到的方法没有定义,因为它是一个抽象方法.然后我尝试使用getBaseContext()传递上下文; 和警告已关闭,但我没有得到读取输出的结果.我也尝试将上下文作为参数传递给构造函数,但这也没有帮助.我想编写静态方法,这样我就不必每次都实例化类,而静态不是原因,因为我也试过没有它.代码是片段,如下所示.
即使在使用内部存储时,是否还需要指定任何路径?在内部存储上写文件是否需要任何权限?(我已经包含了在外部存储上写入的权限)
public static void write (String filename,Context c,String string) throws IOException{
try {
FileOutputStream fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String read (String filename,Context c) throws IOException{
StringBuffer buffer = new StringBuffer();
FileInputStream fis = c.openFileInput(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
if (fis!=null) {
while ((Read = reader.readLine()) != null) {
buffer.append(Read + "\n" );
}
}
fis.close();
return Read;
}
Run Code Online (Sandbox Code Playgroud)