In the realm of Android development, the main thread is our stage, but too often, it becomes a battleground where performance issues arise, leading to ANRS, frozen frames, and sluggish Uls. As we strive for excellence in user experience, understanding and optimizing the main thread becomes essential to prevent these common perforrmance bottlenecks. We have strategies and best practices for keeping the main thread uncluttered. We'll examine the root causes of performance issues and techniques for monitoring and improving main thread health as wel as app performance. In this talk, participants will walk away with practical knowledge on enhancing app performance by mastering the main thread. We'll share proven approaches to eliminate real-life ANRS and frozen frames to build apps that deliver butter smooth experience.
Report
Share
Report
Share
1 of 60
Download to read offline
More Related Content
Similar to Unblocking The Main Thread - Solving ANRs and Frozen Frames
Sashko Stubailo - The GraphQL and Apollo Stack: connecting everything togetherReact Conf Brasil
Apresentado na React Conf Brasil, em São Paulo, 7 de Outubro de 2017 #reactconfbr
I’ve been exploring the space of declarative developer tools and frameworks for over five years. Most recently, I was the founding member of the Apollo project at Meteor Development Group. My greatest passion is to make software development simpler, and enable more people to create software to bring good to the world.
https://medium.com/@stubailo
@stubailo
- Patrocínio: Pipefy, Globo.com, Meteor, Apollo, Taller, Fullcircle, Quanto, Udacity, Cubos, Segware, Entria
- Apoio: Concrete, Rung, LuizaLabs, Movile, Rivendel, GreenMile, STQ, Hi Platform
- Promoção: InfoQ, DevNaEstrada, CodamosClub, JS Ladies, NodeBR, Training Center, BrazilJS, Tableless, GeekHunter
- Afterparty: An English Thing
GraphQL is a wonderful abstraction for describing and querying data. Apollo is an ambitious project to help you build apps with GraphQL. In this talk, we'll go over how all the parts—Client, Server, Dev Tools, Codegen, and more—create an end-to-end experience for building apps on top of any data.
## Detailed description
In today's development ecosystem, there are tons of options for almost every part of your application development process: UI rendering, styling, server side rendering, build systems, type checking, databases, frontend data management, and more. However, there's one part of the stack that hasn't gotten as much love in the last decade, because it usually falls in the cracks between frontend and backend developers: Data fetching.
The most common way to load data in apps today is to use a REST API on the server and manage the data manually on the client. Whether you're using Redux, MobX, or something else, you're usually doing everything yourself—deciding when to load data, how to keep it fresh, updating the store after sending updates to the server, and more. But if you're trying to develop the best user experience for your app, all of that gets in the way; you shouldn't have to become a systems engineer to create a great frontend. The Apollo project is based on the belief that data loading doesn't have to be complicated; instead, you should be able to easily get the data you want, when you want it, and it should be managed for you just like React manages updating your UI.
Because data loading touches both the frontend and backend of your app, GraphQL and Apollo have to include many parts to fulfill that promise of being able to seamlessly connect your data together. First, we need client libraries not only for React and JavaScript, but also for native iOS and Android. Then, we must bring server-side support for GraphQL queries, mutations, and most recently subscriptions to every server technology and make those servers easier to write. And finally, we want not only all of the tools that people are used to with REST APIs, but many more thanks to all of the capabilities enabled by GraphQL.
In this talk, we'll go over all of the parts of a GraphQL-oriented app architecture, and how different GraphQL and Apollo technologies come together to solve all of the parts of data loading and management for React developers.
Angular (v2 and up) - Morning to understand - LinagoraLINAGORA
Slides of the talk about Angular, at the "Matinée Pour Comprendre" organized by Linagora the 22/03/17.
Discover what's new in Angular, why is it more than just a framework (platform) and how to manage your data with RxJs and Redux.
This document provides an introduction to Apache Flink and its streaming capabilities. It discusses stream processing as an abstraction and how Flink uses streams as a core abstraction. It compares Flink streaming to Spark streaming and outlines some of Flink's streaming features like windows, triggers, and how it handles event time.
Django and React serve different roles in web development. Django, a backend framework in Python, excels in building robust, scalable server-side applications with its ORM and templating engine. React, a frontend library in JavaScript, focuses on building interactive user interfaces, offering component-based architecture and efficient state management for dynamic web applications.
Voxxed days Vilnius 2015 - Android Reverse Engineering LabRon Munitz
This document outlines Ron Munitz's presentation on Android reverse engineering. Some key points:
- Ron will demonstrate the Android build process and then the "unbuild" or reverse engineering process. This will include using tools like apktool, dex2jar, and jd-gui.
- The presentation will be 50 minutes and cover decompiling an app's resources, converting dex files to jars and class files, and using a Java decompiler to view source code.
- If time allows, Ron may also demonstrate network analysis using packet interceptors.
- The slides for the presentation are available online but the focus should be on the terminal demonstration and explanation.
- Reverse engineering Android apps can
After I attended Google IO 2014, I wanted to present what is new for Android Lollipop from a Developer perspective.
This presentation covers almost everything except, maybe, native Android Wear development, Android Auto and Android TV
Discussion on angular offering, approaches to integrate web worker in angular (5 and 6) application, their pros and cons. A sample example implementation using custom web worker approach and integrating the same with CLI(1 and 6) and the application.
Kubernetes Forum Seoul 2019: Re-architecting Data Platform with KubernetesSeungYong Oh
Session Video: https://youtu.be/7MPH1mknIxE
In this talk, we share Devsisters' journey of migrating its internal data platform including Spark to Kubernetes, with its benefits and issues.
데브시스터즈에서 데이터플랫폼 컴포넌트를 쿠버네티스로 옮기면서 얻은 장점들과 이슈들에 대해 공유합니다.
Conference session page:
- English: https://sched.co/WIRK
- Korean: https://sched.co/WYRc
The document summarizes the process of migrating an existing AngularJS application to React. It describes refactoring the AngularJS code, extracting reusable modules, rewriting components starting from the top-level component, using tests to maintain functionality, and deploying the initial React version while continuing iterative improvements. Key steps included upgrading AngularJS, removing two-way bindings, splitting into sub-apps, creating a demo page, and addressing challenges of mixing AngularJS and React code during the transition.
Baparekraf Digital Talent Day: Monitoring dan Coaching Penerima Fasilitasi BD...DicodingEvent
Jetpack is a suite of libraries and architecture components that help developers follow best practices to reduce boilerplate code and write code that is compatible across Android versions and devices. It includes libraries for UI components, navigation, data binding, room, lifecycle management, and more. Using Jetpack can help developers focus on the code that matters by eliminating redundant code and ensuring compatibility.
Ultimate Guide to Microservice Architecture on Kuberneteskloia
This document provides an overview of microservice architecture on Kubernetes. It discusses:
1. Benefits of microservice architecture like independent deployability and scalability compared to monolithic applications.
2. Best practices for microservices including RESTful design, distributed configuration, client code generation, and API gateways.
3. Tools for microservices on Kubernetes including Prometheus for monitoring, Elasticsearch (ELK) stack for logging, service meshes, and event sourcing with CQRS.
Nx is a tool that manages monorepos and helps build and architect applications. It provides benefits like code sharing, faster building/testing, and integrations with tools like Jest and Cypress. Nx uses computation caching and graph-based execution to improve speeds. It allows generating components/modules and enforcing development practices. Nx works with Angular and React and manages dependencies through a single package.json. Projects are organized into libraries and applications.
Azure Native Qumulo scales elastically for common High Performance Compute (HPC) workloads based on application requirements for: Financial Services, Automotive, Genomics / Life Sciences, Media and Entertainment, Energy, Oil and Gas, and more. Performance can be increased (and elastically decreased) much higher than the examples shown here. These slides offer a glimpse into ANQ's HPC capabilities, although at a smaller scale. We invite YOU to do your own testing (with a free ANQ trial) and work with us to test your HPC workloads in Azure.
Truemotion Adventures in ContainerizationRyan Hunter
This document summarizes Ryan Hunter's experience switching his company's infrastructure from using Ansible to provision Debian-based servers to using Docker containers and ECS on AWS. Some key reasons for the switch included dependency issues with Ansible, inflexible server sizing, and a desire for more portable and standardized application builds. Docker provided containers as a flexible runtime artifact while ECS and CloudFormation helped with scheduling, provisioning, and configuring containers at scale on AWS. Monitoring tools like Consul, Sumo Logic, and custom monitoring libraries were also implemented.
This document provides an overview of Netty, an asynchronous event-driven network application framework for Java. It discusses key Netty concepts like the event loop, channels, pipelines and handlers. It also provides examples of building an echo server and client with Netty. Additionally, it mentions several large companies that use Netty in production and open-source projects built with Netty. Finally, it discusses some alternative solutions to Netty like ServiceTalk, Armeria and Reactor Netty that provide additional features on top of the Netty core.
The document summarizes the multi-purpose NoSQL database ArangoDB. It describes ArangoDB as a second generation database that is open source, free, and supports multiple data models including documents, graphs, and key-value. It highlights main features such as being extensible through JavaScript, having high performance, and being easy to use through its web interface and query language AQL.
The presentation on Protractor Cucumber BDD Approach was done during #ATAGTR2017, one of the largest global testing conference. All copyright belongs to the author.
Author and presenter : Rajat Acharya
Similar to Unblocking The Main Thread - Solving ANRs and Frozen Frames (20)
20CDE09- INFORMATION DESIGN
UNIT I INCEPTION OF INFORMATION DESIGN
Introduction and Definition
History of Information Design
Need of Information Design
Types of Information Design
Identifying audience
Defining the audience and their needs
Inclusivity and Visual impairment
Case study.
Encontro anual da comunidade Splunk, onde discutimos todas as novidades apresentadas na conferência anual da Spunk, a .conf24 realizada em junho deste ano em Las Vegas.
Neste vídeo, trago os pontos chave do encontro, como:
- AI Assistant para uso junto com a SPL
- SPL2 para uso em Data Pipelines
- Ingest Processor
- Enterprise Security 8.0 (Maior atualização deste seu release)
- Federated Analytics
- Integração com Cisco XDR e Cisto Talos
- E muito mais.
Deixo ainda, alguns links com relatórios e conteúdo interessantes que podem ajudar no esclarecimento dos produtos e funções.
https://www.splunk.com/en_us/campaigns/the-hidden-costs-of-downtime.html
https://www.splunk.com/en_us/pdfs/gated/ebooks/building-a-leading-observability-practice.pdf
https://www.splunk.com/en_us/pdfs/gated/ebooks/building-a-modern-security-program.pdf
Nosso grupo oficial da Splunk:
https://usergroups.splunk.com/sao-paulo-splunk-user-group/
Conservation of Taksar through Economic RegenerationPriyankaKarn3
This was our 9th Sem Design Studio Project, introduced as Conservation of Taksar Bazar, Bhojpur, an ancient city famous for Taksar- Making Coins. Taksar Bazaar has a civilization of Newars shifted from Patan, with huge socio-economic and cultural significance having a settlement of about 300 years. But in the present scenario, Taksar Bazar has lost its charm and importance, due to various reasons like, migration, unemployment, shift of economic activities to Bhojpur and many more. The scenario was so pityful that when we went to make inventories, take survey and study the site, the people and the context, we barely found any youth of our age! Many houses were vacant, the earthquake devasted and ruined heritages.
Conservation of those heritages, ancient marvels,a nd history was in dire need, so we proposed the Conservation of Taksar through economic regeneration because the lack of economy was the main reason for the people to leave the settlement and the reason for the overall declination.
In May 2024, globally renowned natural diamond crafting company Shree Ramkrishna Exports Pvt. Ltd. (SRK) became the first company in the world to achieve GNFZ’s final net zero certification for existing buildings, for its two two flagship crafting facilities SRK House and SRK Empire. Initially targeting 2030 to reach net zero, SRK joined forces with the Global Network for Zero (GNFZ) to accelerate its target to 2024 — a trailblazing achievement toward emissions elimination.
An Internet Protocol address (IP address) is a logical numeric address that is assigned to every single computer, printer, switch, router, tablets, smartphones or any other device that is part of a TCP/IP-based network.
Types of IP address-
Dynamic means "constantly changing “ .dynamic IP addresses aren't more powerful, but they can change.
Static means staying the same. Static. Stand. Stable. Yes, static IP addresses don't change.
Most IP addresses assigned today by Internet Service Providers are dynamic IP addresses. It's more cost effective for the ISP and you.
A vernier caliper is a precision instrument used to measure dimensions with high accuracy. It can measure internal and external dimensions, as well as depths.
Here is a detailed description of its parts and how to use it.
Social media management system project report.pdfKamal Acharya
The project "Social Media Platform in Object-Oriented Modeling" aims to design
and model a robust and scalable social media platform using object-oriented
modeling principles. In the age of digital communication, social media platforms
have become indispensable for connecting people, sharing content, and fostering
online communities. However, their complex nature requires meticulous planning
and organization.This project addresses the challenge of creating a feature-rich and
user-friendly social media platform by applying key object-oriented modeling
concepts. It entails the identification and definition of essential objects such as
"User," "Post," "Comment," and "Notification," each encapsulating specific
attributes and behaviors. Relationships between these objects, such as friendships,
content interactions, and notifications, are meticulously established.The project
emphasizes encapsulation to maintain data integrity, inheritance for shared behaviors
among objects, and polymorphism for flexible content handling. Use case diagrams
depict user interactions, while sequence diagrams showcase the flow of interactions
during critical scenarios. Class diagrams provide an overarching view of the system's
architecture, including classes, attributes, and methods .By undertaking this project,
we aim to create a modular, maintainable, and user-centric social media platform that
adheres to best practices in object-oriented modeling. Such a platform will offer users
a seamless and secure online social experience while facilitating future enhancements
and adaptability to changing user needs.
Phone Us ❤ X000XX000X ❤ #ℂall #gIRLS In Chennai By Chenai @ℂall @Girls Hotel ...
Unblocking The Main Thread - Solving ANRs and Frozen Frames
1. @snnkzk
Unblocking The Main Thread:
Solving ANRs and Frozen Frames
Sinan Kozak
Staff Android Developer
Google Developer Expert
2. @snnkzk
2
Sinan Kozak
12 years Android experience
Google Developer Expert
Staff Android Developer
@snnkzk
I wrote a chapter about performance in 2014
book with GDG community Ankara, Turkey.
7. @snnkzk
7
Rendering a frame
between 16ms and 700ms
Scroll
Animations
Frame render
Slow Rendering
Rendering a frame
between 700ms and 5s
App startup
Navigation
Frozen Frame
Blocking main thread
over 5 seconds
Not being able to
handle user inputs
Application Not Responding
Different stages of Jank
11. @snnkzk
11
Can slow runtime cause app crashes?
YES
● User will continue to click the screen. New events without being
able to handle to current event will cause unexpected app states.
● Foreground services crashes when their start is delayed
13. @snnkzk
13
Reuse thread pool
Reducing allocation
Fix memory leaks
Release Memory Pressure
R8/Proguard optimization
Fast dependency Injection
WebP and vector images
Use reportFullyDrawn
Baseline profile
Render First Frame
Execute in background
Reduce recomposition
Use correct Compose APIs
Measure and optimize
Drain Main Thread
Different categories of solutions
14. @snnkzk
14
Quick wins
01 Execute in background
RxJava, Coroutine and other thread solutions
02 Thread pool reuse
Utilize thread pools
03 R8/Proguard optimization
Auto apply proven optimizations
04 Reducing allocation
Only store necessary data in memory
05 No memory leak
Fix all leaks
06 Dependency Injection
Time consuming injection should be in background
07 WebP and vector images
Simpler the image faster to draw
08 Less recomposition
Avoid recurring recomposition
09 Correct Compose API
Use lambda based api for fast changing values
10 reportFullyDrawn
Talk to OS about what needs to prioritize
11 Baseline profile
Make sure OS optimize app startup
12 Measure and optimize
We can have optimized apps
17. @snnkzk
17
In your heap dump, look for memory leaks caused by any of the following:
● Long-lived references to Activity, Context, View, Drawable, and other objects
that might hold a reference to the Activity or Context container.
● Non-static inner classes, such as a Runnable, that can hold an Activity instance.
● Caches that hold objects longer than necessary.
Memory leak
In your heap dump, look for memory leaks caused by any of the
following:
● Long-lived references to Activity, Context, View, Drawable, and
other objects that might hold a reference to the Activity or
Context container.
● Non-static inner classes, such as a Runnable, that can hold an
Activity instance.
● Caches that hold objects longer than necessary.
21. @snnkzk
21
Share Thread Pools
Most of features have their own thread pool
● RxJava
● Coroutine
● OkHttp
● Image loader
● AsyncTask
● AndroidX arch components
● RecyclerView + DiffUtil
● WorkManager
● … many more
And they have APIs to change thread pool
22. @snnkzk
22
Share Thread Pools
We shared Coroutine Dispatchers with
● RxJava
● OkHttp
● Coil
● WorkManager
Thread count reduced 180+ to 130~ after refresh action
“asOkHttpExecutorService” is a custom implementation that only handle execute function
24. @snnkzk
24
R8 and proguard are mainly obfuscation tools, but…
They also shrink and optimize codes.
In order to optimize your app even further, R8 inspects your code at a deeper level to
remove more unused code or, where possible, rewrite your code to make it less
verbose. The following are a few examples of such optimizations:
● If your code never takes the else {} branch for a given if/else statement, R8
might remove the code for the else {} branch.
● If your code calls a method in only a few places, R8 might remove the method
and inline it at the few call sites.
Prefer "proguard-android-optimize.txt" over default
Improve app performance by up to 30%
R8/Proguard optimization
25. @snnkzk
25
More resources optimizations
High level documentation
https://developer.android.com/build/shrink-code
https://www.guardsquare.com/manual/configuration/optimizations
Detailed posts
https://jakewharton.com/blog/
26. @snnkzk
26
Use multi thread
solutions
● IO operations
● Data parsing
● Encryption
● Any time consuming operation
Move work to the background
Photo by Campbell on Unsplash
27. @snnkzk
27
Execute in background with Coroutine
https://kotlinlang.org/docs/coroutines-overview.html
https://developer.android.com/kotlin/coroutines#use-coroutines-for-main-safety
29. @snnkzk
29
Recomposition
Recompose count shouldn’t affect correctness.
The compose runtime might end up recomposing a lot more than
you’d expect.
Just looking at the code does not reveal reasons.
Functions can be inline
Classes can be mutable
31. @snnkzk
31
Donut hole skipping
● Lambdas are special in Compose
● The runtime keeps track of values used in lambdas
● Lambdas get reevaluated if values change
● Composable can be skipped if they are not affected by change
34. @snnkzk
34
WebP
WebP is an image file format from Google that provides lossy compression
(like JPEG) as well as transparency (like PNG) but can provide better
compression than either JPEG or PNG
Average %26 less space
More efficient
Android Studio can convert images
https://developer.android.com/studio/write/convert-webp
Resource optimizations
35. @snnkzk
35
Resource optimizations
Vector Drawables
is a vector graphic defined in an XML file as a
set of points, lines, and curves along with its
associated color information.
Scalable
svg can be converted to Vector drawables
Simpler is better
The initial loading of a vector drawable can cost
more CPU cycles than the corresponding raster
image.
Size save should be justified with performance
Use Avocado tool to simplify complex vectors
https://github.com/alexjlockwood/avocado
41. @snnkzk
41
Baseline Profiles
● Helps app startup after new install or update
● Android run ahead of time compile to prepare app startup
● We can modify and create aggregated profiles
● Libraries can have their own baseline profiles
● Compose benefit from baseline profiles
https://developer.android.com/topic/performance/baselineprofiles/create-baselineprofile
47. @snnkzk
47
Random ANR points during app start up
ANR stacktrace is delayed
Android 14 has improved ANR capturing
Filter ANR for Android 14 to get better picture
ANR report only contain last executed things
There could be other slowness on main thread
48. @snnkzk
48
Measure as much as you can
● Profile a variant close to release
● Measure high level first
● Add more granular metrics
● Use benchmark tests
● Profile before and after changes
● Collect data from production
50. @snnkzk
50
How to measure?
Data from profiling
● perfetto.dev
● Systrace
● CPU and memory allocation
● Layout inspector and debugger
Data from users
● Firebase Performance Monitoring or similar solutions
● JankStat library
● Memory leaks
● Strict mode
58. @snnkzk
58
10 years retro of performance suggestions
View hierarchy - ViewStub > Composables with if check
ListView - ViewHolder > RecyclerView + LazyColumn
Memory leaks > Memory leaks still exists
Running in background > Coroutine - RxJava
We still have things to optimized.
They are just different.