在app开发过程中,经常会出现卡顿现象,出现卡顿的原因有很多,例如内存、cpu、IO都可能相关。解决卡顿的问题关键在于找出卡顿的代码位置,本文以分析trace文件为例子,来找出卡顿原因
public class AnrView extends View {
private Context mContext;
private Paint mPaint;
public AnrView(Context context) {
this(context,null);
}
private void init(Context context){
this.mContext = context;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setTextSize(40);
}
public AnrView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public AnrView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < 500000; i++) {
canvas.drawText("jerry", ScreenUtil.getScreenWidth(mContext)/2,ScreenUtil.getActionBarHeight(mContext) /2,mPaint);
}
}
}
在自定义View的onDraw方法中,多次循环执行canvas.drawText,进入界面时就会报"程序无响应", 此时会在/data/anr目录下生成trace.txt文件, 用adb命令导出trace文件
adb pull /data/anr/traces.txt /user/work
网友评论