【发布时间】:2017-10-28 22:51:27
【问题描述】:
在我的 Android Vitals 中,有 30% 的用户体验到渲染缓慢。我的应用程序有一个非常复杂的 UI,所以我做了一个非常基本的项目来尝试解决这个问题。但事实证明,即使是最简单的布局,它也很慢。
布局是 Android Studio 作为模板提供的居中文本:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="slowrenderingtest.pichaipls.com.slowrenderingtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/timerView"
android:text="00:00"
android:textSize="40dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>
使用布局的活动每秒都会更改文本(因为它是一个计时器):
Timer updateTicks = new Timer();
updateTicks.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Random r = new Random();
timerView.setText(String.format("%02d", r.nextInt(60))+":"+
String.format("%02d", r.nextInt(60)));
}
});
}
}, 100, 1000);
当我打开 GPU 分析时,这非常接近在一些速度较慢的设备(显然是 30% 的用户)上绘制每帧的 16 毫秒限制。只有一个TextView。但这里有一个问题:当我第一次运行活动时,渲染时间很短,但几秒钟后它们就会迅速增加。如果我一直触摸屏幕(屏幕上没有控件),渲染时间仍然很低。我猜这是由于 CPU/GPU 进入低功耗状态(因此渲染需要更长的时间)。
我的问题是 Android Vitals。我一直看到有关缓慢渲染时间的警告(我认为任何超过 5% 的会话经历缓慢渲染都会收到警告),但我不知道如何加快速度。而且我担心这可能会影响我的应用排名,但即使是这个非常简单的例子,也有太多的 Android 用户使用慢速设备。
对此有什么办法吗?
【问题讨论】:
-
你可以尝试运行 CPU 分析并找出哪个方法花费更多时间,我敢打赌它是
r.nextInt()不应该在 UI 线程上过度使用 -
不,它与 `r.nextInt()' 无关。如果我只显示一个递增的数字,问题也是一样的。事实上,对 CPU 征税似乎可以加快绘图速度。如果我不只是生成一个随机数,而是计算该数的阶乘,那么 GPU 更新缓慢的问题就会得到解决,尽管是以一种可怕且低效的方式。
标签: android performance