Cold start and hot start
Before we start optimizing, let's take a deeper look at the startup process of Android apps. The startup of Android applications can be divided into two situations: cold start and hot start. Cold startup means that the application starts from a fully closed state, while hot startup means restarting the application from a background state. Although hot start is also important, optimizing cold start has a more significant impact on improving user experience, as it requires loading more resources and components.
Layout optimization
When the application starts, the system needs to load layout resources and build view levels. Therefore, layout optimization is the key to improving startup speed.
Flexible layout with ConstraintLayout
ConstraintLayout
It is a powerful and efficient layout method that can reduce nesting levels and improve layout performance. It positions views by defining constraint relationships, reducing frequent measurement and layout operations in traditional layouts.
< xmlns:andro xmlns:app="/apk/res-auto"> <!-- Add yours hereUIelement --> </>
Use ViewStub to implement lazy loading
ViewStub
is a special view provided by Android that acts as a placeholder that is instantiated and loaded when it needs to display its content. Use in layoutViewStub
Ability to effectively delay loading of views, thereby speeding up startup time.
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!-- otherUIelement --> <ViewStub android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout="@layout/my_delayed_layout" /> </RelativeLayout>
in@layout/my_delayed_layout
is a reference to the layout resource to be delayed loading.
Show if requiredViewStub
The location of the content, call()
Method loads the actual layout content:
ViewStub myViewStub = findViewById(); View inflatedView = ();
Normally, you can trigger loading based on user interaction or other conditions. In short, with setting the view toandroid:visibility="gone"
Compared toViewStub
It is a better way to implement latency loading, especially when performance improvements are required at startup.
Startup timing optimization
Finely controlling the startup timing can significantly improve the startup speed. The following are some optimization strategies.
Presents a striking splash screen interface
The introduction of Splash Screen interface (Splash Screen) can display brand logos or load animations while the application loads resources, alleviating the sense of waiting during the startup process.
existres/values/
Styles defined in:
<style name="" parent=""> <item name="android:windowBackground">@drawable/splash_background</item> </style>
existres/drawable
Created insplash_background.xml
:
<layer-list xmlns:andro> <item android:drawable="@color/splashBackgroundColor" /> <item> <bitmap android:src="@drawable/app_logo" android:gravity="center" /> </item> </layer-list>
existSet the Splash Screen style in:
<activity android:name=".SplashActivity" android:theme="@style/"> <intent-filter> <action android:name="" /> <category android:name="" /> </intent-filter> </activity>
Reduce the burden on the main thread
The main thread is responsible for handling the application's UI operations, so it is crucial to reduce the workload of the main thread during startup.
Make full use of asynchronous tasks
Blocking the main thread is avoided by transferring time-consuming tasks to the background thread. You can useAsyncTask
orViewModel
To manage data and UI updates.
public class MyAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { // Execute time-consuming tasks return null; } @Override protected void onPostExecute(Void aVoid) { // Update the UI or perform other operations } }
Smart background initialization
Put part of the initialization work required to start up into the background thread to process it to display the core interface of the application faster.
public class StartupTask extends Application { @Override public void onCreate() { (); // Execute initialization work in background thread new Thread(() -> { // Execute initialization work }).start(); } }
Optimize application resource loading
During application startup, the loading of resources may be an important factor affecting startup speed. Optimizing resource loading can significantly reduce startup time.
Using vector graphics resources
Using vector graphics resources (SVG, Vector Drawable) instead of bitmap resources can reduce the size of the APK and adapt to devices with different screen densities.
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@drawable/ic_vector_image" />
Compressed bitmap resources
Use tools such as TinyPNG to compress PNG and JPEG images to reduce the size of the APK. Also, make sure to provide a variety of densities of picture resources to suit devices with different screens.
Using the application cold start optimization library
Android provides some excellent startup optimization libraries that can help you automatically manage and reduce startup time.
Dependency injection using Hilt
Hilt is a dependency injection library provided by Android. By using Hilt, you can move the dependencies created at startup to the background, reducing work on the main thread.
// Define dependencies@Module @InstallIn() public class MyModule { @Provides public MyDependency provideMyDependency() { return new MyDependency(); } } // Initialize Hilt in Application@HiltAndroidApp public class MyApp extends Application { }
Refactoring the UI using Jetpack Compose
Jetpack Compose is a modern UI toolkit that helps you build interfaces in a declarative way. Due to its performance advantages, using Compose can improve the startup speed of your application.
@Composable fun MyScreen() { Column { Text(text = "Hello, Jetpack Compose!") Button(onClick = { /* Do something */ }) { Text(text = "Click me") } } }
Appropriate use of multi-processes
Putting some time-consuming initialization work in a separate process can reduce the burden on the main process and thus increase the startup speed of the application.
Create a background process
Define a background process in:
<application android:name=".MyApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:process=":background"> <!-- ... --> </application>
Perform time-consuming tasks
Execute time-consuming tasks in background processes, such as initializing certain modules or resources:
public class BackgroundProcessService extends Service { @Override public void onCreate() { (); // Execute time-consuming tasks in background process // ... stopSelf(); // Stop service after the task is completed } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
Reduce cold start of startup activity
During the Android startup process, cold-start activity takes up a large proportion. Here are some ways to reduce cold start activity time.
Start Mode with SingleTask
Setting the cold-start Activity to SingleTask startup mode allows you to reuse existing Activity instances in the same task stack, thereby reducing the duplicate creation of Activity.
<activity android:name=".MainActivity" android:launchMode="singleTask"> </activity>
Optimize cold boot experience with Splash Screen
Perform some initialization operations in Splash Screen, such as preloading data, thereby moving some cold start time to the Splash Screen stage.
public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); // Perform initialization operations, such as preloading data // ... startActivity(new Intent(this, )); finish(); } }
With the help of third-party open source libraries
android-startupProvides a simpler and more efficient way to initialize components when the application starts. Developers can use android-startup to simplify startup sequences and explicitly set the dependencies between the initialization order and components. At the same time, android-startup supports synchronization and asynchronous waiting, and ensures the initialization order of internal dependent components through directed acyclic graph topology sorting.
Add dependencies
repositories { mavenCentral() } dependencies { implementation ':android-startup:1.1.0' }
Define initialized components
Each initialized component needs to implement the AndroidStartup abstract class, which implements the Startup interface. For example, the following defines a SampleSecondStartup class to implement the AndroidStartup abstract class:
class SampleSecondStartup : AndroidStartup<Boolean>() { override fun callCreateOnMainThread(): Boolean = false override fun waitOnMainThread(): Boolean = true override fun create(context: Context): Boolean { // Imitation execution takes time (5000) return true } override fun dependenciesByName(): List<String> { return listOf("") } }
It is returned in the dependenciesByName() method, so it can ensure that SampleFirstStartup is executed first.
Start the configuration
There are two configurations, automatic configuration in Manifest and manual configuration in Application. The following is an example of automatic configuration:
<provider android:name=".android_startup." android:authorities="${applicationId}.android_startup" android:exported="false"> <meta-data android:name="" android:value="" /> </provider>
The StartupProvider class is provided in Android Startup, which is a special content provider that automatically recognizes the initialization components configured in manifest. In order for it to be automatically identified, it is necessary to define the tag in StartupProvider. The name is the defined component class, and the value of the value corresponds to.
Reasonable management of startup tasks will greatly improve the startup time of the application and obtain a better startup experience.
in conclusion
By optimizing application resource loading, using excellent startup optimization libraries, appropriate use of multiple processes, and reducing the time of cold-start activities, you can further improve the startup speed of Android applications and create a better startup experience for users. Different optimization strategies can collaborate with each other to achieve better results.
The above are the detailed contents of some effective Android startup optimization strategies. For more information about Android startup optimization strategies, please follow my other related articles!