转载请标明出处:
http://blog.csdn.net/lmj623565791/article/details/45556391;
本文出自:【张鸿洋的博客】java
2015年初google发布了Android性能优化典范,发了16个小视频供你们欣赏,当时我也将其下载,经过微信公众号给你们推送了百度云的下载地址(地址在文末,ps:欢迎你们订阅公众号),那么近期google又在udacity上开了系列类的相关课程。有了上述的参考,那么本性能优化实战教程就有了坚实的基础,本系列将结合实例为你们展现如何去识别
、诊断
、解决
Android应用开发中存在的性能问题。那么首先带来的就是你们最关注的渲染的性能优化(~~渲染就是把东西绘制到屏幕上)。android
ps:本博客全部案例可能并不会彻底按照Google给出的例子,由于范例代码比较多且很差在博客中展现,因此基本代码都会通过调整,但表达的意思不会变。git
你们本身编写App的时候,有时会感受界面卡顿,尤为是自定义View的时候,大多数是由于布局的层次过多,存在没必要要的绘制,或者onDraw等方法中过于耗时。那么究竟须要多快,才能给用户一个流畅的体验呢?那么就须要简单了解下Android的渲染机制,一图胜千言:github
Android系统每隔16ms发出VSYNC信号,触发对UI进行渲染,那么整个过程若是保证在16ms之内就能达到一个流畅的画面。那么若是操做超过了16ms就会发生下面的状况:canvas
若是系统发生的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的工做,以及潜在的问题,检测的工具和解决方案。markdown
若是你对上图感到不理解,不要紧,你只要知道问题:app
若是你还以为不能理解,不要紧,文本毕竟是枯燥的,那么结合实例来展现优化的过程。
对于性能优化,那么首先确定是去发现问题,那么对么overdraw这个问题,仍是比较容易发现的。
按照如下步骤打开Show GPU Overrdraw的选项:
设置 -> 开发者选项 -> 调试GPU过分绘制 -> 显示GPU过分绘制
好了,打开之后呢,你会发现屏幕上有各类颜色,此时你能够切换到须要检测的程序,对于各个色块,对比一张Overdraw的参考图:
那么若是你发现你的app上深红色的色块比较多,那么可能就要注意了,接下来就开始说若是遇到overdraw的状况比较严重咱们该则么处理。
下面看一个简单的展现ListView的例子:
<?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>
<?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>
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"
这四个没必要要的背景也比较好找,那么移除后的效果是:
对比以前的是否是好多了~~~接下来还存在一些没必要要的背景,你还能找到吗?
这个背景比较难发现,主要须要看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,还有最后一个,这个也是很是容易被忽略的。
记得咱们以前说,咱们的这个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 与最初的比较。
咱们在自定义View的时候,常常会因为疏忽形成不少没必要要的绘制,好比你们看下面这样的图:
多张卡片叠加,那么若是你是一张一张卡片从左到右的绘制,效果确定没问题,可是叠加的区域确定是过分绘制了。
而且material design对于界面设计的新的风格更容易形成上述的问题。那么有什么好的方法去改善呢?
答案是有的,android的Canvas对象给咱们提供了很便利的方法clipRect就能够很好的去解决这类问题。
下面经过一个实例来展现,那么首先看一个效果图:
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();
}
}
/** * 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
。
Android SDK中包含这个工具,不过你们确定也不陌生了~~~
那么就简单说一下它在哪,如何使用,以及真机没法使用该工具该怎么解决。
本博客使用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了,我就是这种方法调试的,哈~~
好了,上面介绍完成了如何使用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>
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能够帮助咱们发现相似的问题。
恩,对了,第一个例子里面的ListView的Item的写法就是Liearlayout嵌套的,你们有兴趣能够修改成RelativeLayout的写法的~~~
到此咱们就介绍完成了如何去对Android渲染进行优化,若是你的app有卡顿的状况,能够经过使用上述的工具首先去检测收集数据,而后按照上面提供的方法进行优化~~have a nice day ~~
群号:264950424,欢迎入群
下载地址
微信公众号:hongyangAndroid
(欢迎关注,第一时间推送博文信息)