1. 程式人生 > >Android 卡頓優化 2 渲染優化

Android 卡頓優化 2 渲染優化

運動 發布 Language 嚴重 onresume 背景色 容易 微信 對比

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可以幫助我們發現類似的問題。

Android 卡頓優化 2 渲染優化