Android 内存溢出解决方案(OOM)

来源:互联网 发布:u盘excel数据恢复 编辑:程序博客网 时间:2024/05/01 03:21
(本文对我帮助很大,在此谢谢原作者)
标签:Android Android加载大 移动开发
原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处 、作者信息和本声明。否则将追究法律责任。http://mzh3344258.blog.51cto.com/1823534/804237
 

在最近做的工程中发现加载的图片太多或图片过大时经常出现OOM问题,找网上资料也提供了很多方法,但自己感觉有点乱,特此,今天在不同型号的三款安卓手机上做了测试,因为有效果也有结果,今天小马就做个详细的总结,以供朋友们共同交流学习,也供自己以后在解决OOM问题上有所提高,提前讲下,片幅有点长,涉及的东西太多,大家耐心看,肯定有收获的,里面的很多东西小马也是学习参考网络资料使用的,先来简单讲下下:

一般我们大家在遇到内存问题的时候常用的方式网上也有相关资料,大体如下几种:

一:在内存引用上做些处理,常用的有软引用、强化引用、弱引用

二:在内存中加载图片时直接在内存中做处理,如:边界压缩

三:动态回收内存

四:优化Dalvik虚拟机的堆内存分配

五:自定义堆内存大小

可是真的有这么简单吗,就用以上方式就能解决OOM了?不是的,继续来看...

下面小马就照着上面的次序来整理下解决的几种方式,数字序号与上面对应:

1:软引用(SoftReference)、虚引用(PhantomRefrence)、弱引用(WeakReference),这三个类是对heap中java对象的应用,通过这个三个类可以和gc做简单的交互,除了这三个以外还有一个是最常用的强引用

1.1:强引用,例如下面代码:

  1. Objecto=newObject();
  2. Object o1=o;

上面代码中第一句是在heap堆中创建新的Object对象通过o引用这个对象,第二句是通过o建立o1到newObject()这个heap堆中的对象的引用,这两个引用都是强引用.只要存在对heap中对象的引用,gc就不会收集该对象.如果通过如下代码:

  1. o=null;
  2. o1=null

heap中对象有强可及对象、软可及对象、弱可及对象、虚可及对象和不可到达对象。应用的强弱顺序是强、软、弱、和虚。对于对象是属于哪种可及的对象,由他的最强的引用决定。如下:

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

上面的代码中:

第一行在heap对中创建内容为“abc”的对象,并建立abc到该对象的强引用,该对象是强可及的。第二行和第三行分别建立对heap中对象的软引用和弱引用,此时heap中的对象仍是强可及的。第四行之后heap中对象不再是强可及的,变成软可及的。同样第五行执行之后变成弱可及的。

1.2:软引用

软引用是主要用于内存敏感的高速缓存。在jvm报告内存不足之前会清除所有的软引用,这样以来gc就有可能收集软可及的对象,可能解决内存吃紧问题,避免内存溢出。什么时候会被收集取决于gc的算法和gc运行时可用内存的大小。当gc决定要收集软引用是执行以下过程,以上面的abcSoftRef为例:

 

1首先将abcSoftRef的referent设置为null,不再引用heap中的newString("abc")对象。

2 将heap中的newString("abc")对象设置为可结束的(finalizable)。

3 当heap中的newString("abc")对象的finalize()方法被运行而且该对象占用的内存被释放,abcSoftRef被添加到它的ReferenceQueue中。

注:对ReferenceQueue软引用和弱引用可以有可无,但是虚引用必须有,参见:

  1. Reference(TparamT, ReferenceQueue<? superT>paramReferenceQueue)

被 Soft Reference 指到的对象,即使没有任何 Direct Reference,也不会被清除。一直要到 JVM内存不足且 没有 Direct Reference 时才会清除,SoftReference 是用来设计 object-cache之用的。如此一来 SoftReference 不但可以把对象 cache 起来,也不会造成内存不足的错误(OutOfMemoryError)。我觉得 Soft Reference 也适合拿来实作 pooling的技巧。

  1. A obj =newA();
  2. Refenrence sr = newSoftReference(obj);
  3. //引用时
  4. if(sr!=null){
  5. obj =sr.get();
  6. }else{
  7. obj = new A();
  8. sr = newSoftReference(obj);
  9. }

1.3:弱引用

当gc碰到弱可及对象,并释放abcWeakRef的引用,收集该对象。但是gc可能需要对此运用才能找到该弱可及对象。通过如下代码可以了明了的看出它的作用:

  1. Stringabc=newString("abc");
  2. WeakReference<String>abcWeakRef = newWeakReference<String>(abc);
  3. abc=null;
  4. System.out.println("before gc:"+abcWeakRef.get());
  5. System.gc();
  6. System.out.println("after gc:"+abcWeakRef.get());

运行结果:

before gc: abc

after gc: null

gc收集弱可及对象的执行过程和软可及一样,只是gc不会根据内存情况来决定是不是收集该对象。如果你希望能随时取得某对象的信息,但又不想影响此对象的垃圾收集,那么你应该用Weak Reference 来记住此对象,而不是用一般的 reference。

 

  1. A obj =newA();
  2. WeakReference wr =newWeakReference(obj);
  3. obj = null;
  4. //等待一段时间,obj对象就会被垃圾回收
  5.   ...
  6.   if (wr.get()==null) {
  7.   System.out.println("obj 已经被清除了");
  8.   } else {
  9.   System.out.println("obj尚未被清除,其信息是"+obj.toString());
  10.   }
  11.   ...
  12. }

 

在此例中,透过 get() 可以取得此 Reference的所指到的对象,如果返回值为 null 的话,代表此对象已经被清除。这类的技巧,在设计 Optimizer 或 Debugger这类的程序时常会用到,因为这类程序需要取得某对象的信息,但是不可以 影响此对象的垃圾收集。

1.4:虚引用

 

就是没有的意思,建立虚引用之后通过get方法返回结果始终为null,通过源代码你会发现,虚引用通向会把引用的对象写进referent,只是get方法返回结果为null.先看一下和gc交互的过程在说一下他的作用.

1.4.1 不把referent设置为null, 直接把heap中的newString("abc")对象设置为可结束的(finalizable).

1.4.2 与软引用和弱引用不同,先把PhantomRefrence对象添加到它的ReferenceQueue中.然后在释放虚可及的对象.

你会发现在收集heap中的newString("abc")对象之前,你就可以做一些其他的事情.通过以下代码可以了解他的作用.

 

  1. importjava.lang.ref.PhantomReference;
  2. importjava.lang.ref.Reference;
  3. importjava.lang.ref.ReferenceQueue;
  4. importjava.lang.reflect.Field;
  5. public classTest {
  6. public staticboolean isRun =true;
  7. public staticvoid main(String[] args)throws Exception{
  8. String abc = new String("abc");
  9. System.out.println(abc.getClass() + "@" +abc.hashCode());
  10. final ReferenceQueue referenceQueue =newReferenceQueue<String>();
  11. new Thread() {
  12. public voidrun() {
  13. while (isRun) {
  14. Object o =referenceQueue.poll();
  15. if (o != null) {
  16. try{
  17. Field rereferent =Reference.class
  18. .getDeclaredField("referent");
  19. rereferent.setAccessible(true);
  20. Object result =rereferent.get(o);
  21. System.out.println("gc willcollect:"
  22. + result.getClass() +"@"
  23. +result.hashCode());
  24. } catch (Exception e){
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. }
  30. }.start();
  31. PhantomReference<String>abcWeakRef = newPhantomReference<String>(abc,
  32. referenceQueue);
  33. abc = null;
  34. Thread.currentThread().sleep(3000);
  35. System.gc();
  36. Thread.currentThread().sleep(3000);
  37. isRun = false;
  38. }
  39. }

 

结果为

class java.lang.String@96354

gc will collect:class java.lang.String@96354 好了,关于引用就讲到这,下面看2

2:在内存中压缩小马做了下测试,对于少量不太大的图片这种方式可行,但太多而又大的图片小马用个笨的方式就是,先在内存中压缩,再用软引用避免OOM,两种方式代码如下,大家可参考下:

方式一代码如下:

  1. @SuppressWarnings("unused")
  2. private Bitmap copressImage(StringimgPath){
  3. File picture =newFile(imgPath);
  4. Options bitmapFactoryOptions =newBitmapFactory.Options();
  5. //下面这个设置是将图片边界不可调节变为可调节
  6. bitmapFactoryOptions.inJustDecodeBounds =true;
  7. bitmapFactoryOptions.inSampleSize = 2;
  8. intoutWidth =bitmapFactoryOptions.outWidth;
  9. int outHeight =bitmapFactoryOptions.outHeight;
  10. bmap =BitmapFactory.decodeFile(picture.getAbsolutePath(),
  11. bitmapFactoryOptions);
  12. float imagew = 150;
  13. float imageh = 150;
  14. intyRatio = (int)Math.ceil(bitmapFactoryOptions.outHeight
  15. /imageh);
  16. intxRatio = (int)Math
  17. .ceil(bitmapFactoryOptions.outWidth /imagew);
  18. if(yRatio > 1|| xRatio > 1) {
  19. if (yRatio > xRatio){
  20. bitmapFactoryOptions.inSampleSize =yRatio;
  21. } else {
  22. bitmapFactoryOptions.inSampleSize =xRatio;
  23. }
  24. }
  25. bitmapFactoryOptions.inJustDecodeBounds =false;
  26. bmap =BitmapFactory.decodeFile(picture.getAbsolutePath(),
  27. bitmapFactoryOptions);
  28. if(bmap != null){
  29. //ivwCouponImage.setImageBitmap(bmap);
  30. return bmap;
  31. }
  32. return null;
  33. }

方式二代码如下:

  1. packagecom.lvguo.scanstreet.activity;
  2. importjava.io.File;
  3. importjava.lang.ref.SoftReference;
  4. importjava.util.ArrayList;
  5. importjava.util.HashMap;
  6. importjava.util.List;
  7. importandroid.app.Activity;
  8. importandroid.app.AlertDialog;
  9. importandroid.content.Context;
  10. importandroid.content.DialogInterface;
  11. importandroid.content.Intent;
  12. importandroid.content.res.TypedArray;
  13. importandroid.graphics.Bitmap;
  14. importandroid.graphics.BitmapFactory;
  15. importandroid.graphics.BitmapFactory.Options;
  16. importandroid.os.Bundle;
  17. importandroid.view.View;
  18. importandroid.view.ViewGroup;
  19. importandroid.view.WindowManager;
  20. importandroid.widget.AdapterView;
  21. importandroid.widget.AdapterView.OnItemLongClickListener;
  22. importandroid.widget.BaseAdapter;
  23. importandroid.widget.Gallery;
  24. importandroid.widget.ImageView;
  25. importandroid.widget.Toast;
  26. importcom.lvguo.scanstreet.R;
  27. importcom.lvguo.scanstreet.data.ApplicationData;

  28. public classPhotoScanActivity extendsActivity {
  29. private Gallery gallery;
  30. privateList<String>ImageList;
  31. privateList<String> it;
  32. private ImageAdapter adapter;
  33. private String path;
  34. private StringshopType;
  35. private HashMap<String,SoftReference<Bitmap>>imageCache = null;
  36. private Bitmap bitmap = null;
  37. privateSoftReference<Bitmap> srf= null;
  38. @Override
  39. public voidonCreate(Bundle savedInstanceState){
  40. super.onCreate(savedInstanceState);
  41. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  42. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  43. setContentView(R.layout.photoscan);
  44. Intent intent =this.getIntent();
  45. if(intent != null){
  46. if(intent.getBundleExtra("bundle") != null){
  47. Bundle bundle =intent.getBundleExtra("bundle");
  48. path =bundle.getString("path");
  49. shopType =bundle.getString("shopType");
  50. }
  51. }
  52. init();
  53. }
  54. private voidinit(){
  55. imageCache =newHashMap<String,SoftReference<Bitmap>>();
  56. gallery =(Gallery)findViewById(R.id.gallery);
  57. ImageList =getSD();
  58. if(ImageList.size() == 0){
  59. Toast.makeText(getApplicationContext(), "无照片,请返回拍照后再使用预览",Toast.LENGTH_SHORT).show();
  60. return ;
  61. }
  62. adapter = new ImageAdapter(this, ImageList);
  63. gallery.setAdapter(adapter);
  64. gallery.setOnItemLongClickListener(longlistener);
  65. }

  66. private OnItemLongClickListener longlistener= newOnItemLongClickListener() {
  67. @Override
  68. public booleanonItemLongClick(AdapterView<?>parent, View view,
  69. final intposition, long id){
  70. //此处添加长按事件删除照片实现
  71. AlertDialog.Builderdialog = newAlertDialog.Builder(PhotoScanActivity.this);
  72. dialog.setIcon(R.drawable.warn);
  73. dialog.setTitle("删除提示");
  74. dialog.setMessage("你确定要删除这张照片吗?");
  75. dialog.setPositiveButton("确定", newDialogInterface.OnClickListener() {
  76. @Override
  77. public voidonClick(DialogInterface dialog, int which) {
  78. File file = newFile(it.get(position));
  79. boolean isSuccess;
  80. if(file.exists()){
  81. isSuccess =file.delete();
  82. if(isSuccess){
  83. ImageList.remove(position);
  84. adapter.notifyDataSetChanged();
  85. //gallery.setAdapter(adapter);
  86. if(ImageList.size() == 0){
  87. Toast.makeText(getApplicationContext(),getResources().getString(R.string.phoSizeZero),Toast.LENGTH_SHORT).show();
  88. }
  89. Toast.makeText(getApplicationContext(),getResources().getString(R.string.phoDelSuccess),Toast.LENGTH_SHORT).show();
  90. }
  91. }
  92. }
  93. });
  94. dialog.setNegativeButton("取消",newDialogInterface.OnClickListener() {
  95. @Override
  96. public voidonClick(DialogInterface dialog, int which) {
  97. dialog.dismiss();
  98. }
  99. });
  100. dialog.create().show();
  101. return false;
  102. }
  103. };

  104. privateList<String> getSD(){

  105. File fileK;
  106. it = newArrayList<String>();
  107. if("newadd".equals(shopType)){
  108. //如果是从查看本人新增列表项或商户列表项进来时
  109. fileK = newFile(ApplicationData.TEMP);
  110. }else{
  111. //此时为纯粹新增
  112. fileK = new File(path);
  113. }
  114. File[] files =fileK.listFiles();
  115. if(files != null &&files.length>0){
  116. for(File f : files){
  117. if(getImageFile(f.getName())){
  118. it.add(f.getPath());
  119. OptionsbitmapFactoryOptions = newBitmapFactory.Options();
  120. //下面这个设置是将图片边界不可调节变为可调节
  121. bitmapFactoryOptions.inJustDecodeBounds =true;
  122. bitmapFactoryOptions.inSampleSize = 5;
  123. intoutWidth =bitmapFactoryOptions.outWidth;
  124. int outHeight =bitmapFactoryOptions.outHeight;
  125. float imagew = 150;
  126. float imageh = 150;
  127. intyRatio = (int)Math.ceil(bitmapFactoryOptions.outHeight
  128. /imageh);
  129. intxRatio = (int)Math
  130. .ceil(bitmapFactoryOptions.outWidth /imagew);
  131. if(yRatio > 1|| xRatio > 1) {
  132. if (yRatio > xRatio){
  133. bitmapFactoryOptions.inSampleSize =yRatio;
  134. } else {
  135. bitmapFactoryOptions.inSampleSize =xRatio;
  136. }
  137. }
  138. bitmapFactoryOptions.inJustDecodeBounds =false;
  139. bitmap =BitmapFactory.decodeFile(f.getPath(),
  140. bitmapFactoryOptions);
  141. //bitmap = BitmapFactory.decodeFile(f.getPath());
  142. srf = newSoftReference<Bitmap>(bitmap);
  143. imageCache.put(f.getName(), srf);
  144. }
  145. }
  146. }
  147. return it;
  148. }

  149. private booleangetImageFile(String fName) {
  150. boolean re;

  151. String end =fName
  152. .substring(fName.lastIndexOf(".") + 1, fName.length())
  153. .toLowerCase();

  154. if(end.equals("jpg")|| end.equals("gif") ||end.equals("png")
  155. ||end.equals("jpeg") ||end.equals("bmp")){
  156. re = true;
  157. } else {
  158. re = false;
  159. }
  160. return re;
  161. }
  162. public classImageAdapter extendsBaseAdapter{

  163. intmGalleryItemBackground;
  164. private ContextmContext;
  165. privateList<String>lis;

  166. public ImageAdapter(Context c,List<String> li){
  167. mContext =c;
  168. lis = li;
  169. TypedArray a =obtainStyledAttributes(R.styleable.Gallery);
  170. mGalleryItemBackground =a.getResourceId(R.styleable.Gallery_android_galleryItemBackground,0);
  171. a.recycle();
  172. }

  173. public intgetCount() {
  174. return lis.size();
  175. }

  176. public Object getItem(int position) {
  177. returnlis.get(position);
  178. }

  179. public longgetItemId(intposition) {
  180. return position;
  181. }

  182. public View getView(int position, View convertView, ViewGroupparent) {
  183. System.out.println("lis:"+lis);
  184. File file = newFile(it.get(position));
  185. SoftReference<Bitmap>srf = imageCache.get(file.getName());
  186. Bitmap bit =srf.get();
  187. ImageView i =newImageView(mContext);
  188. i.setImageBitmap(bit);
  189. i.setScaleType(ImageView.ScaleType.FIT_XY);
  190. i.setLayoutParams( newGallery.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
  191. WindowManager.LayoutParams.WRAP_CONTENT));
  192. return i;
  193. }
  194. }
  195. }

上面两种方式第一种直接使用边界压缩,第二种在使用边界压缩的情况下间接的使用了软引用来避免OOM,但大家都知道,这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存,如果图片多且大,这种方式还是会引用OOM异常的,不着急,有的是办法解决,继续看,以下方式也大有妙用的:

  1. 1.InputStream is =this.getResources().openRawResource(R.drawable.pic1);
  2. BitmapFactory.Optionsoptions=newBitmapFactory.Options();
  3. options.inJustDecodeBounds =false;
  4. options.inSampleSize = 10;//width,hight设为原来的十分一
  5. Bitmap btp =BitmapFactory.decodeStream(is,null,options);
  6. 2. if(!bmp.isRecycle()){
  7. bmp.recycle()//回收图片所占的内存
  8. system.gc()//提醒系统及时回收
  9. }
上面代码与下面代码大家可分开使用,也可有效缓解内存问题哦...吼吼...
  1. public static BitmapreadBitMap(Context context, int resId){
  2. BitmapFactory.Options opt = newBitmapFactory.Options();
  3. opt.inPreferredConfig =Bitmap.Config.RGB_565;
  4. opt.inPurgeable = true;
  5. opt.inInputShareable = true;
  6. //获取资源图片
  7. InputStream is = context.getResources().openRawResource(resId);
  8. returnBitmapFactory.decodeStream(is,null,opt);
  9. }

3:大家可以选择在合适的地方使用以下代码动态并自行显式调用GC来回收内存:

  1. if(bitmapObject.isRecycled()==false)//如果没有回收
  2. bitmapObject.recycle();

4:这个就好玩了,优化Dalvik虚拟机的堆内存分配,听着很强大,来看下具体是怎么一回事

对于Android平台来说,其托管层使用的DalvikJavaVM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体原理我们可以参考开源工程,这里我们仅说下使用方法:代码如下:

  1. private finalstaticfloatTARGET_HEAP_UTILIZATION = 0.75f;
  2. 在程序onCreate时就可以调用
  3. VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
  4. 即可

5:自定义我们的应用需要多大的内存,这个好暴力哇,强行设置最小内存大小,代码如下:

  1. private finalstatic int CWJ_HEAP_SIZE= 6* 1024*1024 ;
  2. //设置最小heap内存为6MB大小
  3. VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE);

好了,文章写完了,片幅有点长,因为涉及到的东西太多了,其它文章小马都会贴源码,这篇文章小马是直接在项目中用三款安卓真机测试的,有效果,项目原码就不在这贴了,不然泄密了都,吼吼,但这里讲下还是会因为手机的不同而不同,大家得根据自己需求选择合适的方式来避免OOM,大家加油呀,每天都有或多或少的收获,这也算是进步,加油加油!


=============================================================================================



Android有效解决加载大图片时内存溢出的问题

尽量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大图,
因为这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存。

因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的 source,
decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,
无需再使用java层的createBitmap,从而节省了java层的空间。
如果在读取时加上图片的Config参数,可以跟有效减少加载的内存,从而跟有效阻止抛out of Memory异常
另外,decodeStream直接拿的图片来读取字节码了, 不会根据机器的各种分辨率来自动适应, 
使用了decodeStream之后,需要在hdpi和mdpi,ldpi中配置相应的图片资源, 
否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。

另外,以下方式也大有帮助:
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()  //提醒系统及时回收
}

以下奉上一个方法:

Java代码

   1. /**
   2.  * 以最省内存的方式读取本地资源的图片
   3.  * @param context
   4.  * @param resId
   5.  * @return
   6.  */  
   7. public static Bitmap readBitMap(Context context, int resId){  
   8.     BitmapFactory.Options opt = new BitmapFactory.Options();  
   9.     opt.inPreferredConfig = Bitmap.Config.RGB_565;   
  10.     opt.inPurgeable = true;  
  11.     opt.inInputShareable = true;  
  12.        //获取资源图片  
  13.     InputStream is = context.getResources().openRawResource(resId);  
  14.         return BitmapFactory.decodeStream(is,null,opt);  
  15. }


================================================================================
Android内存溢出的解决办法

转自:http://www.cppblog.com/iuranus/archive/2010/11/15/124394.html?opt=admin

昨天在模拟器上给gallery放入图片的时候,出现java.lang.OutOfMemoryError: bitmap size exceeds VM budget 异常,图像大小超过了RAM内存。
      模拟器RAM比较小,只有8M内存,当我放入的大量的图片(每个100多K左右),就出现上面的原因。
由于每张图片先前是压缩的情况,放入到Bitmap的时候,大小会变大,导致超出RAM内存,具体解决办法如下:

//解决加载图片 内存溢出的问题
                    //Options 只保存图片尺寸大小,不保存图片到内存
                BitmapFactory.Options opts = new BitmapFactory.Options();
                //缩放的比例,缩放是很难按准备的比例进行缩放的,其值表明缩放的倍数,SDK中建议其值是2的指数值,值越大会导致图片不清晰
                opts.inSampleSize = 4;
                Bitmap bmp = null;
                bmp = BitmapFactory.decodeResource(getResources(), mImageIds[position],opts);                             

                ...              

               //回收
                bmp.recycle();

通过上面的方式解决了,但是这并不是最完美的解决方式。

通过一些了解,得知如下:

优化Dalvik虚拟机的堆内存分配

对 于Android平台来说,其托管层使用的Dalvik Java VM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体 原理我们可以参考开源工程,这里我们仅说下使用方法:   private final static float TARGET_HEAP_UTILIZATION = 0.75f; 在程序onCreate时就可以调用 VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。


Android堆内存也可自己定义大小

    对于一些Android项目,影响性能瓶颈的主要是Android自己内存管理机制问题,目前手机厂商对RAM都比较吝啬,对于软件的流畅性来说RAM对 性能的影响十分敏感,除了 优化Dalvik虚拟机的堆内存分配外,我们还可以强制定义自己软件的对内存大小,我们使用Dalvik提供的 dalvik.system.VMRuntime类来设置最小堆内存为例:

private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;

VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理


bitmap 设置图片尺寸,避免 内存溢出 OutOfMemoryError的优化方法
★android 中用bitmap 时很容易内存溢出,报如下错误:Java.lang.OutOfMemoryError : bitmap size exceeds VM budget

● 主要是加上这段:
BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;

● eg1:(通过Uri取图片)
private ImageView preview;
BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一
                    Bitmap bitmap = BitmapFactory.decodeStream(cr
                            .openInputStream(uri), null, options);
                    preview.setImageBitmap(bitmap);
以上代码可以优化内存溢出,但它只是改变图片大小,并不能彻底解决内存溢出。
● eg2:(通过路径去图片)
private ImageView preview;
private String fileName= "/sdcard/DCIM/Camera/2010-05-14 16.01.44.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之一
                        Bitmap b = BitmapFactory.decodeFile(fileName, options);
                        preview.setImageBitmap(b);
                        filePath.setText(fileName);

★Android 还有一些性能优化的方法:
●  首先内存方面,可以参考 Android堆内存也可自己定义大小 和 优化Dalvik虚拟机的堆内存分配

●  基础类型上,因为Java没有实际的指针,在敏感运算方面还是要借助NDK来完成。Android123提示游戏开发者,这点比较有意思的是Google 推出NDK可能是帮助游戏开发人员,比如OpenGL ES的支持有明显的改观,本地代码操作图形界面是很必要的。

●  图形对象优化,这里要说的是Android上的Bitmap对象销毁,可以借助recycle()方法显示让GC回收一个Bitmap对象,通常对一个不用的Bitmap可以使用下面的方式,如

if(bitmapObject.isRecycled()==false) //如果没有回收  
         bitmapObject.recycle();   

●  目前系统对动画支持比较弱智对于常规应用的补间过渡效果可以,但是对于游戏而言一般的美工可能习惯了GIF方式的统一处理,目前Android系统仅能预览GIF的第一帧,可以借助J2ME中通过线程和自己写解析器的方式来读取GIF89格式的资源。

● 对于大多数Android手机没有过多的物理按键可能我们需要想象下了做好手势识别 GestureDetector 和重力感应来实现操控。通常我们还要考虑误操作问题的降噪处理。

Android堆内存也可自己定义大小

   对于一些大型Android项目或游戏来说在算法处理上没有问题外,影响性能瓶颈的主要是Android自己内存管理机制问题,目前手机厂商对RAM都比 较吝啬,对于软件的流畅性来说RAM对性能的影响十分敏感,除了上次Android开发网提到的 优化Dalvik虚拟机的堆内存分配外,我们还可以强制定义自己软件的对内存大小,我们使用Dalvik提供的 dalvik.system.VMRuntime类来设置最小堆内存为例:

private final static int CWJ_HEAP_SIZE = 6* 1024* 1024 ;

VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); //设置最小heap内存为6MB大小。当然对于内存吃紧来说还可以通过手动干涉GC去处理,我们将在下次提到具体应用。

优化Dalvik虚拟机的堆内存分配

对 于Android平台来说,其托管层使用的Dalvik JavaVM从目前的表现来看还有很多地方可以优化处理,比如我们在开发一些大型游戏或耗资源的应用中可能考虑手动干涉GC处理,使用 dalvik.system.VMRuntime类提供的setTargetHeapUtilization方法可以增强程序堆内存的处理效率。当然具体 原理我们可以参考开源工程,这里我们仅说下使用方法:   private final static floatTARGET_HEAP_UTILIZATION = 0.75f; 在程序onCreate时就可以调用 VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); 即可。

 

 

介绍一下图片占用进程的内存算法吧。
android中处理图片的基础类是Bitmap,顾名思义,就是位图。占用内存的算法如下:
图片的width*height*Config。
如果Config设置为ARGB_8888,那么上面的Config就是4。一张480*320的图片占用的内存就是480*320*4 byte。
前面有人说了一下8M的概念,其实是在默认情况下android进程的内存占用量为16M,因为Bitmap他除了java中持有数据外,底层C++的 skia图形库还会持有一个SKBitmap对象,因此一般图片占用内存推荐大小应该不超过8M。这个可以调整,编译源代码时可以设置参数。

0 0
原创粉丝点击