-
-
Notifications
You must be signed in to change notification settings - Fork 427
/
ActivityFramesTracker.java
242 lines (207 loc) · 8.23 KB
/
ActivityFramesTracker.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package io.sentry.android.core;
import android.app.Activity;
import android.util.SparseIntArray;
import androidx.core.app.FrameMetricsAggregator;
import io.sentry.ILogger;
import io.sentry.MeasurementUnit;
import io.sentry.SentryLevel;
import io.sentry.android.core.internal.util.MainThreadChecker;
import io.sentry.protocol.MeasurementValue;
import io.sentry.protocol.SentryId;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
/**
* A class that tracks slow and frozen frames using the FrameMetricsAggregator class from
* androidx.core package. It also checks if the FrameMetricsAggregator class is available at
* runtime.
*/
public final class ActivityFramesTracker {
private @Nullable FrameMetricsAggregator frameMetricsAggregator = null;
private boolean androidXAvailable = true;
private final @NotNull Map<SentryId, Map<String, @NotNull MeasurementValue>>
activityMeasurements = new ConcurrentHashMap<>();
private final @NotNull Map<Activity, FrameCounts> frameCountAtStartSnapshots =
new WeakHashMap<>();
private final @Nullable ILogger logger;
private final @NotNull MainLooperHandler handler;
public ActivityFramesTracker(
final @NotNull LoadClass loadClass,
final @Nullable ILogger logger,
final @NotNull MainLooperHandler handler) {
androidXAvailable =
loadClass.isClassAvailable("androidx.core.app.FrameMetricsAggregator", logger);
if (androidXAvailable) {
frameMetricsAggregator = new FrameMetricsAggregator();
}
this.logger = logger;
this.handler = handler;
}
public ActivityFramesTracker(final @NotNull LoadClass loadClass, final @Nullable ILogger logger) {
this(loadClass, logger, new MainLooperHandler());
}
public ActivityFramesTracker(final @NotNull LoadClass loadClass) {
this(loadClass, null);
}
@TestOnly
ActivityFramesTracker(
final @Nullable FrameMetricsAggregator frameMetricsAggregator,
final @NotNull MainLooperHandler handler) {
this.frameMetricsAggregator = frameMetricsAggregator;
this.logger = null;
this.handler = handler;
}
private boolean isFrameMetricsAggregatorAvailable() {
return androidXAvailable && frameMetricsAggregator != null;
}
@SuppressWarnings("NullAway")
public synchronized void addActivity(final @NotNull Activity activity) {
if (!isFrameMetricsAggregatorAvailable()) {
return;
}
runSafelyOnUiThread(() -> frameMetricsAggregator.add(activity), "FrameMetricsAggregator.add");
snapshotFrameCountsAtStart(activity);
}
private void snapshotFrameCountsAtStart(final @NotNull Activity activity) {
FrameCounts frameCounts = calculateCurrentFrameCounts();
if (frameCounts != null) {
frameCountAtStartSnapshots.put(activity, frameCounts);
}
}
private @Nullable FrameCounts calculateCurrentFrameCounts() {
if (!isFrameMetricsAggregatorAvailable()) {
return null;
}
if (frameMetricsAggregator == null) {
return null;
}
final @Nullable SparseIntArray[] framesRates = frameMetricsAggregator.getMetrics();
int totalFrames = 0;
int slowFrames = 0;
int frozenFrames = 0;
if (framesRates != null && framesRates.length > 0) {
final SparseIntArray totalIndexArray = framesRates[FrameMetricsAggregator.TOTAL_INDEX];
if (totalIndexArray != null) {
for (int i = 0; i < totalIndexArray.size(); i++) {
int frameTime = totalIndexArray.keyAt(i);
int numFrames = totalIndexArray.valueAt(i);
totalFrames += numFrames;
// hard coded values, its also in the official android docs and frame metrics API
if (frameTime > 700) {
// frozen frames, threshold is 700ms
frozenFrames += numFrames;
} else if (frameTime > 16) {
// slow frames, above 16ms, 60 frames/second
slowFrames += numFrames;
}
}
}
}
return new FrameCounts(totalFrames, slowFrames, frozenFrames);
}
@SuppressWarnings("NullAway")
public synchronized void setMetrics(
final @NotNull Activity activity, final @NotNull SentryId transactionId) {
if (!isFrameMetricsAggregatorAvailable()) {
return;
}
// NOTE: removing an activity does not reset the frame counts, only reset() does
// throws IllegalArgumentException when attempting to remove
// OnFrameMetricsAvailableListener
// that was never added.
// there's no contains method.
// throws NullPointerException when attempting to remove
// OnFrameMetricsAvailableListener and
// there was no
// Observers, See
// https://android.googlesource.com/platform/frameworks/base/+/140ff5ea8e2d99edc3fbe63a43239e459334c76b
runSafelyOnUiThread(() -> frameMetricsAggregator.remove(activity), null);
final @Nullable FrameCounts frameCounts = diffFrameCountsAtEnd(activity);
if (frameCounts == null
|| (frameCounts.totalFrames == 0
&& frameCounts.slowFrames == 0
&& frameCounts.frozenFrames == 0)) {
return;
}
final MeasurementValue tfValues =
new MeasurementValue(frameCounts.totalFrames, MeasurementUnit.NONE);
final MeasurementValue sfValues =
new MeasurementValue(frameCounts.slowFrames, MeasurementUnit.NONE);
final MeasurementValue ffValues =
new MeasurementValue(frameCounts.frozenFrames, MeasurementUnit.NONE);
final Map<String, @NotNull MeasurementValue> measurements = new HashMap<>();
measurements.put("frames_total", tfValues);
measurements.put("frames_slow", sfValues);
measurements.put("frames_frozen", ffValues);
activityMeasurements.put(transactionId, measurements);
}
private @Nullable FrameCounts diffFrameCountsAtEnd(final @NotNull Activity activity) {
@Nullable final FrameCounts frameCountsAtStart = frameCountAtStartSnapshots.remove(activity);
if (frameCountsAtStart == null) {
return null;
}
@Nullable final FrameCounts frameCountsAtEnd = calculateCurrentFrameCounts();
if (frameCountsAtEnd == null) {
return null;
}
final int diffTotalFrames = frameCountsAtEnd.totalFrames - frameCountsAtStart.totalFrames;
final int diffSlowFrames = frameCountsAtEnd.slowFrames - frameCountsAtStart.slowFrames;
final int diffFrozenFrames = frameCountsAtEnd.frozenFrames - frameCountsAtStart.frozenFrames;
return new FrameCounts(diffTotalFrames, diffSlowFrames, diffFrozenFrames);
}
@Nullable
public synchronized Map<String, @NotNull MeasurementValue> takeMetrics(
final @NotNull SentryId transactionId) {
if (!isFrameMetricsAggregatorAvailable()) {
return null;
}
final Map<String, @NotNull MeasurementValue> stringMeasurementValueMap =
activityMeasurements.get(transactionId);
activityMeasurements.remove(transactionId);
return stringMeasurementValueMap;
}
@SuppressWarnings("NullAway")
public synchronized void stop() {
if (isFrameMetricsAggregatorAvailable()) {
runSafelyOnUiThread(() -> frameMetricsAggregator.stop(), "FrameMetricsAggregator.stop");
frameMetricsAggregator.reset();
}
activityMeasurements.clear();
}
private void runSafelyOnUiThread(final Runnable runnable, final String tag) {
try {
if (MainThreadChecker.isMainThread()) {
runnable.run();
} else {
handler.post(
() -> {
try {
runnable.run();
} catch (Throwable ignored) {
if (logger != null && tag != null) {
logger.log(SentryLevel.WARNING, "Failed to execute " + tag);
}
}
});
}
} catch (Throwable ignored) {
if (logger != null && tag != null) {
logger.log(SentryLevel.WARNING, "Failed to execute " + tag);
}
}
}
private static final class FrameCounts {
private final int totalFrames;
private final int slowFrames;
private final int frozenFrames;
private FrameCounts(final int totalFrames, final int slowFrames, final int frozenFrames) {
this.totalFrames = totalFrames;
this.slowFrames = slowFrames;
this.frozenFrames = frozenFrames;
}
}
}