- 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:
- In App Updates API by Google for Android — why and when it’s going to be useful, how to properly implement.
- Things to know before starting
- Overview
- Let’s begin the coding part
- Checking for updates:
- Immediate Update:
- Flexible Update:
- 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.
Источник
In App Updates API by Google for Android — why and when it’s going to be useful, how to properly implement.
In app updates feature is one of the most awaited feature for android developers. Auto update feature in play store is enabled still most of the users aren’t updating to latest versions(they are but it was taking weeks, in some cases months), by then damage might be done for example, for all of us there is a time when we release a version and find out there is an issue which need to be fixed immediately or when you try a new feature in your app but most of the users haven’t updated to that version in weeks, which results in wrong metrics to track weather the feature is success.
Now that we know why to use in app updates API, developers let’s focus on how to do it.
Things to know before starting
Google being Google in 2019 IO released stable version of most useful and very easy to implement API called In App Updates API which is a part of play core library(≥ 1.5.0) and as always it’s backward compatible till Android 5.0 ( API level 21).
Overview
With In App Updates API integrated in your code google provide two types of update requests with materialistic design which seamlessly connect to your app UI.
Flexible: A user experience that provides background download of the update and at the same time no interruption on seamless use of the app. Flexible update is most useful when you integrated a new feature which is not core to your app.
Immediate: This is the flow where a blocking UI is prompted by google until the update is download and installed. Immediate update is most useful when there is bug in the production version.
However Android allows you to handle any of the two update types for every version of your app, so it’s up to you how to handle.
Let’s begin the coding part
Checking for updates:
Before getting started with either of these methods we should first check for an update is available. For that we use AppUpdateManager as show below
As shown in the above peace of code we start by creating an instance for AppUpdateManager class which contains AppUpdateInfo that returns an intent object that we use to check for an update. As we see in the code the object which is returned by AppUpdateInfo contains a method updateAvailability() which returns one the following
- UNKNOWN
- UPDATE_AVAILABLE
- UPDATE_NOT_AVAILABLE
- DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
UPDATE_AVAILABLE: If this is the result then we can proced with step update request.
UPDATE_NOT_AVAILABLE: Your app is update to date, none of the following steps is required.
DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS: The update is already in progress which means you have requested for the update at-least once.
After checking that you are able to update the app, you can request an update using AppUpdateManager.startUpdateFlowForResult() , as shown below. However, you should be mindful how often you request updates to avoid annoying your users.
Requirements for startUpdateFlowForResult():
We need to pass AppUpdateInfo which we previously retrieved from AppUpdateManager , AppUpdateType (IMMEDIATE OR FLEXIBLE), Context of the present component, MY_REQUEST_CODE to monitor result from update request.
Calling this startUpdateFlowForResult() method will trigger a startActivityForResult() call and start the app update flow. In some cases, the request 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 Update:
The purpose of it is explained above and now we deal with logic & coding part
Immediate In-app Updates can be trigged by AppUpdateType.IMMEDIATE as mentioned previously, this will show a materialistic blocking UI by Google during the entire update time means downloading and installing the update.
For this, we begin by launching the app update flow for a IMMEDIATE update:
If the user leaves the app before completion still update will be downloaded and installed in the background meanwhile if the user entered the app then developer should ensure that update is in progress. 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.
This is all we need to do for immediate update, system will take care of the things from here.
Flexible Update:
Flexible In-app Updates can be trigged by AppUpdateType.FLEXIBLE as mentioned previously, 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 while the user can continue to use the application.
For this, we begin by launching the app update flow for a FLEXIBLE update:
As mentioned above this is all happening in the background, a little more monitoring is required during the update.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
With these many options means, more flexibility during the update for example you can allow user to continue interact with the app throught the process and ask user to restart the app to complete the update on receiving DOWNLOADED state or developer can show appropriate UI based on the states in the listener.
To complete the update, when user allow to restart the app we can use the following method, which will complete the update and restart the app.
If the update is 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 learn about the new approach for in app updates through which we don’t need to put much effort.
If you have any difficulty in implementing or anything I have missed in the process, please let me know in the comments below.
If you like my article, please don’t forget to click 👏👏👏 & to recommend it to others 👏👏👏.
Also, to be notified about my next articles and stories, follow me on Medium.
Источник
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 для всех пользователей.
Источник