Issue Description
The application has a high Android ANR (Application Not Responding) rate, currently above 3%, and requires optimization to reduce it to around 2%. The ANR stack traces typically appear during the Agora RtcEngine creation process or immediately after it is created.
Platform and SDK Context
Platform: Android
SDK: Agora RTC SDK (specifically observed on versions 3.1.0, 3.2.0, and 3.2.1, but applicable generally)
Error Message
No explicit error message is displayed. Application crash logs and traces point to ANRs occurring during RtcEngine creation, native library loading, initialization, or immediately when calling setLogFile.
Root Cause Analysis
The issue is not caused by a deadlock within the SDK. Based on the provided stack traces, the ANRs happen around RtcEngine creation, library loading, and initial configuration.
On lower-end Android devices, instantiating the RtcEngine and loading its associated native libraries can take longer than expected. If the application creates the RtcEngine on the main (UI) thread right before the user triggers the first channel join, it blocks the main thread. This delay causes the app UI to become unresponsive, subsequently triggering an ANR by the Android OS.
Solution and Resolution Steps
Do Not Create the RtcEngine Immediately Before the First Join
Avoid initializing the
RtcEngineright before the user attempts to join a channel. Synchronous creation at this stage will likely block the application flow on slower devices.Create the RtcEngine Earlier in the App Lifecycle
Shift the initialization of the
RtcEngineto an earlier phase in the application's lifecycle, preferably shortly after the app launches or during a dedicated loading screen.Run RtcEngine Creation on a Background Thread
This is the most critical step. Initialize the
RtcEngineon a background thread instead of the main thread. This ensures that heavy operations like native library loading do not freeze the UI.Finish Initialization Before the Join Scenario
Ensure that the background initialization of the SDK is fully completed before the user enters the specific scenario or UI view that requires joining a channel.
Reuse the Existing RtcEngine Instance
Once the engine is successfully created, maintain a reference to it and reuse the existing
RtcEngineinstance when the user joins a channel. Do not destroy and recreate the engine unnecessarily for subsequent joins.
Prevention and Best Practice
Always initialize the Agora
RtcEngineearly and asynchronously on a background thread, especially for user flows where the first channel join must happen quickly and seamlessly.By avoiding heavy instantiations on the main thread, you prevent blocking the user flow and significantly reduce the chance of ANRs, providing a smoother experience across a wider range of Android devices.