欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

總結(jié)Android App內(nèi)存優(yōu)化之圖片優(yōu)化

 更新時(shí)間:2016年08月22日 17:02:13   投稿:daisy  
網(wǎng)上有很多大拿分享的關(guān)于A(yíng)ndroid性能優(yōu)化的文章,主要是通過(guò)各種工具分析,使用合理的技巧優(yōu)化APP的體驗(yàn),提升APP的流暢度,但關(guān)于內(nèi)存優(yōu)化的文章很少有看到。下面是我在實(shí)踐過(guò)程中使用的一些方法,很多都是不太成熟的項(xiàng)目,只是將其作為一種處理方式分享給大家。

前言

在A(yíng)ndroid設(shè)備內(nèi)存動(dòng)不動(dòng)就上G的情況下,的確沒(méi)有必要去太在意APP對(duì)Android系統(tǒng)內(nèi)存的消耗,但在實(shí)際工作中我做的是教育類(lèi)的小學(xué)APP,APP中的按鈕、背景、動(dòng)畫(huà)變換基本上全是圖片,在2K屏上(分辨率2048*1536)一張背景圖片就會(huì)占用內(nèi)存12M,來(lái)回切換幾次內(nèi)存占用就會(huì)增漲到上百兆,為了在不影響APP的視覺(jué)效果的前提下,有必要通過(guò)各種手段來(lái)降低APP對(duì)內(nèi)存的消耗。

通過(guò)DDMS的APP內(nèi)存占用查看工具分析發(fā)現(xiàn),APP中占用內(nèi)存最多的是圖片,每個(gè)Activity中圖片占用內(nèi)存占大半,本文重點(diǎn)分享對(duì)圖片的內(nèi)存優(yōu)化。

不要將Button的背景設(shè)置為selector

  在布局文件和代碼中,都可以為Button設(shè)置background為selector,這樣方便實(shí)現(xiàn)按鈕的正反選效果,但實(shí)際跟蹤發(fā)現(xiàn),如果是將Button的背景設(shè)置為selector,在初始化Button的時(shí)候會(huì)將正反選圖片都加載在內(nèi)存中(具體可以查看Android源碼,在類(lèi)Drawable.javacreateFromXmlInner方法中對(duì)圖片進(jìn)行解析,最終調(diào)用Drawableinflate方法),相當(dāng)于一個(gè)按鈕占用了兩張相同大小圖片所使用的內(nèi)存,如果一個(gè)界面上按鈕很多或者是按鈕很大,光是按鈕占用的內(nèi)存就會(huì)很大,可以通過(guò)在布局文件中給按鈕只設(shè)置正常狀態(tài)下的背景圖片,然后在代碼中監(jiān)聽(tīng)按鈕的點(diǎn)擊狀態(tài),當(dāng)按下按鈕時(shí)為按鈕設(shè)置反選效果的圖片,抬起時(shí)重新設(shè)置為正常狀態(tài)下的背景,具體實(shí)現(xiàn)方式如下:

 public class ImageButtonClickUtils {
 private ImageButtonClickUtils(){

 }

 /**
  * 設(shè)置按鈕的正反選效果
  * 
  * */
 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;
   }

   // 為了不影響監(jiān)聽(tīng)按鈕的onClick回調(diào),返回值應(yīng)為false
   return false;
  }
  });
 }
}

  通過(guò)上面這種方式就可以解決同一個(gè)按鈕占用兩倍內(nèi)存的問(wèn)題,如果你覺(jué)得為一個(gè)按鈕提供正反選兩張圖片會(huì)導(dǎo)致APK的體積變大,可以通過(guò)如下方式實(shí)現(xiàn)按鈕點(diǎn)擊的反選效果,這種方式既不會(huì)存在Button占用兩倍內(nèi)存的情況,又減小了APK的體積(Android 5.0中的tintColor也可以實(shí)現(xiàn)類(lèi)似的效果):

 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();
  }

  // 為了不影響監(jiān)聽(tīng)按鈕的onClick回調(diào),返回值應(yīng)為false
  return false;
 }
 });

將背景圖片放在非UI線(xiàn)程繪制,提升APP的效率

  在高分辨率的平板設(shè)備上,繪制大背景的圖片會(huì)影響程序的運(yùn)行效率,嚴(yán)重情況下就和沒(méi)有開(kāi)硬件加速的時(shí)候使用手寫(xiě)功能一樣,相當(dāng)?shù)乜ǎ詈笪覀兊慕鉀Q方案是將背景圖片通過(guò)SurfaceView來(lái)繪制,這樣相當(dāng)于是在非UI線(xiàn)程繪制,不會(huì)影響到UI線(xiàn)程做其它事情:

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>

沒(méi)有必要使用硬件加速的界面建議關(guān)掉硬件加速

  通過(guò)DDMS的heap跟蹤發(fā)現(xiàn),相比于關(guān)閉硬件加速,在打開(kāi)硬件加速的情況下會(huì)消耗更多的內(nèi)存,但有的界面打開(kāi)或者關(guān)閉硬件加速對(duì)程序的運(yùn)行效率并沒(méi)有太大的影響,此種情況下可以考慮在A(yíng)ndroidManifest.xml文件中關(guān)閉掉對(duì)應(yīng)Activity的硬件加速,like this:

<!-- 設(shè)置界面 -->
<activity
 android:name=".SettingActivity"
 android:hardwareAccelerated="false"
 android:screenOrientation="sensorLandscape"
 android:theme="@style/Translucent_NoTitle">
</activity>

注意:如果使用到WebView、視頻播放、手寫(xiě)、動(dòng)畫(huà)等功能時(shí),關(guān)掉硬件加速會(huì)嚴(yán)重音效程序的運(yùn)行效率,這種情況可以只關(guān)閉掉Activity中某些view的硬件加速,整個(gè)Activity的硬件加速不關(guān)閉。

  如果Activity中某個(gè)View需要關(guān)閉硬件加速,但整個(gè)Activity不能關(guān)閉,可以調(diào)用view層級(jí)關(guān)閉硬件加速的方法:

// view.setLayerType || 在定義view的構(gòu)造方法中調(diào)用該方法
setLayerType(View.LAYER_TYPE_SOFTWARE, null);

盡量少用AnimationDrawable,如果必須要可以自定義圖片切換器代替AnimationDrawable

  AnimationDrawable也是一個(gè)耗內(nèi)存大戶(hù),圖片幀數(shù)越多耗內(nèi)存越大,具體可以查看AnimationDrawable的源碼,在A(yíng)nimationDrawable實(shí)例化的時(shí)候,Drawable的createFromXmlInner方法會(huì)調(diào)用AnimationDrawable的inflate方法,該方法里面有一個(gè)while循環(huán)去一次性將所有幀都讀取出來(lái),也就是在初始化的時(shí)候就將所有的幀讀在內(nèi)存中了,有多少?gòu)垐D片,它就要消耗對(duì)應(yīng)大小的內(nèi)存。

  雖然可以通過(guò)如下方式釋放AnimationDrawable占用的內(nèi)存,但是當(dāng)退出使用AnimationDrawable的界面,再次進(jìn)入使用其播放動(dòng)畫(huà)時(shí),會(huì)報(bào)使用已經(jīng)回收了的圖片的異常,這個(gè)應(yīng)該是Android對(duì)圖片的處理機(jī)制導(dǎo)致的,雖然Activity被finish掉了,但是這個(gè)Activity中使用到的圖片還是在內(nèi)存中,如果被回收,下次進(jìn)入時(shí)就會(huì)報(bào)異常信息:

/**
 * 釋放AnimationDrawable占用的內(nèi)存
 * 
 * 
 * */
@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);
}

  通常情況下我會(huì)自定義一個(gè)ImageView來(lái)實(shí)現(xiàn)AnimationDrawable的功能,根據(jù)圖片之間切換的時(shí)間間隔來(lái)定時(shí)設(shè)置ImageView的背景圖片,這樣始終只是一個(gè)ImageView實(shí)例,更換的只是其背景,占用內(nèi)存會(huì)比AnimationDrawable小很多:

/**
 * 圖片動(dòng)態(tài)切換器
 * 
 * */
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;

 /* 運(yùn)行狀態(tài)*/
 private int mState = STATE_RUNNING;
 private ImageView mImageView;
 /* 圖片資源ID列表*/
 private List<Integer> mResourceIdList = null;
 /* 定時(shí)任務(wù)*/
 private Timer mTimer = null;
 private AnimTimerTask mTimeTask = null;
 /* 記錄播放位置*/
 private int mFrameIndex = 0;
 /* 播放形式*/
 private boolean isLooping = false;

 public AnimImageView( ){
 mTimer = new Timer();
 }

 /**
 * 設(shè)置動(dòng)畫(huà)播放資源
 * 
 * */
 public void setAnimation( HanziImageView imageview, List<Integer> resourceIdList ){
 mImageView = imageview;
 mResourceIdList = resourceIdList;
 }

 /**
 * 開(kāi)始播放動(dòng)畫(huà)
 * @param loop 時(shí)候循環(huán)播放
 * @param duration 動(dòng)畫(huà)播放時(shí)間間隔
 * */
 public void start(boolean loop, int duration){
 stop();
 isLooping = loop;
 mFrameIndex = 0;
 mState = STATE_RUNNING;
 mTimeTask = new AnimTimerTask( );
 mTimer.schedule(mTimeTask, 0, duration);
 }

 /**
 * 停止動(dòng)畫(huà)播放
 * 
 * */
 public void stop(){
 if (mTimeTask != null) {
  mFrameIndex = 0;
  mState = STATE_STOP;
  mTimer.purge();
  mTimeTask.cancel();
  mTimeTask = null;
  mImageView.setBackgroundResource(0);
 }
 }

 /**
 * 定時(shí)器任務(wù)
 * 
 * 
 */
 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;
  }
  }
 };
}

其它優(yōu)化方式

1、盡量將Activity中的小圖片和背景合并,一張小圖片既浪費(fèi)布局的時(shí)間,又平白地增加了內(nèi)存占用;

2、不要在A(yíng)ctivity的主題中為Activity設(shè)置默認(rèn)的背景圖片,這樣會(huì)導(dǎo)致Activity占用的內(nèi)存翻倍:

<!--千萬(wàn)不要在主題中為Activity設(shè)置默認(rèn)背景

<style name="Activity_Style" parent="@android:Theme.Holo.Light.NoActionBar">
<item name="android:background">@drawable/*</item>
</style>

3、對(duì)于在需要時(shí)才顯示的圖片或者布局,可以使用ViewStub標(biāo)簽,通過(guò)sdk/tools目錄下的hierarchyviewer.bat查看布局文件會(huì)發(fā)現(xiàn),使用viewstub標(biāo)簽的組件幾乎不消耗布局的時(shí)間,在代碼中當(dāng)需要顯示時(shí)再去實(shí)例化有助于提高Activity的布局效率和節(jié)省Activity消耗的內(nèi)存。

總結(jié)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家開(kāi)發(fā)Android能有所幫助,如果有疑問(wèn)可以留言討論。

相關(guān)文章

最新評(píng)論