- Implement In-app Update In Android
- Make sure every user of your app is on the new version.
- What is In-App Update:
- Flexible Update:
- Benefits:
- Exploring in-app updates on Android
- Exploring in-app updates on Android
- I’m sure there has often been a time when you’ve needed to send out an app update that has some form of urgency — maybe…
- Checking an update is available
- Immediate in-app updates
- Flexible in-app updates
- In-App Updates: ускоряем процесс обновления приложения на Android
- Интеграция IAUs Flexible Flow
- Варианты использования
- Основные требования к тестированию
- Пример кода
- Ошибка «Update is Not Available»
- IAUs Flexible Flow в приложении Pandao
Implement In-app Update In Android
Make sure every user of your app is on the new version.
Apr 6, 2020 · 8 min read
In this article, we will learn about the In-app update feature in Android what is all about In-app update, what are the benefits of using the In-app update in your android application. Recently I’ve been working on a product in which I need to Implement an In-app update Why we need to Implement this?.
As a Developer we always want our users to have the updated version of their application but there are a lot of people who actually turned off their auto update from google play store and he/she doesn’t know about any update available or not.
To overcome the problem Google Introduced this feature called In-app update from this feature you can easily prompt the user to update the application and with the user permission you can update the application also while updating the app user can be able to interact with the application. Now the user doesn’t need to go to google play store to check there is any update available or not.
What is In-App Update:
An In-app update was Introduced as a part of the Play Core Library, which actually allows you to prompts the user to update the application when there is any update available on the Google Play Store.
There are two modes of an In-app update.
- Flexible Update
- Immediate Update
Flexible Update:
In Flexible update, the dialog will appear and after the update, the user can interact with the application.
This mode is recommended to use when there is no major change In your application like some features that don’t affect the core functionality of your application.
The update of the application is downloading in the background in the flexible update and after the completion of the downloading, the user will see the dialog in which the user needs to restart the application. The dialog will not automatically show, we need to check and show to the user and we will learn how later.
Benefits:
The major benefit of the flexible update is the user can interact with the application.
Источник
Exploring in-app updates on Android
This was originally posted on joebirch.co:
Exploring in-app updates on Android
I’m sure there has often been a time when you’ve needed to send out an app update that has some form of urgency — maybe…
I’m sure there has often been a time when you’ve needed to send out an app update that has some form of urgency — maybe there’s a security issue or some bug which is causing a lot of issues for users. Previously, we’ve needed to roll out a new update on the Google play store and wait for our users to receive the update. And if they don’t have automatic updates installed, we rely on the user visiting the play store to update our application. At Google I/O this week we saw the announcement of In-App Updates for the Play Core library. In this post we’re going to learn more about this addition and how we can make use of it in our applications.
Supporting API level 21 and above, the Play Core library now allows us to offer in-app updates to our users — meaning we can show that an app update is available whilst the user is within the context of our application. The Play Core library offers us two different ways in which we can prompt our users that an update is available — either using the Flexible or Immediate approach.
The Flexible approach shows the user an upgrade dialog but performs the downloading of the update within the background. This means that the user can continue using our app whilst the update is being downloaded. For more crucial application updates we can make use of the Immediate flow — this is where a blocking UI is used to prompt the user to update the application, disallowing continued use until the app has been updated and restarted.
Checking an update is available
Before we can get started with either of these, we’re going to begin by checking whether there is an update that is available from the play store. The code for doing this looks like so:
We begin by creating an instance of the AppUpdateManager class — this will be responsible for handling the information around our application information. Using this, we’re going to fetch an AppUpdateInfo instance — this needs to make a remote request to do so, which is why you can see us accessing the result property above. This AppUpdateInfo contains a collection of data that can be used to determine whether we should trigger the update flow.
To begin with, it has a method availableVersionCode() — if there is an update that is either currently available or in progress of being updated, this will return that version value. As well as this, there is also an updateAvailability() method which returns a value that represents the update state. This can be either:
- UNKNOWN
- UPDATE_AVAILABLE
- UPDATE_IN_PROGRESS
- DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
We first want to check that this is equal to UPDATE_AVAILABLE, followed by ensuring that the desired update type is supported by using the isUpdateTypeAllowed() function — passing in AppUpdateType type (either IMMEDIATE or FLEXIBLE) to ensure that the update type we want to use is supported.
Now that we have the information we need to determine whether or not an app update is available, we’re going to want to trigger the update flow. We can do this by making use of the startUpdateFlowForResult() method that comes with the AppUpdateManager class. When we call this we just need to pass:
- The AppUpdateInfo instance that we previously retrieved
- The AppUpdateType that we want to trigger (IMMEDIATE or FLEXIBLE)
- The context for the current component
- A request code so that cancellations / failures can be caught within the calling component
Calling this startUpdateFlowForResult() method will trigger a startActivityForResult() call and kick off the app update flow. In some cases, the request app update may be cancelled by the user (ActivityResult. RESULT_CANCELLED), or even fail (ActivityResult. RESULT_IN_APP_UPDATE_FAILED). In these cases we can catch the result in the onActivityResult() of our activity / fragment and handle the result accordingly.
Immediate in-app updates
Immediate in-app updates can be triggered by using the AppUpdateType.IMMEDIATE value — and as previously mentioned, this will trigger a blocking UI flow for the user until they have updated the app. This means that this UI will be shown during the entire time that the app is downloading and then installing, until the entire update process has completed. When the user leaves your app whilst the update is in process, the update will continue to download and then install in the background. However, if the user leaves and then returns to your app before the update process has completed, then you will need to ensure that we continue the update process.
For this we need to check whether or not the updateAvailability() returns the DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS state. If so then we need to trigger the update flow so that the update process can be resumed. If you do not implement this part of the flow then the user will be able to continue using your application without the immediate update in-effect.
For immediate updates we are not required to do any further work. The implementation will automatically restart our app once the update is downloaded, this is so that the update can be installed.
Flexible in-app updates
Flexible in-app updates can be triggered by using the AppUpdateType.FLEXIBLE value — and as previously mentioned, this will trigger a flow that displays an upgrade pop-up to the user and perform a download / install of the update in the background whilst the user can continue to use the application.
For this, we begin by launching the app update flow for a FLEXIBLE update:
Because this is all happening in the background, rather than creating a blocking UI like the immediate update, we need to add some monitoring so that we can keep a check on the state of the update install. For this we’re going to make use of the InstallStateUpdatedListener which will receive callbacks when the state of the flexible install changes. This contains a single callback, onStateUpdated(), which will pass us an instance of the InstallState class. From this we can make use of:
installStatus() — returns us a InstallStatus value that represents the current state of the update. This can be one of:
- UNKNOWN
- REQUIRES_UI_INTENT
- PENDING
- DOWNLOADING
- DOWNLOADED
- INSTALLING
- INSTALLED
- FAILED
- CANCELLED
installErrorCode() — returns us an InstallErrorCode that represents the error state of the install
- NO_ERROR
- NO_ERROR_PARTIALLY_ALLOWED
- ERROR_UNKOWN
- ERROR_API_NOT_AVAILABLE
- ERROR_INVALID_REQUEST
- ERROR_INSTALL_UNAVAILABLE
- ERROR_INSTALL_NOT_ALLOWED
- ERROR_DOWNLOAD_NOT_PRESENT
- ERROR_INTERNAL_ERROR
packageName() — returns us the package name that the install status applies to
Whilst there are a lot of options here for both the install status and the install error code, this gives us a lot of flexibility when it comes to handling the status. For example, if we are showing the user some specific UI to notify them of the current state, then we can customise the content within this based on the current status.
We can also have our activity implement this interface so that the callback can be overriden within the activity itself.
Now that we have the listener, we can register it with out AppUpdateManager instance using the registerListener() method. When finished with listener, we need to be sure to make use of the unregisterListener() method to remove any callbacks being triggered when they are no longer required.
Once we detect that the InstallStatus represents the DOWNLOADED state, we are required to restart the app so that the update can be installed. Whilst the immediate update method handles this for you, in the case of the flexible update we need to manually trigger this. In order to manually trigger this update we need to make use of the completeUpdate() method from our AppUpdateManager instance. When this is called, a full-screen UI will be displayed from the play core library and the app will be restarted in the background so that the update can be installed. The app will then be restarted with the update applied.
When this is called from the background, the app will still be updated but no fullscreen UI will be displayed and the app will not be relaunched once the update has been completed.
However, if the update is being carried out when the app is in the foreground then there is a chance that the user will leave and return to our app before the update has been downloaded and installed. In this case, when our activity hit onResume() we’re going to want to check the status from our AppUpdateManager so that we can determine if we need to complete the update process. We can determine this by checking if the InstallStatus is in a DOWNLOADED state. If so, we can go ahead and call the completeUpdate() method to finish the update process.
From this article we’ve learnt about the new approach to in-app updates that is provided by the play core library. I’m excited to use this in the applications that I work on and I really believe that this will greatly improve a range of experiences for both our users and developers when it comes to android application development. If you have any questions about the play core library or in-app updates then please do reach out.
In my next article i’ll be talking about the CameraX Jetpack library on Android. Follow me on Twitter to keep updated as to when this is released!
Источник
In-App Updates: ускоряем процесс обновления приложения на Android
Среди многообразия инструментов, анонсированных на Android Dev Summit, особое внимание хочется уделить механизму обновления приложения In-App Updates (IAUs), который помогает разработчикам ускорить добавление новых фич, баг-фиксов и улучшений производительности. Поскольку эта функциональность была опубликована после Google I/O 2019, в этой статье я подробно расскажу об IAUs, опишу рекомендованные схемы реализации и приведу некоторые примеры кода. Также я расскажу о нашем опыте интеграции IAUs в Pandao, приложение для заказа товаров из Китая.
Новый API позволяет разработчикам инициировать обновление приложения до последней доступной в Google Play версии. Таким образом IAUs дополняет уже существующий механизм автоматического обновления Google Play. IAUs содержит несколько схем реализации, которые принципиально различаются с точки зрения взаимодействия с пользователем.
- Flexible Flow предлагает пользователям скачать обновление в фоновом режиме и установить в удобное для пользователя время. Он предназначен для случаев, когда пользователи всё ещё могут использовать старую версию, но уже доступна новая.
Immediate Flow требует от пользователей скачать и установить обновление, прежде чем продолжить использование приложения. Он предназначен для случаев, когда для разработчиков критически важно обновить приложение.
Поскольку второй вариант не так важен и меньше подходит для приложения Pandao, разберём подробнее сценарий Flexible Flow.
Интеграция IAUs Flexible Flow
Варианты использования
Процесс обновления с помощью IAUs состоит из нескольких шагов.
- Приложение с помощью библиотеки Play Core, которая проверяет в Google Play, есть ли доступные обновления.
- Если они есть, то приложение просит Google Play показать диалог IAUs. Google Play показывает пользователю диалог с предложением обновиться.
- Если пользователь соглашается, Google Play в фоновом режиме скачивает обновление, показывая пользователю в статус-баре прогресс скачивания.
- Если скачивание завершилось, когда приложение работает в фоновом режиме, Google Play автоматически завершает установку. Если же приложение в этот момент активно, то для таких случаев нужно определять собственную логику завершения установки. Рассмотрим следующие сценарии.
- Приложение запускает процесс установки, показав пользователю диалог Google Play с индикатором прогресса. После завершения установки запускается обновленная версия приложения. В этом случае рекомендуется отобразить дополнительный диалог, который позволит пользователю подтвердить, что он готов сейчас перезапустить приложение. Это рекомендуемая схема реализации.
- Приложение ждёт, пока оно окажется в фоновом режиме, и после этого завершает обновление. С одной стороны, это менее навязчивое поведение с точки зрения UX, так как взаимодействие пользователя с приложением не прерывается. Но с другой — оно требует от разработчика реализовать логику для определения того, находится ли приложение в фоновом режиме.
Если установка скачанного обновления не была завершена, то Google Play может завершить установку в фоновом режиме. Данный вариант лучше не использовать явно, потому что он не гарантирует установки обновления.
Основные требования к тестированию
Чтобы вручную выполнить весь процесс обновления на тестовом устройстве, нужно иметь как минимум две версии приложения с разными номерами сборок: исходная и целевая.
- Исходная версия с более высоким номером должна быть опубликована в Google Play, она будет идентифицирована Google Play как доступное обновление. Целевая версия с более низким номером сборки и интегрированным IAUs должна быть установлена на устройстве, её мы будем обновлять. Суть в том, что когда приложение попросит Google Play проверить наличие обновления, он сравнит номера сборок у установленной и доступной версии. Так что IAUs будет запущено только в том случае, если номер сборки в Google Play выше, чем у текущей версии на устройстве.
- Исходная и целевая версии должны иметь одинаковые имена пакета и должны быть подписаны одинаковым релизным сертификатом.
- Android 5.0 (API level 21) или выше.
- Библиотека Play Core 1.5.0 или выше.
Пример кода
Здесь мы рассмотрим пример кода для использования IAUs Flexible Flow, который также можно найти в официальной документации. Для начала необходимо добавить библиотеку Play Core в build.gradle файл на уровне модуля.
Затем создадим экземпляр AppUpdateManager и добавим функцию обратного вызова к AppUpdateInfo , в которой будет возвращаться информация о доступности обновления, объект для запуска обновления (если оно доступно) и текущий прогресс скачивания, если оно уже началось.
Чтобы показать диалог для запроса обновления из Google Play, необходимо передать полученный объект AppUpdateInfo в метод startIntentSenderForResult .
Для отслеживания состояния обновления можно добавить в менеджер IAUs слушатель событий InstallStateUpdatedListener .
Как только обновление будет скачано (статус DOWNLOADED ), нужно перезапустить приложение, чтобы завершить обновление. Перезапуск можно инициировать с помощью вызова appUpdateManager.completeUpdate() , но перед этим рекомендуется показать диалоговое окно, чтобы пользователь явно подтвердил свою готовность к перезапуску приложения.
Ошибка «Update is Not Available»
Во-первых, перепроверьте соответствие требованиям, перечисленным в разделе «Basic Implementation Requirements». Если вы все выполнили, однако обновление согласно вызову onSuccess , всё же недоступно, то проблема может быть в кэшировании. Вполне вероятно, что приложение Google Play не знает о доступном обновлении из-за внутреннего механизма кэширования. Чтобы избежать этого при ручном тестировании, вы можете принудительно сбросить кэш, зайдя на страницу «Мои приложения и игры» в Google Play. Или можете просто очистить кэш в настройках приложения Google Play. Обратите внимание, что эта проблема возникает только в ходе тестирования, она не должна влиять на конечных пользователей, поскольку у них кэш всё равно обновляется ежедневно.
IAUs Flexible Flow в приложении Pandao
Мы участвовали в программе раннего доступа и интегрировали IAUs Flexible Flow (рекомендованная реализация) в приложение Pandao — платформу, на которой производители и вендоры могут торговать китайскими товарами. Диалог IAUs отображался на главном экране, так что с ним могло взаимодействовать максимальное количество пользователей. Изначально мы хотели показывать диалог не чаще раза в день, чтобы не отвлекать людей от взаимодействия с приложением.
Поскольку A/B-тестирование играет ключевую роль в жизненном цикле любой новой фичи, мы решили оценить эффект от IAUs в нашем приложении. Мы случайным образом разделили пользователей на две непересекающиеся группы. Первая была контрольной, без использования IAUs, а вторая группа была тестовой, этим пользователям мы показывали диалог IAUs.
A/B-тест IAUs Flexible Flow в приложении Pandao.
В течение последних нескольких релизов мы измерили долю активных пользователей каждой версии приложения. Оказалось, что среди активных пользователей с последней доступной на тот момент версией основную часть составляли участники из группы B, то есть с функцией IAU. Фиолетовая линия на графике показывает, что в первые дни после публикации версии 1.29.1 количество активных пользователей с IAUs превысило количество пользователей без этой функции. Поэтому можно утверждать, что пользователи с IAUs быстрее обновляют приложение.
Диалог IAUs Flexible Flow в приложении Pandao.
Согласно нашим данным (см. график выше), пользователи больше всего кликают на кнопку подтверждения в диалоге IAUs в первые дни после релиза, а затем конверсия постоянно снижается вплоть до публикации следующей версии приложения. То же самое наблюдается с кнопкой установки в диалоговом окне, которая инициирует установку скачанного обновления. Следовательно, можно сказать, что среднее значение конверсии в обоих случаях прямо пропорционально частоте релизов. В Pandao средняя конверсия в течение одного месяца достигает 35 % для клика на кнопку подтверждения и 7 % для клика на кнопку установки.
Мы предполагаем, что уменьшение доли подтверждений с течением времени — лишь проблема пользовательского опыта, потому что люди, которым интересна новая версия, будут обновляться довольно быстро, а те, кто не интересуются обновлением, так и не станут интересоваться. Исходя из этого предположения, мы решили не беспокоить тех, кому не интересно обновление, и не спрашивать их каждый день. Хорошей практикой будет использование другой логики запросов, которая основывается на «устаревании», то есть чтобы не беспокоить пользователей, мы оцениваем, насколько старые версии стоят у них и как часто мы уже предлагали им обновиться.
В целом IAUs продемонстрировала хорошие результаты в ходе A/B-тестирования, так что мы раскатили IAUs для всех пользователей.
Источник