Android app start time

Содержание
  1. Русские Блоги
  2. Холодный старт и горячий старт Android и схема оптимизации
  3. Горячий старт
  4. Определение:
  5. Особенности:
  6. Холодный старт
  7. Определение:
  8. Особенности:
  9. Холодный старт для приложения, чтобы открыть в считанные секунды
  10. Схема оптимизации
  11. Устранить белый / черный экран при запуске
  12. 1. Установите фоновое изображение в качестве логотипа нашего приложения в качестве руководства для запуска приложения. Теперь большинство приложений на рынке делают то же самое.
  13. 2. Установите прозрачный фоновый цвет, чтобы, когда пользователь нажимает на изображение APP на рабочем столе, он не входил в приложение «сразу» и некоторое время оставался на рабочем столе. Фактически, приложение уже активировано в это время, на наш взгляд Я установил прозрачный цвет windowBackground в Theme и принудительно отправил банк производителю приложений для мобильных телефонов (отклик на мобильный телефон слишком медленный, ха-ха). На самом деле WeChat делает то же самое сейчас. Не думаю, что вы можете попробовать.
  14. Интеллектуальная рекомендация
  15. Многослойная презентацияViewController Jap
  16. Распечатать список с конца до головы
  17. Типы данных и переменные
  18. Python Daily Practice (4) -идиомы заполняют музыку
  19. Warming Up The Cold Start: How To Reduce Cold Startup Time Of Your Android App
  20. Cold start? Enlighten me, please!
  21. How much is too much?
  22. How do I track the cold start performance of my app?
  23. And how do I get the exact number?
  24. Enough said! How do I fix it now?
  25. Good to Go. What next?
  26. RESTRUCTURING THE CODE
  27. OPTIMISING THE UI

Русские Блоги

Холодный старт и горячий старт Android и схема оптимизации

Горячий старт

Определение:

Когда приложение запускается, процесс приложения уже существует в фоновом режиме (например: нажмите клавишу возврата, клавишу возврата домой, хотя приложение будет закрыто, но процесс приложения останется в фоновом режиме, вы можете ввести список задач для просмотра), поэтому В случае процесса этот запуск запустит приложение из существующего процесса. Этот метод называется горячим стартом.

Особенности:

Поскольку горячий запуск будет начинаться с существующего процесса, поэтому горячий запуск не будет выполнять шаг приложения, а будет напрямую переходить к MainActivity (включая серию измерений, макет, чертеж), поэтому процесс горячего запуска нужно только создать И инициализировать MainActivity без необходимости создавать и инициализировать приложение,

Поскольку приложение создается от создания нового процесса до его уничтожения, приложение инициализируется только один раз.

Процесс создания, инициализации и запуска Activity может ссылаться на эту статью:Глубокое погружение в жизненный цикл деятельности и процесс запуска

Холодный старт

Определение:

Когда приложение запускается, процесс в фоновом режиме для приложения отсутствует. В это время система заново создаст новый процесс, назначенный приложению. Этот метод запуска — холодный запуск.

Особенности:

Холодный запуск, потому что система будет воссоздавать новый процесс, назначенный ей, поэтому он будет создан и инициализирован первымКласс приложенияЗатем создайте и инициализируйте класс MainActivity (включая серию измерений, макет, чертеж) и, наконец, отобразите в интерфейсе.

WindowBackground и другие свойства имеют значение MainActivity и настраивают некоторые свойства на уровне Activity, а затем раздувают макет.После завершения метода onCreate / onStart / onResume мера contentView / layout / draw наконец-то отображается в интерфейсе, так что пока здесь,

Первый запуск приложения считается завершенным. На данный момент интерфейс, который мы видим, является первым кадром. Итак, подведем итог, процесс запуска приложения выглядит следующим образом:

Метод конструктора приложения-> attachBaseContext () -> onCreate () -> Метод построения действия-> onCreate () -> настроить фон и другие свойства в теме-> onStart () -> onResume ( ) -> Схема измерений рисуется и отображается на интерфейсе.

Создание и инициализация конкретного действия также могут быть отмечены:Глубокое погружение в жизненный цикл деятельности и процесс запуска

Холодный старт для приложения, чтобы открыть в считанные секунды

Время холодного старта:
Время холодного запуска относится к периоду времени с момента, когда пользователь щелкает приложение с мобильного рабочего стола, до момента, когда активность на странице запуска вызывает метод onCreate ().

Что произошло в период холодного старта:
Прежде всего, нам нужно знать, что происходит при открытии действия. Когда открывается действие, если приложение, которому принадлежит действие, не было запущено, система создаст процесс для этого действия ( Приложение вызывается каждый раз, когда создается процесс, поэтому метод ApplicationContate () может вызываться несколько раз.) Во время создания и инициализации процесса он определенно будет занимать некоторое время. За это время WindowManager загрузит Фон окна в стиле темы (windowBackground) используется в качестве элемента предварительного просмотра, а затем фактически загружается макет. Если это время слишком длинное и фон по умолчанию черный или белый, это создаст иллюзию для пользователя. Это приложение очень застряло Очень свободно, естественно, также влияет на пользовательский опыт.

Читайте также:  Текстовый редактор для андроид для html

Схема оптимизации

Устранить белый / черный экран при запуске

Когда пользователь нажимает на мобильное приложение для настольного компьютера, черный или белый экран, который он видит, фактически является первым кадром перед визуализацией интерфейса. Если вы понимаете две проблемы в начале статьи, решить эту проблему очень легко. Достаточно установить windowBackground в теме на изображение, которое мы хотим видеть пользователю. Вот два способа:

1. Установите фоновое изображение в качестве логотипа нашего приложения в качестве руководства для запуска приложения. Теперь большинство приложений на рынке делают то же самое.

2. Установите прозрачный фоновый цвет, чтобы, когда пользователь нажимает на изображение APP на рабочем столе, он не входил в приложение «сразу» и некоторое время оставался на рабочем столе. Фактически, приложение уже активировано в это время, на наш взгляд Я установил прозрачный цвет windowBackground в Theme и принудительно отправил банк производителю приложений для мобильных телефонов (отклик на мобильный телефон слишком медленный, ха-ха). На самом деле WeChat делает то же самое сейчас. Не думаю, что вы можете попробовать.

При таком способе прозрачности следует помнить, что если тема непосредственно вводится в Activity, во время выполнения могут возникать следующие исключения:

Это потому, что используется несовместимая тема. Например, моя активность здесь наследует AppCompatActivity. Решение простое:
1. Пусть его Activity интегрируется с Activity вместо AppCompatActivity с совместимостью
2. Установите тему нашего оригинального приложения перед super.onCreate (saveInstanceState) в методе onCreate ()

Для вышеупомянутых двух методов нам нужно ввести тему в соответствующее задание

Автор: лишайник Вэй
Ссылка :https://www.jianshu.com/p/03c0fd3fc245
Источник: Цзяньшу
Авторские права на Jianshu принадлежат автору. Пожалуйста, свяжитесь с автором для авторизации в любой форме, чтобы перепечатать и указать источник.

Интеллектуальная рекомендация

Многослойная презентацияViewController Jap

. Недавно, проект использует многоэтажные прыжки [A presentViewController: B animated: YES] [B presentViewController: C animated: YES] . Проблема в том, где: как это идет прямо к? Я не нашел ме.

Распечатать список с конца до головы

В случае, когда таблица цепи не может изменять дисплей, данные хранения стека могут рассматриваться с рекурсивным методом. Разрешить модификацию структуры ссылки.

Типы данных и переменные

тип данных Компьютерная программа может обрабатывать различные значения. Однако компьютеры могут обрабатывать гораздо больше, чем числовые значения. Они также могут обрабатывать различные данные, таки.

Python Daily Practice (4) -идиомы заполняют музыку

оглавление 1. Одно место 2. Случайное расположение 3. Добавьте баллы для оценки 4. Получение файла 5. Установите уровень сложности. 6. Срок завершения 7. Выберите заполнение пропусков. 1. Одно место Н.

Источник

Warming Up The Cold Start: How To Reduce Cold Startup Time Of Your Android App

Have you ever had your patience tested by apps that cheekily keep flashing their logos at you for a moment too long, while you just cannot wait to order food or book a cab or pay the cab driver and rush to work? If that sounds like you, you too have been a victim of poor cold startup time, and unless you want your app to add to that growing pool of the digitally downtrodden, read on!

Cold start? Enlighten me, please!

Cold start refers to an app starting from a scratch, that is the time taken from the moment the code is initialised till the UI is responsive to the user. It happens in cases such as your app is being launched for the first time since the device booted, or since the system killed the app. Needless to say, the lesser the cold startup time, the better the user experience.

developer.android provides a comprehensive explanation of app startup time here.

How much is too much?

For cold start, anything above 5 seconds is considered excessive.

How do I track the cold start performance of my app?

To check how your Android app is performing in comparison to other apps, go to Play Console > your app > Android Vitals > App Startup Time.

Читайте также:  Гибкая камера для смартфона андроид

And how do I get the exact number?

In Android 4.4 and higher, logcat includes an output line containing a value called “Displayed”. This value represents the amount of time elapsed between launching the process and finishing drawing the corresponding activity on the screen. The reported log line looks similar to the following example:

ActivityManager: Displayed com.android.app/.StartupTiming: +3s534ms

P.S. if you are tracking the time in Android studio, make sure you disable filters in your logcat view because it is the system server, and not the app, that serves this log.

Don’t be confused if the “Displayed” line in the logcat output contains an additional field for “total” time. For example:

ActivityManager: Displayed com.android.gradeup/.StartupTiming: +3s534ms (total +1m22s643ms)

Here, the first time measurement is only for the activity that was first drawn and the “total” time measurement begins at the app process start, and could include another activity that was started first but did not display anything to the screen (for example a splash screen). This extra measurement is shown when there is a difference between the single activity and total startup times.

Enough said! How do I fix it now?

Before we delve into the code and start digging it for prospective flaws, let’s first try and identify the performance bottlenecks. Android provides us with some really cool tools that provide us with an in-depth analysis of our app’s behaviour.

  • Android profiler: The new Android Profiler window in Android Studio 3.0 and higher replaces the Android Monitor tools. It provides realtime data for your app’s CPU, memory, and network activity. You can perform sample-based method tracing to time your code execution, capture heap dumps, view memory allocations, and inspect the details of network-transmitted files.
  • Firebase Performance monitoring: It is a service that helps you to gain insights into the performance characteristics of your app. It automatically measures the app startup time and gives you the details about the rendering time and startup metrics of your activities in the Firebase console. You can also use it to measure custom traces by specifying the trace start and end points within the code.
  • Traceview: Traceview is a tool that provides a graphical representations of trace logs. You can generate the logs by instrumenting your code with the Debug class. This method of tracing is very precise because you can specify exactly where in the code you want to start and stop logging trace data.
  • Systrace: The Systrace command allows you to collect and inspect timing information across all processes running on your device at the system level. It combines data from the Android kernel to generate an HTML report that provides an overall picture of an Android device’s system processes for a given period of time and also inspects the captured information to highlight problems that it observes, such as UI jank, and provides recommendations about how to fix them.
  • Hierarchy Viewer: Hierarchy Viewer allows you to measure the layout speed for each view in your layout hierarchy. It can help you find performance bottlenecks caused by the structure of your view hierarchy.

P.S. If you’re using Android Studio 3.1 or later, you should instead use Layout Inspector to inspect your app’s view hierarchy at runtime.

  • Debug GPU Overdraw tool: It uses color-coding to show the number of times your app draws each pixel on the screen. The higher this count, the more likely it is that overdraw affects your app’s performance.

For those of you who are unfamiliar with these tools, Udacity provides a free course on Android performance that nicely explains how to leverage these tools to your benefit. Access the course here.

Good to Go. What next?

Now that you have analysed your app and zeroed in the problematic areas, let’s see how we can fix them for a better user experience and healthy app vitals.

Читайте также:  Slack не приходят уведомления android

RESTRUCTURING THE CODE

  • Tweaking the onCreate() — The chief reason for a poor cold-startup time is doing too much of work in the onCreate of your launcher activity.
  • Check the onCreate of your class and move all the independent and unblocking but time-consuming methods to a separate thread.
  • Make sure you use lazy initialisations wherever you can, so that the onCreate is not bombarded by unnecessary method or class initialisations.
  • Use Local variables wherever possible.
  • Use a dependency injection: You can use Koin or Dagger or any other dependency injector that can lazily provide you with the dependencies you want, as and when you want them.

You can refer to this article for a detailed explanation of Koin and its usage, or this for Dagger 2.

  • Using Handler with delay: Now this one might sound like a hack but it does wonders to your app startup performance- in cases where there is some piece of lethargic code which you cannot afford to shift from the main thread, you can put in in a Handler and use the postDelayed method, adding an appropriate delay(100 to 200ms should do just fine). This takes the weight off the onCreate and your app launches much quicker than before ,with unnoticeable delay in the execution of the delayed method.

new Handler().postDelayed(() -> < //your code >, 200);

OPTIMISING THE UI

  • Restructure the splash screen: Image rendering is a time consuming process and can mess up with your startup time. If you app uses a splash screen that displays your logo in an ImageView, one optimization you can do is to remove the ImageView from the xml and instead add the logo to the theme of your activity as windowBackground. Add the following line of code to your activity’s theme:
  • Flatten the view hierarchy: A nested hierarchy comes with a huge performance overhead called Overdraw. Overdraw refers to the system’s drawing a pixel on the screen multiple times in a single frame of rendering, where only the last drawn pixels are shown to the user while the others only add to the performance cost. For a better rendering performance, check your xml and flatten the view hierarchy as much as you can, removing any nested Relative or Linear layouts. Constrain layout suffices our need of creating a flat hierarchy to a large extent and gives great flexibility by providing multiple anchoring points, vertical and horizontal guidelines, chaining and more.
  • Use View Stubs: Views with default visibility set to “gone” add an unnecessary rendering overhead because they are drawn every time the view is rendered, but used only when the user sets their visibility to visible e.g. an activity that needs to show coach marks in the first session only will still draw the coach marks every time it is opened, setting their visibility to gone otherwise. By replacing such views with a ViewStub, we can reduce this overhead. A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime. It is only when a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated.

ViewStub coachStub = findViewById(R.id.homeCoachLayoutStub); View stubView = coachStub.inflate();

whenever you need to show the view.

  • Use WebP Images: 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. Using images in WebP format instead of PNG can reduce the size of on image by about 75%, resulting in less memory consumption and hence better performance!

Thats all, folks! Needless to say, there are many other factors that impact your app’s start up performance like the memory allocation of your app or the efficiency of your mobile device but by employing the above mentioned technique we at Gradeup and GoPrep managed to reduce our startup time by a whooping 58%! Cheers!

Источник

Оцените статью