Androidプログラミングのメモリオーバーフロー解決策(OOM)の実例をまとめます。


本論文の例は、Androidプログラミングのメモリオーバーフロー解決策(OOM)をまとめたものである。皆さんに参考にしてあげます。具体的には以下の通りです。
最近作った工事の中でロードされた写真が多すぎたり、写真が大きすぎたりした時、よくOOM問題が発生しました。インターネットの資料を探して、いろいろな方法を提供しましたが、自分はちょっと乱れていると感じました。特に、今日は違うタイプのAndroid携帯でテストをしました。効果もあります。自分自身の後でOOM問題を解決する上で向上しました。前もって言ってください。幅が少し長いです。関連するものが多すぎます。みんなが根気よく見て、必ず収穫があります。中の多くのものは馬さんもネット資料を参考にして使っています。まず簡単に説明してください。
一般的に私達みんながメモリ問題に遭遇する時によく使う方法はネット上にも関連資料があります。大体以下の通りです。
一:メモリの引用の上でいくつか処理をして、常用するのは柔らかい引用、強化の引用、弱い引用があります。
二:メモリに画像をロードする時、直接メモリに処理を行います。例えば、境界圧縮
三:メモリを動的に回収する
四:Dalvik仮想マシンのメモリの割り当てを最適化する
五:カスタムヒープメモリサイズ
しかし、本当にこんな簡単な方法がありますか?以上の方法でOOMを解決できますか?いいえ、続けて見に来ます。
次の馬さんは上の順に整理して解決します。数字の番号は上の番号に対応しています。
1:ソフト引用(SoftReference)、虚引用(PhotomRefrefnce)、弱引用(Weak Reference)、これらの3つのカテゴリーはheapのjavaオブジェクトへの応用であり、この3つのクラスを通じてgcと簡単に相互作用することができます。この3つの他に、最も一般的な強引用があります。
1.1:強引用、例えば以下のコード:

Object o=new Object();   
Object o1=o; 

上のコードの中で最初の文はheapスタックの中で新しいObjectオブジェクトを作成します。このオブジェクトの引用は強い引用です。heapのオブジェクトに対する参照がある限り、gcは対象を集めません。以下のコードを通じて:

o=null;   
o1=null

heapの対象は強い可以及び対象、ソフト可及び対象、弱可及び対象、虚可及び対象及び不可到達対象がある。応用の強弱順は強い、柔らかい、弱い、虚です。対象がどのような対象かについては、彼の最強の引用によって決定されます。以下のとおりです

String abc=new String("abc"); //1   
SoftReference<String> abcSoftRef=new SoftReference<String>(abc); //2   
WeakReference<String> abcWeakRef = new WeakReference<String>(abc); //3   
abc=null; //4   
abcSoftRef.clear();//5  

上のコードで:
最初の行はheapペアで「abc」という内容のオブジェクトを作成し、abcからオブジェクトへの強い参照を作成します。二行目と三行目はそれぞれheapのオブジェクトに対するソフト引用と弱引用を確立します。この時heapのオブジェクトはまだ強いです。4行目以降はheapの対象が強くなく、ソフトになります。同じ5行目を実行したら弱いです。
1.2:ソフト引用
ソフト引用は主にメモリに敏感なキャッシュです。jvmがメモリ不足を報告する前に、すべてのソフト引用をクリアします。これにより、gcはソフトなオブジェクトを集めることができます。メモリ不足を解決し、メモリオーバーを避けることができます。いつ収集されますか?gcのアルゴリズムとgcの実行時のメモリのサイズによって異なります。gcがソフト参照を収集すると決定した場合は、上記のabc SoftRefを例として以下のプロセスを実行します。
 
1まずabcSoftRefのreferentをnullに設定し、heapのnew String(abc)オブジェクトを参照しない。
2 heapのnew String(abc)オブジェクトを終了可能に設定します。
3 heap内のnew Stringオブジェクトのfinalizeメソッドが実行され、オブジェクトが占有しているメモリが解放されると、abcSoftRefがReferenceQueに追加される。
注:ReferenceQueソフトへの引用と弱引用は可能ですが、虚引用は必ずあります。
Reference(T paramT,ReferenceQue)<?super T>paramReferenceQue)
Soft Referenceに指摘されたオブジェクトは、たとえ何のDirect Referenceがなくてもクリアされません。JVMのメモリが不足していて、Direct Referenceがない時に掃除します。ソフトReferenceはobject-cacheを設計するのに使います。これによりソフトReferenceは対象cacheだけでなくメモリ不足のエラーも発生しません。ソフトレferenceも実際にpoolingを作る技術に適していると思います。

A obj = new A();  
Refenrence sr = new SoftReference(obj);  
//     
if(sr!=null){  
  obj = sr.get();  
}else{  
  obj = new A();  
  sr = new SoftReference(obj);  
}  

1.3:弱引用
gcが弱いオブジェクトにぶつかると、abc WeakRefの参照を解放し、オブジェクトを収集する。しかし、gcはこの運用を必要とする可能性があります。下記のコードを通じて、その役割が分かります。

String abc=new String("abc");   
WeakReference<String> abcWeakRef = new WeakReference<String>(abc);   
abc=null;   
System.out.println("before gc: "+abcWeakRef.get());   
System.gc();   
System.out.println("after gc: "+abcWeakRef.get());  

実行結果:
before gc:abc  
after gc:null 
gc収集の弱さやオブジェクトの実行プロセスはソフトと同様であるが、gcはメモリの状況によってそのオブジェクトを収集するかどうかを決定しない。いつでも相手の情報を得たいと思っていますが、相手のゴミ収集に影響を与えたくないなら、相手をWeak Referenceで覚えるべきです。 

A obj = new A();  
  WeakReference wr = new WeakReference(obj);  
  obj = null;  
  //      ,obj          
  ...  
  if (wr.get()==null) {  
  System.out.println("obj        ");  
  } else {  
  System.out.println("obj      ,     "+obj.toString()); 
  } 
  ... 
} 

この例では、このReferenceの対象はget()を介して取得でき、戻り値がnullであれば、このオブジェクトはすでにクリアされている。このような技術は、OptimizerやDebuggerなどのプログラムを設計する際によく使われます。このようなプログラムはある対象の情報を取得する必要がありますが、対象のゴミ収集に影響を与えてはいけません。
1.4:虚引用
虚引用を作ってからget方法で結果を返してもnullです。ソースコードを通して、虚引用がreferentに引用の対象を書き込みます。get方法だけで結果はnullに戻ります。まずはgcと相互作用する過程を見て、彼の役割を説明します。
1.4.1 referentをnullに設定せず、直接にheapのnew String(abc)のオブジェクトを終了可能に設定します。
1.4.2ソフト引用と弱引用は違って、まずPhotomRefrenceの対象をそのReferenceQueに追加して、虚構の対象を釈放します。
heapの中のnew String(abc)のオブジェクトを集める前に、他のことができます。以下のコードで彼の役割が分かります。

import java.lang.ref.PhantomReference;   
import java.lang.ref.Reference;   
import java.lang.ref.ReferenceQueue;   
import java.lang.reflect.Field;   
public class Test {   
  public static boolean isRun = true;   
  public static void main(String[] args) throws Exception {   
    String abc = new String("abc");   
    System.out.println(abc.getClass() + "@" + abc.hashCode());   
    final ReferenceQueue referenceQueue = new ReferenceQueue<String>();
    new Thread() {   
      public void run() {   
        while (isRun) {   
          Object o = referenceQueue.poll();   
          if (o != null) {   
            try {   
              Field rereferent = Reference.class   
                  .getDeclaredField("referent");   
              rereferent.setAccessible(true);   
              Object result = rereferent.get(o);   
              System.out.println("gc will collect:"   
                  + result.getClass() + "@"   
                  + result.hashCode());   
            } catch (Exception e) {   
              e.printStackTrace();   
            }   
          }   
        }   
      }   
    }.start();   
    PhantomReference<String> abcWeakRef = new PhantomReference<String>(abc,
        referenceQueue);   
    abc = null;   
    Thread.currentThread().sleep(3000);   
    System.gc();   
    Thread.currentThread().sleep(3000);   
    isRun = false;   
  }   
}
結果は
class java.lang.String@96354 
gc will collect:class java.lang.String@96354
 はい、引用についてはこれまでにします。
 
2:メモリの中で圧縮した馬さんはテストをしました。少量の大きさではない画像に対してはこのようにしてもいいですが、多すぎて大きい画像の馬さんは馬鹿な方法でメモリの中で圧縮して、ソフト引用でOOMを避けます。二つの方法のコードは以下の通りです。
方式のコードは以下の通りです。

@SuppressWarnings("unused")
private Bitmap copressImage(String imgPath){
  File picture = new File(imgPath);
  Options bitmapFactoryOptions = new BitmapFactory.Options();
  //                     
  bitmapFactoryOptions.inJustDecodeBounds = true;
  bitmapFactoryOptions.inSampleSize = 2;
  int outWidth = bitmapFactoryOptions.outWidth;
  int outHeight = bitmapFactoryOptions.outHeight;
  bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
     bitmapFactoryOptions);
  float imagew = 150;
  float imageh = 150;
  int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
      / imageh);
  int xRatio = (int) Math
      .ceil(bitmapFactoryOptions.outWidth / imagew);
  if (yRatio > 1 || xRatio > 1) {
    if (yRatio > xRatio) {
      bitmapFactoryOptions.inSampleSize = yRatio;
    } else {
      bitmapFactoryOptions.inSampleSize = xRatio;
    }
  } 
  bitmapFactoryOptions.inJustDecodeBounds = false;
  bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(),
      bitmapFactoryOptions);
  if(bmap != null){        
    //ivwCouponImage.setImageBitmap(bmap);
    return bmap;
  }
  return null;
}

方式二コードは以下の通りです。

package com.lvguo.scanstreet.activity;
import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import com.lvguo.scanstreet.R;
import com.lvguo.scanstreet.data.ApplicationData;
/** 
* @Title: PhotoScanActivity.java
* @Description:        
* @author XiaoMa 
*/
public class PhotoScanActivity extends Activity {
  private Gallery gallery ;
  private List<String> ImageList;
  private List<String> it ;
  private ImageAdapter adapter ; 
  private String path ;
  private String shopType;
  private HashMap<String, SoftReference<Bitmap>> imageCache = null;
  private Bitmap bitmap = null;
  private SoftReference<Bitmap> srf = null;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
    WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.photoscan);
    Intent intent = this.getIntent();
    if(intent != null){
      if(intent.getBundleExtra("bundle") != null){
        Bundle bundle = intent.getBundleExtra("bundle");
        path = bundle.getString("path");
        shopType = bundle.getString("shopType");
      }
    }
    init();
  }
  private void init(){
    imageCache = new HashMap<String, SoftReference<Bitmap>>();
     gallery = (Gallery)findViewById(R.id.gallery);
     ImageList = getSD();
     if(ImageList.size() == 0){
      Toast.makeText(getApplicationContext(), "   ,           ", Toast.LENGTH_SHORT).show();
      return ;
     }
     adapter = new ImageAdapter(this, ImageList);
     gallery.setAdapter(adapter);
     gallery.setOnItemLongClickListener(longlistener);
  }
  /**
   * Gallery        
   */
  private OnItemLongClickListener longlistener = new OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view,
        final int position, long id) {
      //              
      AlertDialog.Builder dialog = new AlertDialog.Builder(PhotoScanActivity.this);
      dialog.setIcon(R.drawable.warn);
      dialog.setTitle("    ");
      dialog.setMessage("           ?");
      dialog.setPositiveButton("  ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          File file = new File(it.get(position));
          boolean isSuccess;
          if(file.exists()){
            isSuccess = file.delete();
            if(isSuccess){
              ImageList.remove(position);
              adapter.notifyDataSetChanged();
              //gallery.setAdapter(adapter);
              if(ImageList.size() == 0){
                Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoSizeZero), Toast.LENGTH_SHORT).show();
              }
              Toast.makeText(getApplicationContext(), getResources().getString(R.string.phoDelSuccess), Toast.LENGTH_SHORT).show();
            }
          }
        }
      });
      dialog.setNegativeButton("  ",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          dialog.dismiss();
        }
      });
      dialog.create().show();
      return false;
    }
  };
  /**
   *   SD         
   * @return
   */
  private List<String> getSD() {
    /*          */
    File fileK ;
    it = new ArrayList<String>();
    if("newadd".equals(shopType)){ 
       //                      
      fileK = new File(ApplicationData.TEMP);
    }else{
      //       
      fileK = new File(path);
    }
    File[] files = fileK.listFiles();
    if(files != null && files.length>0){
      for(File f : files ){
        if(getImageFile(f.getName())){
          it.add(f.getPath());
          Options bitmapFactoryOptions = new BitmapFactory.Options();
          //                     
          bitmapFactoryOptions.inJustDecodeBounds = true;
          bitmapFactoryOptions.inSampleSize = 5;
          int outWidth = bitmapFactoryOptions.outWidth;
          int outHeight = bitmapFactoryOptions.outHeight;
          float imagew = 150;
          float imageh = 150;
          int yRatio = (int) Math.ceil(bitmapFactoryOptions.outHeight
              / imageh);
          int xRatio = (int) Math
              .ceil(bitmapFactoryOptions.outWidth / imagew);
          if (yRatio > 1 || xRatio > 1) {
            if (yRatio > xRatio) {
              bitmapFactoryOptions.inSampleSize = yRatio;
            } else {
              bitmapFactoryOptions.inSampleSize = xRatio;
            }
          } 
          bitmapFactoryOptions.inJustDecodeBounds = false;
          bitmap = BitmapFactory.decodeFile(f.getPath(),
              bitmapFactoryOptions);
          //bitmap = BitmapFactory.decodeFile(f.getPath()); 
          srf = new SoftReference<Bitmap>(bitmap);
          imageCache.put(f.getName(), srf);
        }
      }
    }
    return it;
  }
  /**
   *               
   * @param fName
   * @return
   */
  private boolean getImageFile(String fName) {
    boolean re;
    /*       */
    String end = fName
        .substring(fName.lastIndexOf(".") + 1, fName.length())
        .toLowerCase();
    /*          MimeType */
    if (end.equals("jpg") || end.equals("gif") || end.equals("png")
        || end.equals("jpeg") || end.equals("bmp")) {
      re = true;
    } else {
      re = false;
    }
    return re;
  }
  public class ImageAdapter extends BaseAdapter{
    /*      */
    int mGalleryItemBackground;
    private Context mContext;
    private List<String> lis;
    /* ImageAdapter     */
    public ImageAdapter(Context c, List<String> li) {
      mContext = c;
      lis = li;
      TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
      mGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
      a.recycle();
    }
    /*         getCount,       */
    public int getCount() {
      return lis.size();
    }
    /*         getItem,  position */
    public Object getItem(int position) {
      return lis.get(position);
    }
    /*         getItemId,  position */
    public long getItemId(int position) {
      return position;
    }
    /*         getView,   View   */
    public View getView(int position, View convertView, ViewGroup parent) {
      System.out.println("lis:"+lis);
      File file = new File(it.get(position));
      SoftReference<Bitmap> srf = imageCache.get(file.getName());
      Bitmap bit = srf.get();
      ImageView i = new ImageView(mContext);
      i.setImageBitmap(bit);
      i.setScaleType(ImageView.ScaleType.FIT_XY);
      i.setLayoutParams( new Gallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
          WindowManager.LayoutParams.WRAP_CONTENT));
      return i;
    }
  }
}

上記の2つの方法は、最初の境界圧縮を直接使用し、2番目の境界圧縮を使用して間接的にソフトガイドを使用してOOMを回避しましたが、これらの関数はdecodeを完成した後、最後にjava層のcreateBitmapによって完成されます。より多くのメモリを消費する必要があります。解決方法もあります。継続して見てください。以下の方法も大いに効果があります。
1.

InputStream is = this.getResources().openRawResource(R.drawable.pic1);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10;  //width,hight        
Bitmap btp =BitmapFactory.decodeStream(is,null,options);

2.

if(!bmp.isRecycle() ){
     bmp.recycle()  //         
     system.gc() //        
}

上のコードは下のコードと分けて使えます。メモリの問題も解決できます。ほえ…

/**           ,             ,           
*                  
*/ 
public static Bitmap readBitMap(Context context, int resId){ 
    BitmapFactory.Options opt = new BitmapFactory.Options(); 
    opt.inPreferredConfig = Bitmap.Config.RGB_565;  
    opt.inPurgeable = true; 
    opt.inInputShareable = true; 
     //       
    InputStream is = context.getResources().openRawResource(resId); 
      return BitmapFactory.decodeStream(is,null,opt); 
}
3:皆さんは適切なところで以下のコードを使って、自分で明示的にGCを呼び出してメモリを回収することができます。

if(bitmapObject.isRecycled()==false) //       
     bitmapObject.recycle();  

4:これは面白いです。Dalvik仮想マシンのメモリの割り当てを最適化して、聞いていてとても強いです。具体的にはどういうことですか?
Androidプラットフォームにとっては、そのホスト層が使用するDalvik JavaVMは、現在の表現から、処理を最適化するところが多くあります。例えば、大型ゲームやリソース消費のアプリケーションを開発する際に、手動干渉GC処理を考慮して、dalvik.system.VMRuntime類が提供するsetTarget Heapplization方法を使用すると、プログラムスタックメモリの処理効率を高めることができます。もちろん具体的な原理はオープンソースプロジェクトを参照してもいいです。ここでは使用方法だけを話します。コードは以下の通りです。
private final static floatTARGET_HEAP_UTILIZATION = 0.75f;
プログラムオンクリアー時に呼び出すことができます。
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
すぐできます
5:私達のアプリケーションをカスタマイズするにはどれぐらいのメモリが必要ですか?

private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;
 //    heap   6MB  
VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);

はい、文章を書き終わりました。片の幅はちょっと長いです。関連するものが多すぎるので、他の文章の馬さんはソースコードを貼ります。この文章は馬さんが直接プロジェクトの中で3つのAndroidの実機でテストしました。みんなは自分の需要によって適当な方法を選んでOOMを避けなければなりません。頑張ってください。毎日少しずつ収穫があります。これも進歩です。頑張ってください。
ここで述べたように、皆さんのAndroidプログラムの設計に役に立ちます。