- Как открыть магазин Google Play непосредственно из моего приложения для Android?
- 18 ответов:
- Как сделать из сайта приложение и выложить его в Google Play за несколько часов. Часть 2/2: Trusted Web Activity
- Android Studio
- Конфигурация приложения и зависимости
- Создание подписанного приложения
- Google Play Console
- Digital Asset Link
- Готово
- Заключение
- Android App Linking
- Web url
- Android
- Features
- Pros and Cons
- App Links
- Android
- Features
- Pros and Cons
- Custom scheme
- Android
- Features
- Pros and Cons
- Intent scheme
- Android
- Features
- Pros and Cons
- App scheme
- Android
- Features
- Pros and Cons
- Firebase Dynamic Links
- Android
- Features
- Pros and Cons
- Play Store url
- Android
- Features
- Pros and Cons
- Market scheme
- Android
- Features
- Pros and Cons
- Referrer Receiver
- Deeplinking
- Deferred deeplink
- Url redirections
- Adb Activity Manager
Как открыть магазин Google Play непосредственно из моего приложения для Android?
Я открыл магазин google play, используя следующий код
но он показывает мне полное представление действий, чтобы выбрать опцию (браузер / play store). Мне нужно открыть приложение в playstore напрямую.
18 ответов:
мы использовать try/catch блок здесь, потому что Exception будет брошен, если Play Store не установлен на целевом устройстве.
Примечание: любое приложение может зарегистрироваться как способный обрабатывать market://details?id= Uri, если вы хотите специально ориентироваться на Google Play, проверьте Berťák ответ
многие ответы здесь предлагают использовать Uri.parse(«market://details?id=» + appPackageName)) чтобы открыть Google Play, но я думаю, что это недостаточно по сути:
некоторые сторонние приложения могут использовать свои собственные фильтры намерений с «market://» схема определена, таким образом, они могут обрабатывать поставляемый Uri вместо Google Play (я испытал эту ситуацию, например, с приложением SnapPea). Вопрос в том, » как открыть магазин Google Play?»поэтому я предполагаю, что вы не хотите открывать никаких других приложение. Обратите также внимание, что, например, рейтинг приложения имеет значение только в приложении GP Store и т. д.
чтобы открыть Google Play и только Google Play я использую этот метод:
дело в том, что когда больше приложений рядом с Google Play может открыть наше намерение, диалог выбора приложения пропускается и приложение GP запускается напрямую.
обновление: Иногда кажется, что он открывает только приложение GP, не открывая профиль приложения. Как Треворвили предложил в своем комментарии Intent.FLAG_ACTIVITY_CLEAR_TOP может решить проблему. (Я сам еще не проверял. )
посмотреть ответ для понимания того, что Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED делает.
перейдите по официальной ссылке разработчика Android в качестве учебника шаг за шагом см. и получил код для вашего пакета приложений из play store, если он существует или приложения play store не существует, а затем откройте приложение из веб-браузера.
официальная ссылка для разработчиков Android
ссылка на страницу приложения
С веб-сайта: http://play.google.com/store/apps/details?id=
из приложения для Android: market://details?id=
ссылка на список продуктов
из приложения для Android: market://search?q=pub:
ссылка на результат поиска
Источник
Как сделать из сайта приложение и выложить его в Google Play за несколько часов. Часть 2/2: Trusted Web Activity
В первой части мы превратили наш сайт в Progressive Web App. Там же было сказано, что совсем недавно, 6 февраля 2019 года, Google предоставили простую возможность выкладывать PWA в Google Play при помощи Trusted Web Activity. Всё, что нужно сделать, это написать небольшую обёртку под Android, которую можно будет выложить в Google Play. Когда пользователь скачает такое приложение-обёртку, оно просто будет открывать наше PWA внутри Chrome. Конечно же, интерфейс Chrome будет спрятан и всё будет выглядеть красиво.
Если вы, как и я, никогда не писали приложений под Android, то дальнейшее вам тоже должно показаться чередой магических манипуляций. Но к чему только не прибегнешь, чтобы выложить своё приложение. Поехали!
Android Studio
Для начала скачиваем впервые в жизни Android Studio. Создаём новый проект и при этом выбираем «Add No Activity».
Далее конфигурируем свой проект:
Для Package name рекомендуется формировать название следующим образом: стартовая страница skorochtec.ru/app превращается в ru.skorochtec.app.
Конфигурация приложения и зависимости
Созданный проект имеет следующую структуру:
Нам нужно будет изменить AndroidManifest.xml, styles.xml (папка res/values) и оба файла build.gradle.
Также рекомендую в папках res/drawable и res/mipmap задать иконку приложения, иначе у вашего приложения будет стандартная иконка Android.
Некогда объяснять, просто скопируйте это себе 🙂
А вот тут нужно дать некоторые пояснения:
- versionCode необходимо будет менять при каждой новой сборке, а вот versionName менять необязательно;
- defaultUrl соответствует start_url из Web App Manifest;
- в assetStatements должен быть именно базовый url («skorochtec.ru» в моём случае);
- вся магия обеспечивается подключением custom-tabs в последней строке, используйте именно эту версию, так как она на 100% проходит тестирование в Google Play.
AndroidManifest.xml
Скопируйте это, поменяв package в теге (в самом верху).
Создание подписанного приложения
Всё готово к тому, чтобы выпустить приложение. Но его ещё нужно подписать. Для этого находим в панели инструментов build -> Generate Signed Boundle / APK… Выбираем APK:
Жмём Create new…
Создаём новое хранилище ключей и сам ключ в нём:
И наконец собираем и подписываем приложение:
Ура! Наш APK готов к выпуску!
Google Play Console
Чтобы выложить приложение, у вас должен быть аккаунт разработчика, который стоит $25. После покупки у вас появится доступ в Google Play Console. В ней несложно разобраться, но уточню один момент. На этапе загрузки вашего APK в консоль разработчика, вы увидите следующее:
Google как бы намекает, что мы криворукие и скорее всего потеряем свой ключ подписи, а значит не сможем потом обновлять приложение. А потому нам предлагают, чтобы мы подписывали наш APK, а вот конечное приложение уже подписывалось самим Google-ом. Рекомендую принять это условие.
Digital Asset Link
Не заметили ничего подозрительного в предыдущих действиях? Для создания приложения мы по сути использовали только адрес нашего сайта… Тогда что нам мешает прямо сейчас выпустить приложение, например, Twitter?
А мешает Digital Asset Link, который мы должны разместить на своём сайте, чтобы доказать, что у приложения и сайта один владелец (на основании ключа подписи приложения).
Делается это очень легко: находите в Google Play Console, Управление релизом -> Подписи приложений. Там будет сертификат для подписи приложений, сгенерированный Google (если вы последовали моей рекомендации и приняли условие). Вам нужно скопировать Цифровой отпечаток сертификата SHA-256.
И вставить его в digital asset links tool. А сгенерированное им положить в файл assetlinks.json, который должен быть доступен на сервере вашего сайта по пути .well-known/assetlinks.json.
Готово
Вот и всё! Выпускаем наше приложение, ждём несколько часов, пока Google его одобрит и, в конце концов, наслаждаемся его присутствием в Google Play Market!
Кстати, красивые картиночки экранов можно сделать в https://apptoolkit.io/.
Заключение
Что ж, мы прошли полный путь от сайта до приложения, он был не очень лёгким, но и не очень сложным. Технологии PWA и TWA ещё очень молодые и имеют ряд недостатков. Например, выпущенное таким образом приложение не откроется у пользователя, если Google Chrome версии 72+ не является браузером по умолчанию на его смартфоне. Так что готовьтесь пожертвовать частью пользователей ради скорости выпуска.
В App Store выложить приложение таким образом пока нельзя. Ну и в целом Apple отстаёт в плане поддержки этих технологий (надеемся, что не намеренно). Но область Progressive Web App быстро развивается и улучшается, поэтому можно надеяться, что в скором времени все мобильные браузеры станут её поддерживать, а существующие недочёты будут исправлены.
Как бы то ни было, я верю, что будущее за Progressive Web App и призываю вас становиться ранними последователями этой технологии. Благо инструкция для этого у вас теперь есть.
Источник
Android App Linking
The ultimate developer guide to Android application linking methods
The main objectives of this guide are to explore the most common deeplinking methods available on Android and evaluate their pros and cons.
The source code of the AppLinks Android app is available on the corresponding GitHub repository.
Method | Link | App not installed | Offline | Referrer | Deeplink | Deferred deeplink |
---|---|---|---|---|---|---|
Web url | Test | ❌ | ✔️ | ❌ | ✔️ | ❌ |
App Links | Test | ❌ | ✔️ | ❌ | ✔️ | ❌ |
Custom scheme | Test | ❌ | ✔️ | ❌ | ✔️ | ❌ |
Intent scheme | Test | ✔️ | ✔️ | ✔️ | ✔️ | ❌ |
App scheme | Test | ✔️ | ✔️ | ✔️ | ✔️ | ❌ |
Firebase Dynamic Links | Test | ✔️ | ❌ | ❌ | ✔️ | ✔️ |
Play Store url | Test | ✔️ | ✔️ | ✔️ | ❌ | ✔️ |
Market scheme | Test | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Web url
http://smarquis.fr/action?key=value#data
Android
Uri | Value |
---|---|
scheme | http |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ❌ |
Offline | ✔️ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Initial disambiguation dialog
- Doesn’t work on the same domain
- Some (in-app) browsers might directly handle these links and prevent the app to launch
App Links
https://smarquis.fr/action?key=value#data
A JSON verification file needs to be available at https://smarquis.fr/.well-known/assetlinks.json containing the application’s package name and keystore fingerprint
To test an existing statement file, you can use the official Statement List Generator and Tester tool.
During app install/update, an Android service will verify if the App Links configuration complies with the server side assetlinks.json file.
The results will be sent to logcat, with these tags: IntentFilterIntentSvc and SingleHostAsyncVerifier
Click to see logcat content
Valid App Links configuration
Invalid App Links configuration (missing or malformed assetlinks.json file, missing package_name or sha256_cert_fingerprints )
Android
Same as Web url but with https only and android:autoVerify=»true» attribute.
Uri | Value |
---|---|
scheme | https |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ❌ |
Offline | ✔️ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- No more disambiguation dialog
- No potential app hijacking
- Doesn’t work on the same domain
- Some (in-app) browsers might directly handle these links and prevent the app to launch
Custom scheme
link://smarquis.fr/action?key=value#data
Android
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ❌ |
Offline | ✔️ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Some browser doesn’t handle non-http links
Intent scheme
intent://smarquis.fr/action?key=value#data#Intent;scheme=link;package=fr.smarquis.applinks;S.key=value;S.market_referrer=my%20referrer%20data;end
Extra parameters can be added to the link and will be transfered as extras Bundle in the Intent :
- String: S.key=value
- Boolean: B.key=value
- Integer: i.key=value
- Long: l.key=value
- Float: f.key=value
- S.browser_fallback_url is the fallback URL if the corresponding link doesn’t work of if app isn’t available (will be removed from the Intent ).
- S.market_referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the parseUri() method from the Android source code.
The new url will be link://smarquis.fr/action?key=value#data
And will contain additional parameters in the Intent .
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Extra | Value |
---|---|
key | value |
market_referrer | my referrer data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Some browser doesn’t handle non-http links
App scheme
android-app://fr.smarquis.applinks/https/smarquis.fr/action?key=value#data#Intent;S.key=value;S.market_referrer=my%20referrer%20data;end
Extra parameters can be added to the link and will be transfered as extras Bundle in the Intent :
- String: S.key=value
- Boolean: B.key=value
- Integer: i.key=value
- Long: l.key=value
- Float: f.key=value
- S.market_referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the parseUri() method from the Android source code.
The new url will be https://smarquis.fr/action?key=value#data
And will contain additional parameters in the Intent .
Uri | Value |
---|---|
scheme | https |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Extra | Value |
---|---|
key | value |
market_referrer | my referrer data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ✔️ |
Deferred deeplink | ❌ |
Pros and Cons
- Some browser doesn’t handle non-http links
Firebase Dynamic Links
https://mr7f2.app.goo.gl/Tbeh
Create the link from the Firebase console.
Android
Same requirements as App Links.
And add the Firebase Dynamic Links dependency in the app-level build.gradle file:
Then in your Activity ‘s onCreate method, use this code to get the link if the user came from a Firebase Dynamic Link:
Uri | Value |
---|---|
scheme | https |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ❌ |
Referrer | ❌ |
Deeplink | ✔️ |
Deferred deeplink | ✔️ |
Pros and Cons
- Ugly progress dialog when fetching link data
Play Store url
https://play.google.com/store/apps/details?id=fr.smarquis.applinks&url=link%3A%2F%2Fsmarquis.fr%2Faction%3Fkey%3Dvalue%23data&referrer=my%20referrer%20data
Very similar to the Market scheme.
This url contains additional query parameters that will be handled by the Play Store app:
- url is the forwarded url
- referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the Play Store to link://smarquis.fr/action?key=value#data
Uri available in deferred deeplink only
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ❌ |
Deferred deeplink | ✔️ |
Pros and Cons
- Some (in-app) browsers might directly handle these links and prevent the Play Store app to launch
- When app is installed, it still opens the Play Store app and completely ignores the deeplink
- Changes the «Open» button in Play Store to «Continue»
- Triggers a notification with «Tap to continue»
Market scheme
market://details?id=fr.smarquis.applinks&url=link%3A%2F%2Fsmarquis.fr%2Faction%3Fkey%3Dvalue%23data&referrer=my%20referrer%20data
This url contains additional query parameters that will be handled by the Play Store app:
- url is the forwarded url
- referrer will trigger a com.android.vending.INSTALL_REFERRER Broadcast once the app is installed.
Android
The url will be rewritten by the Play Store to link://smarquis.fr/action?key=value#data
Uri | Value |
---|---|
scheme | link |
host | smarquis.fr |
path | /action |
query | ?key=value |
fragment | data |
Referrer |
---|
my referrer data |
Features
Feature | ✔️ / ❌ |
---|---|
App not installed | ✔️ |
Offline | ✔️ |
Referrer | ✔️ |
Deeplink | ✔️ |
Deferred deeplink | ✔️ |
Pros and Cons
- Changes the «Open» button in Play Store to «Continue»
- Triggers a notification with «Tap to continue»
Referrer Receiver
Add the Broadcast Receiver in AndroidManifest.xml
And in the Receiver’s onReceive() method, you can get the referrer value
Deeplinking
You can get the deeplink Uri in your Activity ‘s onCreate() method as well as the corresponding properties:
Deferred deeplink
When using Play Store url or Market scheme or Firebase Dynamic Links methods, the regular Play Store Open button will be replaced by a Continue button.
Furthermore, a notification will be displayed with Tap to continue content.
These two actions are essential to the Deferred deeplink method as they provide the initial data to the app.
Regular Deeplink | Deferred Deeplink |
---|
Url redirections
Adb Activity Manager
To try links with adb, use the Activity Manager (am) command:
Источник