获取界面布局耗时

获取界面布局耗时

常规方式

复写方法、手动埋点

AOP/Art Hook实现

通过 hook setContentView 来优雅的实现布局耗时

参考Aspectjx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Aspect
public class PerformanceApp {

@Around("execution(* android.app.Activity.setContentView(..))")
public void getSetContentViewTime(ProceedingJoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
String name = signature.toShortString();
long time = System.currentTimeMillis();
try {
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
Log.e(name + " cost " + (System.currentTimeMillis() - time));
}
}

参考ART

总结:

无侵入性、推荐使用

扩展:获取每个控件的加载耗时

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
LayoutInflater.from(this).setFactory2(new LayoutInflater.Factory2() {
@Nullable
@Override
public View onCreateView(@Nullable View parent, @NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
long start = System.currentTimeMillis();
View view = getDelegate().createView(parent, name, context, attrs);
Log.e("createViewTime", "cost: " + (System.currentTimeMillis() - start));
return view;
}

@Nullable
@Override
public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
return onCreateView(null, name, context, attrs);
}
});
// 注意:需要在super前配置
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}