1. 为什么要做性能优化
Android设备是一种移动设备,内存和CPU 都有限,过多使用内存会OOM,过多使用CPU(大量耗时操作)会ANR。
2. 如何做性能优化,有哪几种
- 布局优化
- 绘制优化
- 内存泄漏优化
- 响应速度优化
- LIstView优化
- BitMap优化
- 线程优化
3. 各类优化方法介绍
布局优化
1. 使用简洁高效的ViewGroup(例如LinearLayout和FrameLayout 比RelativeLayout 更轻量级),删除无用控件,减少布局层级(例如需要多层LinearLayout,但是单层RelativeLayout能实现,那就用RelativeLayout)。
2. 使用标签<include> <merge>
如果include 的布局中的ViewGroup和外层布局重复。那么就把这个ViewGroup 替换成<merge>。
3. 按需加载 ViewStub
继承View,轻量级,宽高为0,本身不参与任何布局和绘制过程。以下是使用方式和两种显示方式,
显示后,ViewStub就会被内部的布局替换掉。
<ViewStub android:id="@+id/vs" android:inflatedId="@+id/ll"//包含布局的根元素id android:layout="@layout/list_item"//包含的布局 android:layout_width="match_parent" android:layout_height="wrap_content" /> |
findViewById(R.id.vs).setVisibility(View.VISIBLE); |
View v = findViewById(R.id.vs).inflate(); |
绘制优化
1. View的onDraw()方法避免执行大量操作,应为要频繁调用。
在OnDraw() 中别创建局部对象,别做耗时操作。
内存泄漏优化
1. 静态变量导致内存泄漏
2. 单例
也是activity对象被单例对象持有,注册之后未取消
3. 属性动化
无线循环动画没有在 onDestroy() 中取消 也会导致activity无法释放
响应速度优化
1. 避免在主线程做耗时操作
ListView和BitMap优化
1. listView 采用ViewHolder 避免在getView() 中耗时操作,根据滑动状态来控制任务执行的频率,开启硬件加速。
2. BitMap
package com.scy.android.util;
import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point;
/** * 沈程阳 * created by scy on 2018/12/26 20:24 * 邮箱:1797484636@qq.com */ public class PictureUtils { public static Bitmap getScaledBitmap(String path, Activity activity) { Point size = new Point(); activity.getWindowManager().getDefaultDisplay() .getSize(size); return getScaledBitmap(path, size.x, size.y); }
public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight) { // Read in the dimensions of the image on disk BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; // Figure out how much to scale down by int inSampleSize = 1; if (srcHeight > destHeight || srcWidth > destWidth) { float heightScale = srcHeight / destHeight; float widthScale = srcWidth / destWidth; inSampleSize = Math.round(heightScale > widthScale ? heightScale : widthScale); } options = new BitmapFactory.Options(); options.inSampleSize = inSampleSize; // Read in and create final bitmap return BitmapFactory.decodeFile(path, options); } } |
线程优化
1. 使用线程池,避免存在大量线程,可以实现重用,避免线程创建销毁所带来的性能开销,控制并发数量。
一些性能优化的建议
不要过多创建对象,不要过多使用枚举
常量使用static final
使用Android特有的数据结构:SparseArray Pair
适当使用软引用和弱引用
采用内存缓存和磁盘缓存
尽量采用静态内部类,这样可以避免潜在的内部类而导致内存泄漏。