0
# Configuration and Performance
1
2
Global configuration, render mode settings, performance optimization options, and monitoring tools for Lottie Android applications.
3
4
## Capabilities
5
6
### Global Configuration
7
8
System for configuring global Lottie settings including network fetching, caching, and debugging options.
9
10
```java { .api }
11
/**
12
* Global configuration class
13
*/
14
public class Lottie {
15
/**
16
* Initialize Lottie with global configuration
17
* @param config Configuration instance
18
*/
19
public static void initialize(LottieConfig config);
20
}
21
22
/**
23
* Configuration builder for global Lottie settings
24
*/
25
public class LottieConfig {
26
// Internal configuration
27
final LottieNetworkFetcher networkFetcher;
28
final LottieNetworkCacheProvider cacheProvider;
29
final boolean enableSystraceMarkers;
30
31
// Private constructor - use Builder
32
private LottieConfig(LottieNetworkFetcher networkFetcher,
33
LottieNetworkCacheProvider cacheProvider,
34
boolean enableSystraceMarkers);
35
36
/**
37
* Builder for LottieConfig
38
*/
39
public static final class Builder {
40
// Network configuration
41
public Builder setNetworkFetcher(LottieNetworkFetcher fetcher);
42
public Builder setNetworkCacheDir(File file);
43
public Builder setNetworkCacheProvider(LottieNetworkCacheProvider fileCacheProvider);
44
45
// Performance configuration
46
public Builder setEnableSystraceMarkers(boolean enable);
47
48
// Build configuration
49
public LottieConfig build();
50
}
51
}
52
```
53
54
**Usage Examples:**
55
56
```java
57
// Basic global configuration
58
LottieConfig config = new LottieConfig.Builder()
59
.setNetworkCacheDir(new File(getCacheDir(), "lottie_animations"))
60
.setEnableSystraceMarkers(BuildConfig.DEBUG)
61
.build();
62
63
Lottie.initialize(config);
64
65
// Custom network fetcher configuration
66
LottieConfig config = new LottieConfig.Builder()
67
.setNetworkFetcher(new CustomNetworkFetcher())
68
.setNetworkCacheDir(new File(getExternalCacheDir(), "lottie_cache"))
69
.build();
70
71
Lottie.initialize(config);
72
73
// Production configuration
74
LottieConfig prodConfig = new LottieConfig.Builder()
75
.setNetworkCacheProvider(() -> new File(getCacheDir(), "lottie_network_cache"))
76
.setEnableSystraceMarkers(false) // Disable in production
77
.build();
78
79
Lottie.initialize(prodConfig);
80
81
// Development configuration with debugging
82
LottieConfig devConfig = new LottieConfig.Builder()
83
.setNetworkFetcher(new LoggingNetworkFetcher())
84
.setNetworkCacheDir(new File(getCacheDir(), "dev_lottie_cache"))
85
.setEnableSystraceMarkers(true) // Enable for performance analysis
86
.build();
87
88
Lottie.initialize(devConfig);
89
```
90
91
### Render Mode Configuration
92
93
System for configuring rendering performance by choosing between hardware acceleration, software rendering, or automatic selection.
94
95
```java { .api }
96
/**
97
* Rendering mode configuration
98
*/
99
public enum RenderMode {
100
AUTOMATIC, // Automatic selection based on animation characteristics
101
HARDWARE, // Force hardware acceleration
102
SOFTWARE; // Force software rendering
103
104
/**
105
* Determine if software rendering should be used
106
* @param sdkInt Android SDK version
107
* @param hasDashPattern Whether animation has dash patterns
108
* @param numMasksAndMattes Number of masks and mattes
109
* @return true if software rendering should be used
110
*/
111
public boolean useSoftwareRendering(int sdkInt, boolean hasDashPattern, int numMasksAndMattes);
112
}
113
```
114
115
**Usage Examples:**
116
117
```java
118
// Set render mode on view
119
animationView.setRenderMode(RenderMode.HARDWARE); // Force hardware acceleration
120
drawable.setRenderMode(RenderMode.SOFTWARE); // Force software rendering
121
122
// Automatic mode (default) - chooses based on animation characteristics
123
animationView.setRenderMode(RenderMode.AUTOMATIC);
124
125
// Check current render mode
126
RenderMode currentMode = animationView.getRenderMode();
127
Log.d("Lottie", "Current render mode: " + currentMode);
128
129
// Dynamic render mode selection based on device capabilities
130
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
131
// Newer devices handle hardware acceleration better
132
animationView.setRenderMode(RenderMode.HARDWARE);
133
} else {
134
// Older devices may perform better with software rendering
135
animationView.setRenderMode(RenderMode.SOFTWARE);
136
}
137
138
// Conditional render mode based on animation complexity
139
LottieCompositionFactory.fromAsset(context, "complex_animation.json")
140
.addListener(composition -> {
141
animationView.setComposition(composition);
142
143
// Choose render mode based on complexity
144
if (composition.getMaskAndMatteCount() > 5 || composition.hasDashPattern()) {
145
animationView.setRenderMode(RenderMode.SOFTWARE);
146
} else {
147
animationView.setRenderMode(RenderMode.HARDWARE);
148
}
149
150
animationView.playAnimation();
151
});
152
153
// Custom render mode logic
154
public class SmartRenderModeHelper {
155
public static RenderMode selectOptimalRenderMode(LottieComposition composition) {
156
int sdkInt = Build.VERSION.SDK_INT;
157
boolean hasDashPattern = composition.hasDashPattern();
158
int masksAndMattes = composition.getMaskAndMatteCount();
159
160
// Use RenderMode's built-in logic
161
if (RenderMode.AUTOMATIC.useSoftwareRendering(sdkInt, hasDashPattern, masksAndMattes)) {
162
return RenderMode.SOFTWARE;
163
} else {
164
return RenderMode.HARDWARE;
165
}
166
}
167
}
168
```
169
170
### Performance Monitoring
171
172
Tools for monitoring and analyzing animation performance, including render time tracking and performance metrics.
173
174
```java { .api }
175
/**
176
* Performance tracking utility
177
*/
178
public class PerformanceTracker {
179
// Enable/disable tracking
180
public void setEnabled(boolean enabled);
181
public boolean isEnabled();
182
183
// Record performance data
184
public void recordRenderTime(String layerName, float renderTimeMs);
185
186
// Retrieve performance data
187
public Map<String, Float> getSortedRenderTimes();
188
public void clearRenderTimes();
189
190
// Listener for performance events
191
public void addFrameListener(FrameListener frameListener);
192
public void removeFrameListener(FrameListener frameListener);
193
194
// Internal methods
195
@RestrictTo(RestrictTo.Scope.LIBRARY)
196
public void startTimer(String layerName);
197
@RestrictTo(RestrictTo.Scope.LIBRARY)
198
public float endTimer(String layerName);
199
}
200
201
/**
202
* Frame performance listener
203
*/
204
public interface FrameListener {
205
void onFrameRendered(float renderTimeMs);
206
}
207
```
208
209
**Usage Examples:**
210
211
```java
212
// Enable performance tracking
213
PerformanceTracker tracker = animationView.getPerformanceTracker();
214
tracker.setEnabled(true);
215
216
// Add frame listener for real-time monitoring
217
tracker.addFrameListener(renderTimeMs -> {
218
if (renderTimeMs > 16.67f) { // Slower than 60fps
219
Log.w("Lottie", "Slow frame detected: " + renderTimeMs + "ms");
220
}
221
});
222
223
// Analyze performance after animation
224
animationView.addAnimatorListener(new AnimatorListenerAdapter() {
225
@Override
226
public void onAnimationEnd(Animator animator) {
227
Map<String, Float> renderTimes = tracker.getSortedRenderTimes();
228
229
float totalTime = 0f;
230
for (Map.Entry<String, Float> entry : renderTimes.entrySet()) {
231
String layerName = entry.getKey();
232
Float renderTime = entry.getValue();
233
totalTime += renderTime;
234
235
Log.d("Lottie", "Layer '" + layerName + "': " + renderTime + "ms");
236
}
237
238
Log.d("Lottie", "Total render time: " + totalTime + "ms");
239
240
// Clear for next analysis
241
tracker.clearRenderTimes();
242
}
243
});
244
245
// Performance monitoring helper
246
public class LottiePerformanceMonitor {
247
private static final float TARGET_FRAME_TIME = 16.67f; // 60fps
248
private final PerformanceTracker tracker;
249
private final List<Float> frameTimes = new ArrayList<>();
250
251
public LottiePerformanceMonitor(LottieAnimationView animationView) {
252
this.tracker = animationView.getPerformanceTracker();
253
this.tracker.setEnabled(true);
254
255
this.tracker.addFrameListener(frameTime -> {
256
frameTimes.add(frameTime);
257
258
// Alert on consistently slow frames
259
if (frameTimes.size() >= 10) {
260
float averageTime = calculateAverage(frameTimes.subList(frameTimes.size() - 10, frameTimes.size()));
261
if (averageTime > TARGET_FRAME_TIME * 1.5f) {
262
Log.w("Lottie", "Performance warning: Average frame time " + averageTime + "ms");
263
}
264
}
265
});
266
}
267
268
public PerformanceReport generateReport() {
269
if (frameTimes.isEmpty()) {
270
return new PerformanceReport();
271
}
272
273
float minTime = Collections.min(frameTimes);
274
float maxTime = Collections.max(frameTimes);
275
float avgTime = calculateAverage(frameTimes);
276
int droppedFrames = (int) frameTimes.stream()
277
.mapToDouble(Float::doubleValue)
278
.filter(time -> time > TARGET_FRAME_TIME)
279
.count();
280
281
return new PerformanceReport(minTime, maxTime, avgTime, droppedFrames, frameTimes.size());
282
}
283
284
private float calculateAverage(List<Float> times) {
285
return (float) times.stream().mapToDouble(Float::doubleValue).average().orElse(0.0);
286
}
287
288
public static class PerformanceReport {
289
public final float minFrameTime;
290
public final float maxFrameTime;
291
public final float avgFrameTime;
292
public final int droppedFrames;
293
public final int totalFrames;
294
295
public PerformanceReport() {
296
this(0, 0, 0, 0, 0);
297
}
298
299
public PerformanceReport(float minFrameTime, float maxFrameTime, float avgFrameTime,
300
int droppedFrames, int totalFrames) {
301
this.minFrameTime = minFrameTime;
302
this.maxFrameTime = maxFrameTime;
303
this.avgFrameTime = avgFrameTime;
304
this.droppedFrames = droppedFrames;
305
this.totalFrames = totalFrames;
306
}
307
308
public float getFrameRate() {
309
return avgFrameTime > 0 ? 1000f / avgFrameTime : 0f;
310
}
311
312
public float getDroppedFramePercentage() {
313
return totalFrames > 0 ? (droppedFrames * 100f) / totalFrames : 0f;
314
}
315
}
316
}
317
```
318
319
### Optimization Settings
320
321
Various settings for optimizing animation performance and behavior.
322
323
```java { .api }
324
// Animation view optimization methods
325
public class LottieAnimationView extends AppCompatImageView {
326
// Merge paths optimization (API 19+)
327
public void enableMergePathsForKitKatAndAbove(boolean enable);
328
329
// Opacity optimization
330
public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled);
331
332
// Clipping optimization
333
public void setClipToCompositionBounds(boolean clipToCompositionBounds);
334
335
// System animation handling
336
public void setIgnoreDisabledSystemAnimations(boolean ignore);
337
}
338
339
// Drawable optimization methods
340
public class LottieDrawable extends Drawable {
341
// Merge paths optimization
342
public void enableMergePathsForKitKatAndAbove(boolean enable);
343
344
// Opacity optimization
345
public void setApplyingOpacityToLayersEnabled(boolean isApplyingOpacityToLayersEnabled);
346
347
// Clipping optimization
348
public void setClipToCompositionBounds(boolean clipToCompositionBounds);
349
350
// System animation handling
351
public void setSystemAnimationsAreEnabled(boolean areSystemAnimationsEnabled);
352
public void setIgnoreDisabledSystemAnimations(boolean ignore);
353
354
// Safe mode for problematic animations
355
public void setSafeMode(boolean safeMode);
356
357
// Performance tracking
358
public void setPerformanceTrackingEnabled(boolean enabled);
359
}
360
```
361
362
**Usage Examples:**
363
364
```java
365
// Enable optimizations
366
animationView.enableMergePathsForKitKatAndAbove(true);
367
animationView.setApplyingOpacityToLayersEnabled(true);
368
animationView.setClipToCompositionBounds(true);
369
370
// Optimize for older devices
371
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
372
animationView.setRenderMode(RenderMode.SOFTWARE);
373
animationView.enableMergePathsForKitKatAndAbove(false);
374
}
375
376
// Handle system animation settings
377
animationView.setIgnoreDisabledSystemAnimations(false); // Respect user's animation settings
378
379
// Safe mode for problematic animations
380
drawable.setSafeMode(true); // Disable some optimizations for stability
381
382
// Performance-optimized setup
383
public void setupOptimizedLottieView(LottieAnimationView animationView, boolean isLowEndDevice) {
384
if (isLowEndDevice) {
385
// Conservative settings for low-end devices
386
animationView.setRenderMode(RenderMode.SOFTWARE);
387
animationView.enableMergePathsForKitKatAndAbove(false);
388
animationView.setApplyingOpacityToLayersEnabled(false);
389
} else {
390
// Aggressive optimizations for high-end devices
391
animationView.setRenderMode(RenderMode.HARDWARE);
392
animationView.enableMergePathsForKitKatAndAbove(true);
393
animationView.setApplyingOpacityToLayersEnabled(true);
394
animationView.setClipToCompositionBounds(true);
395
}
396
397
// Common optimizations
398
animationView.setIgnoreDisabledSystemAnimations(false);
399
}
400
401
// Memory optimization helper
402
public class LottieMemoryManager {
403
private static final int MAX_CACHE_SIZE = 20;
404
405
public static void optimizeForMemory() {
406
// Limit composition cache size
407
LottieCompositionFactory.setMaxCacheSize(MAX_CACHE_SIZE);
408
}
409
410
public static void clearAllCaches(Context context) {
411
// Clear composition cache
412
LottieCompositionFactory.clearCache(context);
413
414
// Clear network cache
415
File cacheDir = new File(context.getCacheDir(), "lottie_network_cache");
416
if (cacheDir.exists()) {
417
deleteRecursively(cacheDir);
418
}
419
}
420
421
private static void deleteRecursively(File file) {
422
if (file.isDirectory()) {
423
File[] children = file.listFiles();
424
if (children != null) {
425
for (File child : children) {
426
deleteRecursively(child);
427
}
428
}
429
}
430
file.delete();
431
}
432
}
433
```
434
435
### Network Configuration
436
437
Configuration for network-based animation loading with custom fetchers and cache providers.
438
439
```java { .api }
440
/**
441
* Interface for custom network fetching
442
*/
443
public interface LottieNetworkFetcher {
444
LottieResult<LottieComposition> fetchSync(String url, String cacheKey);
445
}
446
447
/**
448
* Interface for custom cache providers
449
*/
450
public interface LottieNetworkCacheProvider {
451
File getCacheDir();
452
}
453
454
/**
455
* Network fetch result interface
456
*/
457
public interface LottieFetchResult {
458
boolean isSuccessful();
459
InputStream bodyByteStream();
460
String contentType();
461
}
462
463
/**
464
* Default network fetcher implementation
465
*/
466
public class DefaultLottieNetworkFetcher implements LottieNetworkFetcher {
467
public DefaultLottieNetworkFetcher();
468
public LottieResult<LottieComposition> fetchSync(String url, String cacheKey);
469
}
470
471
/**
472
* Default fetch result implementation
473
*/
474
public class DefaultLottieFetchResult implements LottieFetchResult {
475
public DefaultLottieFetchResult(HttpURLConnection connection);
476
public boolean isSuccessful();
477
public InputStream bodyByteStream();
478
public String contentType();
479
}
480
```
481
482
**Usage Examples:**
483
484
```java
485
// Custom network fetcher with authentication
486
public class AuthenticatedNetworkFetcher implements LottieNetworkFetcher {
487
private final String authToken;
488
489
public AuthenticatedNetworkFetcher(String authToken) {
490
this.authToken = authToken;
491
}
492
493
@Override
494
public LottieResult<LottieComposition> fetchSync(String url, String cacheKey) {
495
try {
496
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
497
connection.setRequestProperty("Authorization", "Bearer " + authToken);
498
connection.setRequestMethod("GET");
499
connection.connect();
500
501
DefaultLottieFetchResult fetchResult = new DefaultLottieFetchResult(connection);
502
if (fetchResult.isSuccessful()) {
503
InputStream inputStream = fetchResult.bodyByteStream();
504
return LottieCompositionFactory.fromJsonInputStreamSync(inputStream, cacheKey);
505
} else {
506
return new LottieResult<>(new IOException("HTTP " + connection.getResponseCode()));
507
}
508
} catch (IOException e) {
509
return new LottieResult<>(e);
510
}
511
}
512
}
513
514
// Custom cache provider
515
public class CustomCacheProvider implements LottieNetworkCacheProvider {
516
private final File customCacheDir;
517
518
public CustomCacheProvider(Context context) {
519
this.customCacheDir = new File(context.getExternalCacheDir(), "custom_lottie_cache");
520
if (!customCacheDir.exists()) {
521
customCacheDir.mkdirs();
522
}
523
}
524
525
@Override
526
public File getCacheDir() {
527
return customCacheDir;
528
}
529
}
530
531
// Configure custom network handling
532
LottieConfig config = new LottieConfig.Builder()
533
.setNetworkFetcher(new AuthenticatedNetworkFetcher(userToken))
534
.setNetworkCacheProvider(new CustomCacheProvider(context))
535
.build();
536
537
Lottie.initialize(config);
538
```
539
540
## Logging and Debugging
541
542
```java { .api }
543
public interface LottieLogger {
544
void debug(String message);
545
void debug(String message, Throwable exception);
546
void warning(String message);
547
void warning(String message, Throwable exception);
548
void error(String message, Throwable exception);
549
}
550
551
public class LogcatLogger implements LottieLogger {
552
public static final LogcatLogger INSTANCE = new LogcatLogger();
553
554
@Override
555
public void debug(String message);
556
@Override
557
public void debug(String message, Throwable exception);
558
@Override
559
public void warning(String message);
560
@Override
561
public void warning(String message, Throwable exception);
562
@Override
563
public void error(String message, Throwable exception);
564
}
565
```