2013年9月10日星期二

Android how to solve it , but use a picture memory leak problem then ?

Internet search a bit , Android assigned to the picture but the memory is only 8M, so when a lot of pictures to use but when designed into the memory leak problem , the Internet is just a simple but say you want to recycle () it , it was in use Bitmap , it is then If you did not use the picture when it comes to Bitmap ?
The following is a program that you can run , but if more pictures will be a memory leak , how to solve it

package com.loulijun.imageswitcher;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class ImageSwitcherActivity extends Activity implements ViewFactory {
    private ImageSwitcher is;
    private Gallery gallery;
    //图片资源
    private Integer[] thumbs = {
     R.drawable.yuanyuan01,
     R.drawable.yuanyuan02,
     R.drawable.yuanyuan03,
     R.drawable.yuanyuan04,
     R.drawable.yuanyuan05,
     R.drawable.yuanyuan06,
     R.drawable.yuanyuan07,
     R.drawable.yuanyuan08
    };
    
    private Integer[] imgIds = {
     R.drawable.yuanyuan01,
     R.drawable.yuanyuan02,
     R.drawable.yuanyuan03,
     R.drawable.yuanyuan04,
     R.drawable.yuanyuan05,
     R.drawable.yuanyuan06,
     R.drawable.yuanyuan07,
     R.drawable.yuanyuan08
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置为全屏模式
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        is = (ImageSwitcher)findViewById(R.id.switcher);
        is.setFactory(this);
        //淡入淡出
        is.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
        is.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
        
        gallery = (Gallery)findViewById(R.id.gallery);
        gallery.setAdapter(new ImageAdapter(this));
        gallery.setOnItemSelectedListener(new Gallery.OnItemSelectedListener()
        {

public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
is.setImageResource(imgIds[arg2]);

}

public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
        
        });
    }
public View makeView() {
ImageView i = new ImageView(this);
  i.setBackgroundColor(0xFF000000);
  i.setScaleType(ImageView.ScaleType.FIT_CENTER);
  i.setLayoutParams(new ImageSwitcher.LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
  return i;
}
public class ImageAdapter extends BaseAdapter
{
//重写构造方法
private Context context;
public ImageAdapter(Context c)
{
context = c;
}

//返回图片的个数
public int getCount() {
// TODO Auto-generated method stub
return thumbs.length;
}

public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView(context);
iv.setImageResource(thumbs[position]);
iv.setAdjustViewBounds(true);
iv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

return iv;
}

}

}

------ Solution ------------------------------------- -------
soft references can reduce the fail rate it a try



/**
 * 该类演示了Soft Reference的应用
 */
package cn.javatx;

import java.lang.ref.SoftReference;


public class softReference {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        A a = new A();
        
        //使用a
        a.test();

        //使用完了a,将它设置为soft引用类型,并且释放强引用
        SoftReference sr = new SoftReference(a);
        a = null;
        
        //下次使用
        if (sr != null) {
            a = (A)sr.get();
            a.test();
        } else {
            //GC由于低内存,已释放a,因此需要重新装载
            a = new A();
            a.test();
            a = null;
            sr = new SoftReference(a);
        }
    }

}

class A {
    public void test() {
        System.out.println(&quot;Soft Reference test&quot;);
    }
}


------ Solution ------------------------------------- -------
public View getView (int position, View convertView, ViewGroup parent) {
ImageView iv = new ImageView (context);
iv.setImageResource (thumbs [position]);
iv.setAdjustViewBounds (true);
iv.setLayoutParams (new Gallery.LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

question here , you have every getView generate a new Imageview, ImageView iv = new ImageView (context);
and you have no way to set null.

can do:

public View getView (int position, View convertView, ViewGroup parent) {
ImageView iv = (ImageView) convertView;
if (iv == null) {
iv = new ImageView (context ) ;
iv.setAdjustViewBounds (true);
iv.setLayoutParams (new Gallery.LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams. WRAP_CONTENT));
}
/ / here should first see if the picture does not change can be returned directly to enhance the efficiency of lazy ^ _ ^
Bitmap oldBp = (Imageview) iv.getTag ();
if (oldBp! = null && oldBp.isRecycled ()) {
oldBp.recycle ();
}
Bitmap newBp = BitmapFactory.decodeResource (getResources (), thumbs [position]);
iv .. setImageBitmap (newBp);
return iv;
}
------ Solution ------------------- -------------------------

private Bitmap decodeFile(File f)
{     
try {         
//Decode image size         
BitmapFactory.Options o = new BitmapFactory.Options();        
o.inJustDecodeBounds = true;        
BitmapFactory.decodeStream(new FileInputStream(f),null,o);          
//The new size we want to scale to         
final int REQUIRED_SIZE=500;          
//Find the correct scale value. It should be the power of 2.        
int width_tmp=o.outWidth, height_tmp=o.outHeight;         
int scale=1;        
while(true){             
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)                 
break;             
width_tmp/=2;           
height_tmp/=2;          
scale*=2;        
}         
//Decode with inSampleSize        
BitmapFactory.Options o2 = new BitmapFactory.Options();        
o2.inSampleSize=scale;        
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);    

catch (FileNotFoundException e) {   
return null; 

}

------ For reference only ------- --------------------------------
good question
Non Bitmap image is too large due to excessive memory leak solutions collection

------ For reference only ---------------------------------- -----
attention Citie .........
------ For reference only ------------------ ---------------------
this code can not see where you are in the running memory leak memory has been found to increase until OOM error , or a start , they reported OOM mistake.
------ For reference only -------------------------------------- -
look . . . . .
------ For reference only -------------------------------------- -
virtual machine memory is managed automatically , no timely recovery , while demand is increasing memory . . . Casual . . .
------ For reference only -------------------------------------- -

one starts running when there is no problem, but click a few pictures in the Gallery after the wrong
error is:
dalvikvm.3775488-byte external allocation too large for this process
Graphics VM won't let us allocate 3775488 bytes

I removed a couple of the big picture , it can barely run, but in practice this is not enough ah
------ For reference only ---------- -----------------------------
encountered a large garden in the blog god, but just tell me you can use the following method
write a global resource management class, with Map and soft references to save these pictures resource , rather than a direct reference to the resource file
But honestly , I do not understand , you who understand that the next
------ For reference only -------------------- -------------------
gorgeous Bangding
------ For reference only ---------------------------------------
click System to track changes in the memory . out.println (Runtime.getRuntime (). totalMemory ()); this value will not be much change in operation that no memory leaks .

This is only needed when you click on the picture to turn into a bitmap resources for less than a memory , 8M bit smaller a large image into a bitmap are several M debugging time can be set / system / build.prop this file dalvik.vm.heapsize set bigger.

------ For reference only ---------------------------------- -----
gorgeous Bangding ~ ~ ~
------ For reference only ------------------------ ---------------
concern Citie , learn together ^ ^ ^ ^
------ For reference only ---------- -----------------------------
image processing compressed about it ?
------ For reference only -------------------------------------- -
professionals to understand it

------ For reference only ---------------------------------- -----
Replies can get 10 points a day available points ! Tips :
------ For reference only ----------------------------------- ----
also have this problem !!!
------ For reference only ------------------------ ---------------
learned
------ For reference only ------------------ ---------------------
learn.
------ For reference only -------------------------------------- -
come to learn
------ For reference only -------------------------------- -------
  This reply was moderator deleted at 2011-11-24 11:31:21

------ For reference only ---------------------------------- -----
explain good
------ For reference only ---------------------------- -----------
every day with 10 points
------ For reference only -------------------- -------------------
see everyone solution
------ For reference only ------------ ---------------------------

concern Citie
------ For reference only - --------------------------------------
  This reply was moderator deleted at 2012-08-28 09:13:21

------ For reference only ---------------------------------- -----
last encountered this problem, but also did not get


The final solution is to compress the art picture quality , and can not be used as a JPG compressed format JPG itself with time will decode it.


There is a direct reference to the time, in fact, is the background bitmap decoding through the





I'm limited, said a rough guess the meaning of the man of God who is not to write directly R.drawable.xxx such a reference , write a class directly through bitmap loading, and then manage their own resources to read and release. Give Program " reference ."

But the last time we tried this , picture resources is large enough , here is say a single image is too large , or too many pictures exist , or will this problem is still not resolved
--- --- For reference only ---------------------------------------
concern , learning .
------ For reference only -------------------------------------- -
top one, learn
------ For reference only ----------------------------- ----------
sustained attention in
------ For reference only ---------------------- -----------------
continue to look at !
------ For reference only -------------------------------------- -
Thank you. Good stuff. Are learning , helpful
------ For reference only -------------------------------- -------
this useful, powerful !
------ For reference only -------------------------------------- -
eh , resource not give ah
------ For reference only -------------------------- -------------
next concern is with the recyle I generally paid more
------ For reference only -------- -------------------------------
soft references are the java SoftReference, android source code , there are many places soft application , you can refer to.
------ For reference only -------------------------------------- -
learning learn
------ For reference only ------------------------------ ---------
or playing C in cool
own memory management , there is somehow compromised, and then take control of everything .
------ For reference only -------------------------------------- -

because Android was introduced in C, which leads to memory leaks . JAVA set of virtual machines automatically reclaims memory
------ For reference only ------------------------------ ---------
studied . Increase their knowledge of
------ For reference only ----------------------------------- ----
learn !!!!!
------ For reference only ------------------------- --------------
Bangding , learning a ~ ha ha
------ For reference only -------------- -------------------------
not a very good solution to this problem ....
------ For reference only ---------------------------------------

Android also has a virtual machine , also automatic recovery , and C does not matter. Mobile resources are already strained , get hold of the virtual machine no problem, but also put forward a memory no control .
so-called garbage collection , and WC, almost , had pulled a punch using the toilet on the line, automatic recovery of it, do your own advantage is rushed , there are experts to help you looked after . In fact, originally justified in China , a large public places toilets are dirty , nobody cleaned really not. But if every family to help you arrange a full- flush toilets , Java , the father of the rich and powerful , but also not afraid of trouble, asked him once every few seconds : Shangwancesuo No, he loved it. But the phone does not like it, you do not trouble trouble Ah , what is broken toilet , I look to you vent .
------ For reference only -------------------------------------- -
well, I come and collect points.
------ For reference only -------------------------------------- -
attention. . . .
------ For reference only -------------------------------------- -
attention. . . . . . .
------ For reference only -------------------------------------- -


Well, thank you ha
------ For reference only ------------------------------ ---------
not read but would like to learn next
------ For reference only -------------- -------------------------
lz code have a little problem , when you pass Context to pass ApplicationContext, rather than directly to the Activity pass inside. So easily cause the entire Activity leaks.
recommended lz look at the Android SDK documentation resources \ articles \ avoiding-memory-leaks.html

sometimes OOM is not necessarily a memory leak , but may be too big picture , when decoding , the need for down-sampling .
------ For reference only -------------------------------------- -
look . . . .
------ For reference only -------------------------------------- -


a picture 3.7M, lz using much pictures ah. . .
Do not use R. drawable, use Bitmap.
decoding must be down-sampling , and color space set to RGB565. After use must be promptly recycle.

someone said Soft / Weak Reference has some effect, but this is the system control , there is no better time to release their own controls what .
------ For reference only -------------------------------------- -
mark look good deep
------ For reference only ----------------------------- ----------
public View getView (int position, View convertView, ViewGroup parent) can try to tag the way .
------ For reference only -------------------------------------- -
is a picture over the General Assembly overflow ? Still pictures more will overflow ?

or more places with pictures will overflow ?

50 House said , do not R.drawrable, use bitmap What does it mean ?

introducing an image , you need to decode decode only once, after just a reference object references , do not take up too much memory , right ?


------ For reference only ---------------------------------- -----
focus attention
------ For reference only ---------------------------- -----------



cow !!!
------ For reference only ------------------------------ ---------
top top
------ For reference only ---------------------- -----------------
not how attention to this problem !
------ For reference only ---------------------------------------
study, study .. .
------ For reference only ------------------------------------- -
attention. . . . . . . . . . . . .
------ For reference only -------------------------------------- -
  This reply was moderator deleted at 2011-07-29 10:25:37

------ For reference only ---------------------------------- -----
BitmapFactory.Options m_BitmapOpt = new BitmapFactory.Options ();

byte [] m_decodeBuffer = new byte [1024 * 1024 * 5]; / / cache 5M

Bitmap bmpBg = BitmapFactory.decodeResource (getResources (), R.drawable.main_bg, m_BitmapOpt);

there's several functions and classes, you can take a look at the sdk inside , do not explain.
------ For reference only -------------------------------------- -
memory leak is the right place
new Gallery.LayoutParams (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)

refreshed every getView had new object
LayoutParams trying to define a global object is initialized only once , try. . .
other places where there are frequent new are corrected below to see will not disclose
------ For reference only ---------------- -----------------------
concern
------ For reference only ---------------------------------------
+1 this very might ah
------ For reference only ------------------------------------ ---
Well, thank you ha , in fact, I just put this question, and this is just a test program, because the future will inevitably encounter due to image resources caused memory leaks , where they want this memory leaks and possible solutions to find out, in case you someday encounter
------ For reference only ------------------- --------------------
strong top look
------ For reference only ----------- ----------------------------
Gallary ah ah nothing ScrollView fly 34 F and 61 House of Big Brother said, well ah SoftReference good use before it overflows it will help you reclaim land
------ For reference only ---------- -----------------------------
picture in the local Fortunately once fetched from the server if the words ; does not recommend more than two pictures to make Gallary words will collapse miserably . .
------ For reference only -------------------------------------- -
I have also encountered this problem , listview bitmap loaded inside too much , leading to memory overflow ......
------ For reference only ----------- ----------------------------
learn. . . . . . . . .
------ For reference only -------------------------------------- -

ls can count on , now mobile phones frequently 800W 1200w pixels , 8M ~ 12M pixels , even RGB565, each pixel also need two bytes, even if it is exaggerated RGBA8888 . A picture is sufficient OOM.
R.drawable direct solution map , did not do scaling , can only be used to display a small icon, display photos in the Gallery certainly not .

public static Bitmap createFitinBitmap(String path, int fitinWidth, int fitinHeight) {
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
int sampleSize1 = opts.outWidth / fitinWidth;
int sampleSize2 = opts.outHeight / fitinHeight;
opts.inSampleSize = sampleSize1>sampleSize2? sampleSize1 : sampleSize2;
opts.inJustDecodeBounds = false;
        opts.inDither = false;
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(path, opts);
}

------ For reference only ----------------------------------- ----
  This reply was moderator deleted at 2011-07-29 17:22:28

------ For reference only ---------------------------------- -----

on Android, not superstition GC, static storage , circular references , ActivityContext may cause memory leaks.
especially the Android Activity mechanisms . Many beginners will Activity as a Context parameter passed around , after exiting the process has not been killed. At this time may cause the entire Activity can not be released , continuous entry and exit procedures , it is easy OOM.
------ For reference only -------------------------------------- -
this should be related to memory management problem, right ?
Although the following link says the bitmap 's , but cause of the error as it should , please have a look
http://yekmer.posterous.com/android-memory-management
- ----- For reference only ---------------------------------------

determine the current position of the ListView only solution currently displayed diagram ( can be added to the pre- reading mechanism ) , all the other recycle.
------ For reference only -------------------------------------- -
android memory resource itself is very tight , it is recommended not to use the big picture
------ For reference only --------------------- ------------------
learn

------ For reference only ---------------------------------- -----
forehead , well advanced , mark the first
------ For reference only ----------------------- ----------------
learn ! !
------ For reference only -------------------------------------- -
Bird Brother of the Linux private kitchens . part2
------ For reference only -------------------------- -------------
not tried this , F, Z can see for yourself that
------ For reference only ---------- -----------------------------

can say a specific point? This problem has troubled me for days ...... has not solved
------ For reference only ------------------------- --------------
learning !
------ For reference only -------------------------------------- -
thumbnail browsing, available mipmap technology, large map browsing, then load the image, can save a lot of memory. Hope to help you
------ For reference only ---------------------------------- -----
novice learning
------ For reference only ---------------------------- -----------
was concluded bound Android defects and traps it
------ For reference only --------------- ------------------------


page is reset date
------ For reference only ---------------------------- -----------
can indeed get
------ For reference only -------------------- -------------------
Bangding learning
------ For reference only ----------- ----------------------------
android learn?
------ For reference only -------------------------------------- -
concern ing
------ For reference only -------------------------------- -------
android virtual machines do not have , how there will be a memory overflow Yeah ! ! ! !
------ For reference only -------------------------------------- -

1. specific code I do not have a very simple principle . Get the current ListView's scroll position , the solution currently displayed diagram does not show the entire recycle.
2. anyway not original solution , only a small map solution , code ls has already been given .
as long as two , or at least show a two hundred pictures, if the picture is too many , we must consider a a .
------ For reference only -------------------------------------- -
ImageView memory leak .
------ For reference only -------------------------------------- -
soft references in memory is tight , the first thing to consider is recycled . We usually build objects are strong references . Soft references are generally used for caching , where the use of pictures is to use soft references can to some extent alleviate the problem of the shortage of memory .
------ For reference only -------------------------------------- -
concern · · · · · · · ·
------ For reference only ---------------- -----------------------
on android know much about learning

没有评论:

发表评论