当前位置: 移动技术网 > IT编程>移动开发>Android > 总结Android App内存优化之图片优化

总结Android App内存优化之图片优化

2019年07月24日  | 移动技术网IT编程  | 我要评论

撕裂人1小游戏,三岁宝宝吃什么奶粉,奇趣网

前言

在android设备内存动不动就上g的情况下,的确没有必要去太在意app对android系统内存的消耗,但在实际工作中我做的是教育类的小学app,app中的按钮、背景、动画变换基本上全是图片,在2k屏上(分辨率2048*1536)一张背景图片就会占用内存12m,来回切换几次内存占用就会增涨到上百兆,为了在不影响app的视觉效果的前提下,有必要通过各种手段来降低app对内存的消耗。

通过ddms的app内存占用查看工具分析发现,app中占用内存最多的是图片,每个activity中图片占用内存占大半,本文重点分享对图片的内存优化。

不要将button的背景设置为selector

  在布局文件和代码中,都可以为button设置background为selector,这样方便实现按钮的正反选效果,但实际跟踪发现,如果是将button的背景设置为selector,在初始化button的时候会将正反选图片都加载在内存中(具体可以查看android源码,在类drawable.javacreatefromxmlinner方法中对图片进行解析,最终调用drawableinflate方法),相当于一个按钮占用了两张相同大小图片所使用的内存,如果一个界面上按钮很多或者是按钮很大,光是按钮占用的内存就会很大,可以通过在布局文件中给按钮只设置正常状态下的背景图片,然后在代码中监听按钮的点击状态,当按下按钮时为按钮设置反选效果的图片,抬起时重新设置为正常状态下的背景,具体实现方式如下:

 public class imagebuttonclickutils {
 private imagebuttonclickutils(){

 }

 /**
  * 设置按钮的正反选效果
  * 
  * */
 public static void setclickstate(view view, final int normalresid, final int pressresid){
  view.setontouchlistener(new ontouchlistener() {
  @override
  public boolean ontouch(view v, motionevent event) {
   switch(event.getaction()){
   case motionevent.action_down:{
   v.setbackgroundresource(pressresid);
   }
   break;
   case motionevent.action_move:{
   v.setbackgroundresource(pressresid);
   }
   break;
   case motionevent.action_up:{
   v.setbackgroundresource(normalresid);
   }
   break;
   default:{

   }
   break;
   }

   // 为了不影响监听按钮的onclick回调,返回值应为false
   return false;
  }
  });
 }
}

  通过上面这种方式就可以解决同一个按钮占用两倍内存的问题,如果你觉得为一个按钮提供正反选两张图片会导致apk的体积变大,可以通过如下方式实现按钮点击的反选效果,这种方式既不会存在button占用两倍内存的情况,又减小了apk的体积(android 5.0中的tintcolor也可以实现类似的效果):

 imagebutton personalinfobtn = (imagebutton)findviewbyid(r.id.personalbtnid);
 personalinfobtn.setontouchlistener(new ontouchlistener() {
 @suppresslint("clickableviewaccessibility")
 @override
 public boolean ontouch(view v, motionevent event) {
  int action = event.getaction();

  if(action == motionevent.action_down){
  ((imagebutton)v).setcolorfilter(getresources().getcolor(0x50000000));
  }else if(action == motionevent.action_up || action == motionevent.action_cancel){
  ((imagebutton)v).clearcolorfilter();
  }

  // 为了不影响监听按钮的onclick回调,返回值应为false
  return false;
 }
 });

将背景图片放在非ui线程绘制,提升app的效率

  在高分辨率的平板设备上,绘制大背景的图片会影响程序的运行效率,严重情况下就和没有开硬件加速的时候使用手写功能一样,相当地卡,最后我们的解决方案是将背景图片通过surfaceview来绘制,这样相当于是在非ui线程绘制,不会影响到ui线程做其它事情:

import android.content.context;
import android.content.res.typedarray;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.graphics.canvas;
import android.graphics.matrix;
import android.graphics.pixelformat;
import android.util.attributeset;
import android.util.displaymetrics;
import android.view.surfaceholder;
import android.view.surfaceview;

import com.eebbk.hanzilearning.activity.r;

public class rootsurfaceview extends surfaceview implements surfaceholder.callback, runnable{
 private float mviewwidth = 0;
 private float mviewheight = 0;
 private int mresourceid = 0;
 private context mcontext = null;
 private volatile boolean isrunning = false;
 private surfaceholder msurfaceholder = null;

 public rootsurfaceview(context context, attributeset attrs, int defstyleattr) {
 super(context, attrs, defstyleattr);
 initrootsurfaceview(context, attrs, defstyleattr, 0);
 }

 public rootsurfaceview(context context, attributeset attrs) {
 super(context, attrs);
 initrootsurfaceview(context, attrs, 0, 0);
 }

 private void initrootsurfaceview(context context, attributeset attrs, int defstyleattr, int defstyleres){
 mcontext = context;
 displaymetrics displaymetrics = context.getresources().getdisplaymetrics();
 typedarray a = context.obtainstyledattributes(attrs, r.styleable.rootsurfaceview, defstyleattr, defstyleres);
 int n = a.getindexcount();
 mviewwidth = displaymetrics.widthpixels;
 mviewheight = displaymetrics.heightpixels;
 for(int index=0; index<n; index++){
  int attr = a.getindex(index);
  switch(attr){
  case r.styleable.rootsurfaceview_background:{
  mresourceid = a.getresourceid(attr, 0);
  }
  break;
  case r.styleable.rootsurfaceview_view_width:{
  mviewwidth = a.getdimension(attr, displaymetrics.widthpixels);
  }
  break;
  case r.styleable.rootsurfaceview_view_height:{
  mviewheight = a.getdimension(attr, displaymetrics.heightpixels);
  }
  break;
  default:{

  }
  break;
  }
 }
 a.recycle();
 msurfaceholder = getholder();
 msurfaceholder.addcallback(this);
 msurfaceholder.setformat(pixelformat.translucent);
 }

 private bitmap getdrawbitmap(context context, float width, float height) {
 bitmap bitmap = bitmapfactory.decoderesource(getresources(), mresourceid);
 bitmap resultbitmap = zoomimage(bitmap, width, height);
 return resultbitmap;
 }

 @override
 public void surfacechanged(surfaceholder arg0, int arg1, int arg2, int arg3) {
 system.out.println("rootsurfaceview surfacechanged");
 }

 @override
 public void surfacecreated(surfaceholder holder) {
 drawbackground(holder);
 system.out.println("rootsurfaceview surfacecreated");
 }

 @override
 public void surfacedestroyed(surfaceholder holder) {
 isrunning = false;
 system.out.println("rootsurfaceview surfacedestroyed");
 }

 @override
 protected void onattachedtowindow() {
 super.onattachedtowindow();
 system.out.println("rootsurfaceview onattachedtowindow");
 }

 @override
 protected void ondetachedfromwindow() {
 super.ondetachedfromwindow();
 system.out.println("rootsurfaceview ondetachedfromwindow");
 }

 @override
 public void run(){ 
 while(isrunning){ 
  synchronized (msurfaceholder) { 
  if(!msurfaceholder.getsurface().isvalid()){
   continue;
  }
  drawbackground(msurfaceholder);
  }
  isrunning = false;
  break;
 } 
 }

 private void drawbackground(surfaceholder holder) {
 canvas canvas = holder.lockcanvas();
 bitmap bitmap = getdrawbitmap(mcontext, mviewwidth, mviewheight);
 canvas.drawbitmap(bitmap, 0, 0, null);
 bitmap.recycle();
 holder.unlockcanvasandpost(canvas);
 }

 public static bitmap zoomimage( bitmap bgimage , float newwidth , float newheight ) {
 float width = bgimage.getwidth( );
 float height = bgimage.getheight( );
 matrix matrix = new matrix();
 float scalewidth = newwidth/width;
 float scaleheight = newheight/height;
 matrix.postscale( scalewidth, scaleheight );
 bitmap bitmap = bitmap.createbitmap( bgimage, 0, 0, ( int ) width , ( int ) height, matrix, true );
 if( bitmap != bgimage ){
  bgimage.recycle();
  bgimage = null;
 }
 return bitmap;
 }
}

  在res/values/attr.xml文件中定义自定义view的自定义属性:

<declare-styleable name="rootsurfaceview">
 <attr name="background" format="reference" />
 <attr name="view_width" format="dimension" />
 <attr name="view_height" format="dimension" />
</declare-styleable>

没有必要使用硬件加速的界面建议关掉硬件加速

  通过ddms的heap跟踪发现,相比于关闭硬件加速,在打开硬件加速的情况下会消耗更多的内存,但有的界面打开或者关闭硬件加速对程序的运行效率并没有太大的影响,此种情况下可以考虑在androidmanifest.xml文件中关闭掉对应activity的硬件加速,like this:

<!-- 设置界面 -->
<activity
 android:name=".settingactivity"
 android:hardwareaccelerated="false"
 android:screenorientation="sensorlandscape"
 android:theme="@style/translucent_notitle">
</activity>

注意:如果使用到webview、视频播放、手写、动画等功能时,关掉硬件加速会严重音效程序的运行效率,这种情况可以只关闭掉activity中某些view的硬件加速,整个activity的硬件加速不关闭。

  如果activity中某个view需要关闭硬件加速,但整个activity不能关闭,可以调用view层级关闭硬件加速的方法:

// view.setlayertype || 在定义view的构造方法中调用该方法
setlayertype(view.layer_type_software, null);

尽量少用animationdrawable,如果必须要可以自定义图片切换器代替animationdrawable

  animationdrawable也是一个耗内存大户,图片帧数越多耗内存越大,具体可以查看animationdrawable的源码,在animationdrawable实例化的时候,drawable的createfromxmlinner方法会调用animationdrawable的inflate方法,该方法里面有一个while循环去一次性将所有帧都读取出来,也就是在初始化的时候就将所有的帧读在内存中了,有多少张图片,它就要消耗对应大小的内存。

  虽然可以通过如下方式释放animationdrawable占用的内存,但是当退出使用animationdrawable的界面,再次进入使用其播放动画时,会报使用已经回收了的图片的异常,这个应该是android对图片的处理机制导致的,虽然activity被finish掉了,但是这个activity中使用到的图片还是在内存中,如果被回收,下次进入时就会报异常信息:

/**
 * 释放animationdrawable占用的内存
 * 
 * 
 * */
@suppresswarnings("unused")
private void freeanimationdrawable(animationdrawable animationdrawable) {
 animationdrawable.stop(); 
 for (int i = 0; i < animationdrawable.getnumberofframes(); ++i){
 drawable frame = animationdrawable.getframe(i);
 if (frame instanceof bitmapdrawable) {
  ((bitmapdrawable)frame).getbitmap().recycle();
 } 
 frame.setcallback(null);
 } 

 animationdrawable.setcallback(null);
}

  通常情况下我会自定义一个imageview来实现animationdrawable的功能,根据图片之间切换的时间间隔来定时设置imageview的背景图片,这样始终只是一个imageview实例,更换的只是其背景,占用内存会比animationdrawable小很多:

/**
 * 图片动态切换器
 * 
 * */
public class animimageview {
 private static final int msg_start = 0xf1;
 private static final int msg_stop = 0xf2;
 private static final int state_stop = 0xf3;
 private static final int state_running = 0xf4;

 /* 运行状态*/
 private int mstate = state_running;
 private imageview mimageview;
 /* 图片资源id列表*/
 private list<integer> mresourceidlist = null;
 /* 定时任务*/
 private timer mtimer = null;
 private animtimertask mtimetask = null;
 /* 记录播放位置*/
 private int mframeindex = 0;
 /* 播放形式*/
 private boolean islooping = false;

 public animimageview( ){
 mtimer = new timer();
 }

 /**
 * 设置动画播放资源
 * 
 * */
 public void setanimation( hanziimageview imageview, list<integer> resourceidlist ){
 mimageview = imageview;
 mresourceidlist = resourceidlist;
 }

 /**
 * 开始播放动画
 * @param loop 时候循环播放
 * @param duration 动画播放时间间隔
 * */
 public void start(boolean loop, int duration){
 stop();
 islooping = loop;
 mframeindex = 0;
 mstate = state_running;
 mtimetask = new animtimertask( );
 mtimer.schedule(mtimetask, 0, duration);
 }

 /**
 * 停止动画播放
 * 
 * */
 public void stop(){
 if (mtimetask != null) {
  mframeindex = 0;
  mstate = state_stop;
  mtimer.purge();
  mtimetask.cancel();
  mtimetask = null;
  mimageview.setbackgroundresource(0);
 }
 }

 /**
 * 定时器任务
 * 
 * 
 */
 class animtimertask extends timertask {
 @override
 public void run() {
  if(mframeindex < 0 || mstate == state_stop){
  return;
  }

  if( mframeindex < mresourceidlist.size() ){
  message msg = animhanlder.obtainmessage(msg_start,0,0,null);
  msg.sendtotarget();
  }else{
  mframeindex = 0;
  if(!islooping){
   message msg = animhanlder.obtainmessage(msg_stop,0,0,null);
   msg.sendtotarget();
  }
  }
 }
 }

 private handler animhanlder = new handler(){
  public void handlemessage(android.os.message msg) {
  switch (msg.what) {
  case msg_start:{
   if(mframeindex >=0 && mframeindex < mresourceidlist.size() && mstate == state_running){
   mimageview.setimageresource(mresourceidlist.get(mframeindex));
   mframeindex++;
   }
  }
   break;
  case msg_stop:{
   if (mtimetask != null) {
   mframeindex = 0;
   mtimer.purge();
   mtimetask.cancel();
   mstate = state_stop;
   mtimetask = null;
   mimageview.setimageresource(0);
   }
  }
   break;
  default:
   break;
  }
  }
 };
}

其它优化方式

1、尽量将activity中的小图片和背景合并,一张小图片既浪费布局的时间,又平白地增加了内存占用;

2、不要在activity的主题中为activity设置默认的背景图片,这样会导致activity占用的内存翻倍:

<!--千万不要在主题中为activity设置默认背景

<style name="activity_style" parent="@android:theme.holo.light.noactionbar">
<item name="android:background">@drawable/*</item>
</style>

3、对于在需要时才显示的图片或者布局,可以使用viewstub标签,通过sdk/tools目录下的hierarchyviewer.bat查看布局文件会发现,使用viewstub标签的组件几乎不消耗布局的时间,在代码中当需要显示时再去实例化有助于提高activity的布局效率和节省activity消耗的内存。

总结

以上就是本文的全部内容,希望对大家开发android能有所帮助,如果有疑问可以留言讨论。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网