A deep dive into Android startup optimization strategies

A deep dive into Android startup optimization strategies

In today's fiercely competitive mobile application market, the startup speed of an application directly affects the user's first impression and satisfaction. As one of the mainstream mobile operating systems, Android startup optimization is a key area that developers must pay attention to. This article will introduce in detail some powerful and effective Android startup optimization strategies to help you optimize the application startup process and create a better experience for users.

Cold start and warm start

Before getting started with optimization, 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 warm start. A cold start is when an app is started from a completely closed state, while a warm start is when an app is restarted from a background state. Although hot start is also important, optimizing cold start has a more significant impact on improving user experience because it requires loading more resources and components.

Layout optimization

When the app starts, the system needs to load layout resources and build the view hierarchy. Therefore, layout optimization is the key to improving startup speed.

Use ConstraintLayout for flexible layout

ConstraintLayoutIt is a powerful and efficient layout method that can reduce nesting levels and thereby improve layout performance. It positions views by defining constraint relationships, reducing frequent measurement and layout operations in traditional layout.

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- 在此添加你的UI元素 -->

</androidx.constraintlayout.widget.ConstraintLayout>
Using ViewStub to implement lazy loading

ViewStub is a special view provided by Android that acts as a placeholder and is instantiated and loaded when its content needs to be displayed. Using ViewStub in the layout can effectively delay the loading of the view, thus speeding up the startup time.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 其他UI元素 -->

    <ViewStub
        android:id="@+id/myViewStub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout="@layout/my_delayed_layout" />
</RelativeLayout>

where@layout/my_delayed_layout is a reference to the layout resource to be lazy loaded.

At the location where ViewStub content needs to be displayed, call the ViewStub.inflate() method to load the actual layout content:

ViewStub myViewStub = findViewById(R.id.myViewStub);
View inflatedView = myViewStub.inflate();

Typically, you can trigger loading based on user interaction or other conditions. In summary, using is a better way to implement lazy loading than setting the view to android:visibility="gone", especially if you need to improve performance at startup. ViewStub

Startup timing optimization

Fine control of startup timing can significantly improve startup speed. Here are some optimization strategies.

Present eye-catching splash screen interfaces

The introduction of the Splash Screen interface can display the brand logo or loading animation while the application is loading resources, alleviating the sense of waiting during the startup process.

Defines style in res/values/styles.xml:

<style name="AppTheme.Splash" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/splash_background</item>
</style>

in res/drawable in middle school splash_background.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/splashBackgroundColor" />
    <item>
        <bitmap
            android:src="@drawable/app_logo"
            android:gravity="center" />
    </item>
</layer-list>

Set Splash Screen style in AndroidManifest.xml:

<activity
    android:name=".SplashActivity"
    android:theme="@style/AppTheme.Splash">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Reduce the burden on the main thread

The main thread is responsible for handling the UI operations of the application, so it is important to reduce the workload of the main thread during the startup process.

Make the most of asynchronous tasks

avoids blocking the main thread by transferring time-consuming tasks to a background thread. You can use AsyncTask or ViewModel to manage data and UI updates.

public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
    
    
    @Override
    protected Void doInBackground(Void... voids) {
    
    
        // 执行耗时任务
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
    
    
        // 更新UI或执行其他操作
    }
}
Intelligent background initialization

Put part of the initialization work required for startup into a background thread to display the core interface of the application faster.

public class StartupTask extends Application {
    
    

    @Override
    public void onCreate() {
    
    
        super.onCreate();
        // 在后台线程中执行初始化工作
        new Thread(() -> {
    
    
            // 执行初始化工作
        }).start();
    }
}

Optimize application resource loading

During the application startup process, the loading of resources may be an important factor affecting the startup speed. Optimizing resource loading can significantly reduce startup time.

Use 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 like TinyPNG to compress PNG and JPEG images to reduce APK size. Also, make sure to provide image assets in a variety of densities to accommodate different screen devices.

Using 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 an official dependency injection library provided by Android. By using Hilt, you can move dependencies created on startup to the background, reducing work on the main thread.

// 定义依赖关系
@Module
@InstallIn(SingletonComponent.class)
public class MyModule {
    
    
    @Provides
    public MyDependency provideMyDependency() {
    
    
        return new MyDependency();
    }
}

// 在Application中初始化Hilt
@HiltAndroidApp
public class MyApp extends Application {
    
    
}
Refactor 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")
        }
    }
}

Use multiple processes appropriately

Placing certain time-consuming initialization work in a separate process can reduce the burden on the main process, thus improving the startup speed of the application.

Create background process

Define a background process in AndroidManifest.xml:

<application
    android:name=".MyApplication"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:process=":background">
    <!-- ... -->
</application>
Perform time-consuming tasks

Perform time-consuming tasks in a background process, such as initializing certain modules or resources:

public class BackgroundProcessService extends Service {
    
    
    @Override
    public void onCreate() {
    
    
        super.onCreate();
        // 在后台进程中执行耗时任务
        // ...
        stopSelf(); // 任务完成后停止服务
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    
    
        return null;
    }
}

Reduce cold starts when starting Activity

During the startup process of Android, cold startup Activity takes up a large proportion of the time. Here are some ways to reduce the time it takes to cold start an activity.

Using SingleTask startup mode

Setting the cold start Activity to SingleTask startup mode can reuse existing Activity instances in the same task stack, thereby reducing repeated creation of Activity.

<activity
    android:name=".MainActivity"
    android:launchMode="singleTask">
</activity>
Optimize the cold start experience with Splash Screen

Perform some initialization operations in Splash Screen, such as preloading data, thereby moving part of the cold start time to the Splash Screen stage.

public class SplashActivity extends AppCompatActivity {
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        // 执行初始化操作,如预加载数据
        // ...
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}

Using third-party open source libraries

Android Startup:https://github.com/idisfkj/android-startup

(You can go to the bottom and click to read the original text)

android-startup provides a simpler and more efficient way to initialize components when the application starts. Developers can use android-startup to simplify the startup sequence and explicitly set dependencies between initialization sequences and components. At the same time, android-startup supports synchronous and asynchronous waiting, and ensures the initialization order of internal dependent components through directed acyclic graph topological sorting.

Add dependencies
repositories {
    
    
    mavenCentral()
}

dependencies {
    
    
    implementation 'io.github.idisfkj: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 {
    
    
        // 模仿执行耗时
        Thread.sleep(5000)
        return true
    }

    override fun dependenciesByName(): List<String> {
    
    
        return listOf("com.rousetime.sample.startup.SampleFirstStartup")
    }

}

com.rousetime.sample.startup.SampleFirstStartup is returned in the dependenciesByName() method, so it can ensure that SampleFirstStartup is executed first.

startup configuration

Two configurations are provided, automatic configuration in Manifiest and manual configuration in Application. An example of automatic configuration is given below:

<provider
    android:name="com.rousetime.android_startup.provider.StartupProvider"
    android:authorities="${applicationId}.android_startup"
    android:exported="false">

    <meta-data
        android:name="com.rousetime.sample.startup.SampleFourthStartup"
        android:value="android.startup" />

</provider>

The StartupProvider class is provided in Android Startup. It is a special content provider that automatically recognizes the initialization components configured in the manifest. In order for it to be automatically recognized, the label needs to be defined in the StartupProvider. The name is the defined component class, and the value of value corresponds to android.startup.

Reasonable management of startup tasks will greatly improve the application startup time and obtain a better startup experience.

in conclusion

By optimizing application resource loading, using excellent startup optimization libraries, appropriately using multiple processes, and reducing cold start activity time, you can further improve the startup speed of Android applications and create a better startup experience for users. Different optimization strategies can cooperate with each other to achieve better results.

Finally, we share a complete set of Android learning materials to give some help to those who want to learn Android!

Applies to:

  • Anyone who wants to learn Android development but doesn't know where to start
  • Also for anyone who's already started Android development but wants to get better at it

1. Learning routes in all directions of Android

Here is a general roadmap for you to become a better Android developer. Its usefulness is that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively. If the following learning route can help everyone become a better Android developer, then my mission will be accomplished:

Including: Android application development, system development, audio and video development, Flutter development, small program development, UI interface, vehicle system development, etc.

Insert image description here

2. Learning software

If a worker wants to do his job well, he must first sharpen his tools. Commonly used Android Studio video tutorials for learning Android and the latest Android Studio installation package are here, saving everyone a lot of time.


3. Advanced learning videos

When we are studying, the source code of books is often difficult to understand and difficult to read. At this time, video tutorials are very suitable. With vivid images and practical cases, it is scientific and interesting to learn more conveniently.

Insert image description here

4. Practical cases

Optical theory is useless. You must learn to follow along and practice it in order to apply what you have learned to practice. At this time, you can learn from some practical cases.

Insert image description here

5. Reading classic books

Reading classic Android books can help readers improve their technical level, broaden their horizons, master core technologies, and improve their ability to solve problems. At the same time, they can also learn from the experiences of others. For readers who want to learn Android development in depth, reading classic Android books is very necessary.

Insert image description here

6. Interview materials

We must learn Android to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and Alibaba bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.

图片

Please add image description

This complete version of the complete set of Android learning materials has been uploaded to CSDN. If you need it, friends can scan the CSDN official certification QR code below on WeChat to get it for free [保证100%免费]

Guess you like

Origin blog.csdn.net/Android23333/article/details/134823634