Android 卡頓優化 2 渲染優化


1、概述

2015年初google發布了Android性能優化典范,發了16個小視頻供大家欣賞,當時我也將其下載,通過微信公眾號給大家推送了百度雲的下載地址(地址在文末,ps:歡迎大家訂閱公眾號),那么近期google又在udacity上開了系列類的相關課程。有了上述的參考,那么本性能優化實戰教程就有了堅實的基礎,本系列將結合實例為大家展示如何去識別診斷解決Android應用開發中存在的性能問題。那么首先帶來的就是大家最關注的渲染的性能優化(~~渲染就是把東西繪制到屏幕上)。

ps:本博客所有案例可能並不會完全按照Google給出的例子,因為范例代碼比較多且不好在博客中展示,所以基本代碼都會經過調整,但表達的意思不會變。

2、 Android渲染機制

大家自己編寫App的時候,有時會感覺界面卡頓,尤其是自定義View的時候,大多數是因為布局的層次過多,存在不必要的繪制,或者onDraw等方法中過於耗時。那么究竟需要多快,才能給用戶一個流暢的體驗呢?那么就需要簡單了解下Android的渲染機制,一圖勝千言:

Android系統每隔16ms發出VSYNC信號,觸發對UI進行渲染,那么整個過程如果保證在16ms以內就能達到一個流暢的畫面。那么如果操作超過了16ms就會發生下面的情況:

如果系統發生的VSYNC信號,而此時無法進行渲染,還在做別的操作,那么就會導致丟幀的現象,(大家在察覺到APP卡頓的時候,可以看看logcat控制太,會有drop frames類似的警告)。這樣的話,繪制就會在下一個16ms的時候才進行繪制,即使只丟一幀,用戶也會發現卡頓的~~(ps:上面標識不應該是32ms么,咋是34ms,難道我錯過了什么)。

好了,很多朋友會不會奇怪為什么是16ms,16ms意味着着1000/60hz,相當於60fps,那么只要解釋為什么是60fps,好在這個問題,網上有解答:

這是因為人眼與大腦之間的協作無法感知超過60fps的畫面更新。12fps大概類似手動快速翻動書籍的幀率,這明顯是可以感知到不夠順滑的。24fps使得人眼感知的是連續線性的運動,這其實是歸功於運動模糊的
效果。24fps是電影膠圈通常使用的幀率,因為這個幀率已經足夠支撐大部分電影畫面需要表達的內容,同時能夠最大的減少費用支出。但是低於30fps是
無法順暢表現絢麗的畫面內容的,此時就需要用到60fps來達到想要的效果,當然超過60fps是沒有必要的(據說Dart能夠帶來120fps的體驗)。本引用來源:Google 發布 Android 性能優化典范 - 開源中國社區

好了,有了對Android渲染機制基本的認識以后,那么我們的卡頓的原因就在於沒有辦法在16ms內完成該完成的操作,而主要因素是在於沒有必要的layouts、invalidations、Overdraw。渲染的過程是由CPU與GPU協作完成,下面一張圖很好的展示出了CPU和GPU的工作,以及潛在的問題,檢測的工具和解決方案。


如果你對上圖感到不理解,沒關系,你只要知道問題:

  • 通過Hierarchy Viewer去檢測渲染效率,去除不必要的嵌套
  • 通過Show GPU Overdraw去檢測Overdraw,最終可以通過移除不必要的背景以及使用canvas.clipRect解決大多數問題。

如果你還覺得不能理解,沒關系,文本畢竟是枯燥的,那么結合實例來展示優化的過程。

3、Overdraw的檢測

對於性能優化,那么首先肯定是去發現問題,那么對么overdraw這個問題,還是比較容易發現的。
按照以下步驟打開Show GPU Overrdraw的選項:

設置 -> 開發者選項 -> 調試GPU過度繪制 -> 顯示GPU過度繪制

好了,打開以后呢,你會發現屏幕上有各種顏色,此時你可以切換到需要檢測的程序,對於各個色塊,對比一張Overdraw的參考圖:

那么如果你發現你的app上深紅色的色塊比較多,那么可能就要注意了,接下來就開始說如果遇到overdraw的情況比較嚴重我們該則么處理。

4、Overdraw 的處理方案一:移除不必要的background

下面看一個簡單的展示ListView的例子:

  • activity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:background="@android:color/white" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="@dimen/narrow_space" android:textSize="@dimen/large_text_size" android:layout_marginBottom="@dimen/wide_space" android:text="@string/header_text"/> <ListView android:id="@+id/id_listview_chats" android:layout_width="match_parent" android:background="@android:color/white" android:layout_height="wrap_content" android:divider="@android:color/transparent" android:dividerHeight="@dimen/divider_height"/> </LinearLayout> 

 

  • item的布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:paddingBottom="@dimen/chat_padding_bottom"> <ImageView android:id="@+id/id_chat_icon" android:layout_width="@dimen/avatar_dimen" android:layout_height="@dimen/avatar_dimen" android:src="@drawable/joanna" android:layout_margin="@dimen/avatar_layout_margin" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/darker_gray" android:orientation="vertical"> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/white" android:textColor="#78A" android:orientation="horizontal"> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:padding="@dimen/narrow_space" android:text="@string/hello_world" android:gravity="bottom" android:id="@+id/id_chat_name" /> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textStyle="italic" android:text="@string/hello_world" android:padding="@dimen/narrow_space" android:id="@+id/id_chat_date" /> </RelativeLayout> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="@dimen/narrow_space" android:background="@android:color/white" android:text="@string/hello_world" android:id="@+id/id_chat_msg" /> </LinearLayout> </LinearLayout> 

 

  • Activity的代碼
package com.zhy.performance_01_render; import android.os.Bundle; import android.os.PersistableBundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; /** * Created by zhy on 15/4/29. */ public class OverDrawActivity01 extends AppCompatActivity { private ListView mListView; private LayoutInflater mInflater ; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_overdraw_01); mInflater = LayoutInflater.from(this); mListView = (ListView) findViewById(R.id.id_listview_chats); mListView.setAdapter(new ArrayAdapter<Droid>(this, -1, Droid.generateDatas()) { @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null ; if(convertView == null) { convertView = mInflater.inflate(R.layout.chat_item,parent,false); holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.id_chat_icon); holder.name = (TextView) convertView.findViewById(R.id.id_chat_name); holder.date = (TextView) convertView.findViewById(R.id.id_chat_date); holder.msg = (TextView) convertView.findViewById(R.id.id_chat_msg); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } Droid droid = getItem(position); holder.icon.setBackgroundColor(0x44ff0000); holder.icon.setImageResource(droid.imageId); holder.date.setText(droid.date); holder.msg.setText(droid.msg); holder.name.setText(droid.name); return convertView; } class ViewHolder { ImageView icon; TextView name; TextView date; TextView msg; } }); } } 

 

  • 實體的代碼
package com.zhy.performance_01_render; import java.util.ArrayList; import java.util.List; public class Droid { public String name; public int imageId; public String date; public String msg; public Droid(String msg, String date, int imageId, String name) { this.msg = msg; this.date = date; this.imageId = imageId; this.name = name; } public static List<Droid> generateDatas() { List<Droid> datas = new ArrayList<Droid>(); datas.add(new Droid("Lorem ipsum dolor sit amet, orci nullam cra", "3分鍾前", -1, "alex")); datas.add(new Droid("Omnis aptent magnis suspendisse ipsum, semper egestas", "12分鍾前", R.drawable.joanna, "john")); datas.add(new Droid("eu nibh, rhoncus wisi posuere lacus, ad erat egestas", "17分鍾前", -1, "7heaven")); datas.add(new Droid("eu nibh, rhoncus wisi posuere lacus, ad erat egestas", "33分鍾前", R.drawable.shailen, "Lseven")); return datas; } } 

 

現在的效果是:

注意,我們的需求是整體是Activity是個白色的背景。

開啟Show GPU Overdraw以后:

對比上面的參照圖,可以發現一個簡單的ListView展示Item,竟然很多地方被過度繪制了4X 。 那么,其實主要原因是由於該布局文件中存在很多不必要的背景,仔細看上述的布局文件,那么開始移除吧。

  • 不必要的Background 1

    我們主布局的文件已經是background為white了,那么可以移除ListView的白色背景

  • 不必要的Background 2

    Item布局中的LinearLayout的android:background="@android:color/darker_gray"

  • 不必要的Background 3

    Item布局中的RelativeLayout的android:background="@android:color/white"

  • 不必要的Background 4

    Item布局中id為id_msg的TextView的android:background="@android:color/white"

這四個不必要的背景也比較好找,那么移除后的效果是:

對比之前的是不是好多了~~~接下來還存在一些不必要的背景,你還能找到嗎?

  • 不必要的Background 5

這個背景比較難發現,主要需要看Adapter的getView的代碼,上述代碼你會發現,首先為每個icon設置了背景色(主要是當沒有icon圖的時候去顯示),然后又設置了一個頭像。那么就造成了overdraw,有頭像的完全沒必要去繪制背景,所有修改代碼:

Droid droid = getItem(position);
                if(droid.imageId ==-1) { holder.icon.setBackgroundColor(0x4400ff00); holder.icon.setImageResource(android.R.color.transparent); }else { holder.icon.setImageResource(droid.imageId); holder.icon.setBackgroundResource(android.R.color.transparent); } 

 

ok,還有最后一個,這個也是非常容易被忽略的。

  • 不必要的Background 6

記得我們之前說,我們的這個Activity要求背景色是白色,我們的確在layout中去設置了背景色白色,那么這里注意下,我們的Activity的布局最終會添加在DecorView中,這個View會中的背景是不是就沒有必要了,所以我們希望調用mDecor.setWindowBackground(drawable);,那么可以在Activity調用getWindow().setBackgroundDrawable(null);

setContentView(R.layout.activity_overdraw_01);
        getWindow().setBackgroundDrawable(null);

 

ok,一個簡單的listview顯示item,我們一共找出了6個不必要的背景,現在再看最后的Show GPU Overdraw 與最初的比較。

ok,對比參照圖,基本已經達到了最優的狀態。

5、Overdraw 的處理方案二:clipRect的妙用

我們在自定義View的時候,經常會由於疏忽造成很多不必要的繪制,比如大家看下面這樣的圖:

多張卡片疊加,那么如果你是一張一張卡片從左到右的繪制,效果肯定沒問題,但是疊加的區域肯定是過度繪制了。
並且material design對於界面設計的新的風格更容易造成上述的問題。那么有什么好的方法去改善呢?
答案是有的,android的Canvas對象給我們提供了很便利的方法clipRect就可以很好的去解決這類問題。

下面通過一個實例來展示,那么首先看一個效果圖:

左邊顯示的時效果圖,右邊顯示的是開啟Show Override GPU之后的效果,可以看到,卡片疊加處明顯的過度渲染了。 (ps:我對這個View添加了一個背景色~~仔細看下面的代碼) * View代碼
package com.zhy.performance_01_render; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.View; /** * Created by zhy on 15/4/30. */ public class CardView extends View { private Bitmap[] mCards = new Bitmap[3]; private int[] mImgId = new int[]{R.drawable.alex, R.drawable.chris, R.drawable.claire}; public CardView(Context context) { super(context); Bitmap bm = null; for (int i = 0; i < mCards.length; i++) { bm = BitmapFactory.decodeResource(getResources(), mImgId[i]); mCards[i] = Bitmap.createScaledBitmap(bm, 400, 600, false); } setBackgroundColor(0xff00ff00); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); canvas.translate(20, 120); for (Bitmap bitmap : mCards) { canvas.translate(120, 0); canvas.drawBitmap(bitmap, 0, 0, null); } canvas.restore(); } } 

 

  • Activity代碼
/** * Created by zhy on 15/4/30. */ public class OverDrawActivity02 extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new CardView(this)); } }

 

那么大家可以考慮下如何去優化,其實很明顯哈,我們上面已經說了使用cliprect方法,那么我們目標直指
自定義View的onDraw方法。
修改后的代碼:


 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); canvas.translate(20, 120); for (int i = 0; i < mCards.length; i++) { canvas.translate(120, 0); canvas.save(); if (i < mCards.length - 1) { canvas.clipRect(0, 0, 120, mCards[i].getHeight()); } canvas.drawBitmap(mCards[i], 0, 0, null); canvas.restore(); } canvas.restore(); }

 

分析得出,除了最后一張需要完整的繪制,其他的都只需要繪制部分;所以我們在循環的時候,給i到n-1都添加了clipRect的代碼。

最后的效果圖:

可以看到,所有卡片變為了淡紫色,對比參照圖,都是1X過度繪制,那么是因為我的View添加了一個
ff00ff00的背景,可以說明已經是最優了。

如果你按照上面的修改,會發現最終效果圖不是淡紫色,而是青色(2X),那是為什么呢?因為你還忽略了
一個優化的地方,本View已經有了不透明的背景,完全可以移除Window的背景了,即在Activity中,添加getWindow().setBackgroundDrawable(null);代碼。

好了,說完了Overdraw的檢測與處理,那么還剩下一個layouts、invalidations過慢的問題,那么這類問題主要可能是你的XML層級過多導致的,當然也有很好的工具可以用來檢測,那么就是Hierarchy Viewer

6、減少不必要的層次:巧用Hierarchy Viewer

1、Hierarchy Viewer工具簡介

Android SDK中包含這個工具,不過大家肯定也不陌生了~~~

那么就簡單說一下它在哪,如何使用,以及真機無法使用該工具該怎么解決。

  • Hierarchy Viewer在哪?

本博客使用IDE為Android Studio,那么只需要按照下圖步驟即可找到:

其他IDE的兄弟,找到這個肯定沒問題,不過還是建議慢慢的轉向AS。

  • 如何使用?

一圖勝千言:

關注下,所有框住的區域~~

  • 無法連接真機調試怎么辦?

如果你不存在這樣的問題,直接跳過本節。

Android的官方文檔中,有這么一句話:

出於安全考慮,Hierarchy Viewer只能連接Android開發版手機或是模擬器

看來的確是存在這樣的問題了,並且網上也有一些解決方案,修改源碼神馬的,有興趣去試試。
這里推薦一種解決方案:romainguy在github上有個項目ViewServer,可以下載下來導入到IDE中,里面有個ViewServer的類,類注釋上也標注了用法,在你希望調試的Activity以下該三個方法中,添加幾行代碼:

 * <pre>
 * public class MyActivity extends Activity { * public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * // Set content view, etc. * ViewServer.get(this).addWindow(this); * } * * public void onDestroy() { * super.onDestroy(); * ViewServer.get(this).removeWindow(this); * } * * public void onResume() { * super.onResume(); * ViewServer.get(this).setFocusedWindow(this); * } * } * </pre>

 

記得先添加依賴,別問我怎么找不到ViewServer這個類,添加以上3行以后,手機運行至該Activity,重啟下Android Device Moniter,然后就ok了,我就是這種方法調試的,哈~~

2、優化案例

好了,上面介紹完成了如何使用Hierarchy Viewer,下面使用一個案例來說明問題。
主要就是個布局文件:

  • 布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- Version 1. Uses nested LinearLayouts --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/activity_vertical_margin"> <ImageView android:id="@+id/chat_author_avatar1" android:layout_width="@dimen/avatar_dimen" android:layout_height="@dimen/avatar_dimen" android:layout_margin="@dimen/avatar_layout_margin" android:src="@drawable/joanna"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/line1_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/line2_text"/> </LinearLayout> </LinearLayout> <!-- Version 2: uses a single RelativeLayout --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="@dimen/activity_vertical_margin"> <ImageView android:id="@+id/chat_author_avatar2" android:layout_width="@dimen/avatar_dimen" android:layout_height="@dimen/avatar_dimen" android:layout_margin="@dimen/avatar_layout_margin" android:src="@drawable/joanna"/> <TextView android:id="@+id/rl_line1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/chat_author_avatar2" android:text="@string/line1_text" /> <TextView android:id="@+id/rl_line2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/rl_line1" android:layout_toRightOf="@id/chat_author_avatar2" android:text="@string/line2_text" /> </RelativeLayout> </LinearLayout> 

 

  • Activity
package com.zhy.performance_01_render; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.android.debug.hv.ViewServer; public class CompareLayoutActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_compare_layouts); ViewServer.get(this).addWindow(this); } @Override protected void onResume() { super.onResume(); ViewServer.get(this).setFocusedWindow(this); } @Override protected void onDestroy() { super.onDestroy(); ViewServer.get(this).removeWindow(this); } } 

 

可以看到我們的Activity里面添加了ViewServer相關的幾行代碼。
然后手機打開此Activity,打開Android Device Moniter,切換到Hierarchy Viewer視圖,可以看到:

點擊LinearLayout,然后點擊Profile Node,你會發現所有的子View上面都有了3個圈圈,
(取色范圍為紅、黃、綠色),這三個圈圈分別代表measure 、layout、draw的速度,並且你也可以看到實際的運行的速度,如果你發現某個View上的圈是紅色,那么說明這個View相對其他的View,該操作運行最慢,注意只是相對別的View,並不是說就一定很慢。

紅色的指示能給你一個判斷的依據,具體慢不慢還是需要你自己去判斷的。

好了,上面的布局文件展示了ListView的Item的編寫的兩個版本,一個是Linearlayout嵌套的,一個是RelativeLayout的。上圖也可以看出Linearlayout的版本相對RelativeLayout的版本要慢很多(請多次點擊Profile Node取樣)。即可說明RelativeLayout的版本更優於RelativeLayout的寫法,並且Hierarchy Viewer可以幫助我們發現類似的問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM