Добавьте ссылки на приложения Android

Android App Links are HTTP URLs that bring users directly to specific content in your Android app. Android App Links can drive more traffic to your app, help you discover which app content is used most, and make it easier for users to find and share content in an installed app.

Для добавления поддержки ссылок на приложения Android:

  1. Создайте фильтры намерений в вашем манифесте.
  2. Добавьте код в активности вашего приложения для обработки входящих ссылок.
  3. Свяжите свое приложение и свой веб-сайт с сервисом Digital Asset Links.

В Android Studio функция App Links Assistant упрощает этот процесс благодаря пошаговому мастеру, описанному ниже.

Для получения более подробной информации о том, как работают ссылки на приложения и какие преимущества они предоставляют, прочитайте статью «Работа со ссылками на приложения Android» .

Добавить фильтры намерений

The App Links Assistant in Android Studio can help you create intent filters in your manifest and map existing URLs from your website to activities in your app. The App Links Assistant also adds template code in each corresponding activity to handle the intent.

Чтобы добавить фильтры намерений и обработку URL-адресов, выполните следующие действия:

  1. Выберите Инструменты > Помощник по ссылкам на приложения .
  2. Нажмите «Открыть редактор сопоставления URL-адресов» , а затем нажмите «Добавить». В нижней части списка сопоставления URL-адресов добавьте новое сопоставление URL-адресов.
  3. Добавьте подробности для нового сопоставления URL-адресов:

    Помощник по ссылкам в приложениях проведет вас через основные этапы сопоставления URL-адресов.

    Рисунок 1. Добавьте основные сведения о структуре ссылок вашего сайта, чтобы сопоставить URL-адреса с действиями в вашем приложении.

    1. Введите URL-адрес вашего сайта в поле «Хост» .
    2. Добавьте path , pathPrefix или pathPattern для URL-адресов, которые вы хотите сопоставить.

      For example, if you have a recipe-sharing app with all the recipes available in the same activity, and your corresponding website's recipes are all in the same /recipe directory, use pathPrefix and enter /recipe. This way, the URL http://www.recipe-app.com/recipe/grilled-potato-salad maps to the activity you select in the following step.

    3. Выберите вид деятельности, на который должны вести URL-адреса.
    4. Нажмите ОК.

    The URL Mapping Editor window appears. The App Links Assistant adds intent filters based on your URL mapping to the AndroidManifest.xml file and highlights the changes in the Preview field. If you'd like to make any changes, click Open AndroidManifest.xml to edit the intent filter. To learn more, see intent filters for incoming links .

    The main App Links Assistant tool window also displays all existing deep links in the AndroidManifest.xml file and lets you quickly fix any misconfigurations by clicking Fix All Manifest Issues .

    Помощник по связям приложений позволяет исправлять ошибки в настройках манифеста.

    Note: To support future links without updating your app, define a URL mapping that supports URLs that you plan to add. Also, include a URL for your app home screen so it's included in search results.

  4. Чтобы убедиться в правильности сопоставления URL-адресов, введите URL-адрес в поле «Проверить сопоставление URL-адресов» .

    Если все работает правильно, в сообщении об успешном завершении будет указано, что введенный вами URL-адрес соответствует выбранному вами действию.

Обработка входящих ссылок

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

  1. В помощнике по ссылкам на приложения нажмите «Выбрать действие» .
  2. Выберите действие из списка и нажмите «Вставить код» .

App Links Assistant добавляет в ваше приложение код, аналогичный следующему:

Котлин

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ...
    // ATTENTION: This was auto-generated to handle app links.
    val appLinkIntent: Intent = intent
    val appLinkAction: String? = appLinkIntent.action
    val appLinkData: Uri? = appLinkIntent.data
    ...
}

Java

@Override
void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    // ATTENTION: This was auto-generated to handle app links.
    Intent appLinkIntent = getIntent();
    String appLinkAction = appLinkIntent.getAction();
    Uri appLinkData = appLinkIntent.getData();
    ...
}

This code isn't complete on its own. You must now take an action based on the URI in appLinkData , such as displaying the corresponding content. For example, for the recipe-sharing app, your code might look like the following sample:

Котлин

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    ...
    handleIntent(intent)
}

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    handleIntent(intent)
}

private fun handleIntent(intent: Intent) {
    val appLinkAction = intent.action
    val appLinkData: Uri? = intent.data
    if (Intent.ACTION_VIEW == appLinkAction) {
        appLinkData?.lastPathSegment?.also { recipeId ->
            Uri.parse("content://com.recipe_app/recipe/")
                    .buildUpon()
                    .appendPath(recipeId)
                    .build().also { appData ->
                        showRecipe(appData)
                    }
        }
    }
}

Java

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ...
  handleIntent(getIntent());
}

protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  handleIntent(intent);
}

private void handleIntent(Intent intent) {
    String appLinkAction = intent.getAction();
    Uri appLinkData = intent.getData();
    if (Intent.ACTION_VIEW.equals(appLinkAction) && appLinkData != null){
        String recipeId = appLinkData.getLastPathSegment();
        Uri appData = Uri.parse("content://com.recipe_app/recipe/").buildUpon()
            .appendPath(recipeId).build();
        showRecipe(appData);
    }
}

Свяжите свое приложение со своим веб-сайтом

После настройки поддержки URL-адресов для вашего приложения, App Links Assistant сгенерирует файл ссылок на цифровые активы, который вы можете использовать для связывания вашего веб-сайта с вашим приложением .

В качестве альтернативы использованию файла ссылок на цифровые активы вы можете связать свой сайт и приложение в Search Console .

If you're using Play App Signing for your app, then the certificate fingerprint produced by the App Links Assistant usually doesn't match the one on users' devices. In this case, you can find the correct Digital Asset Links JSON snippet for your app in your Play Console developer account under Release > Setup > App signing .

Чтобы связать ваше приложение и веб-сайт с помощью App Links Assistant, нажмите «Открыть генератор файлов ссылок на цифровые активы» в App Links Assistant и выполните следующие действия:

Помощник по ссылкам в приложениях проведет вас через основные этапы сопоставления URL-адресов.

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

  1. Введите домен вашего сайта и идентификатор вашего приложения .
  2. To include support in your Digital Asset Links file for One Tap sign-in , select Support sharing credentials between the app and the website and enter your site's sign-in URL.This adds the following string to your Digital Asset Links file declaring that your app and website share sign-in credentials: delegate_permission/common.get_login_creds .

  3. Укажите параметры подписи или выберите файл хранилища ключей .

    Make sure you select the right release config or keystore file for the release build or the debug config or keystore file for the debug build of your app. If you want to set up your production build, use the release config. If you want to test your build, use the debug config.

  4. Нажмите «Сгенерировать файл ссылок на цифровые активы» .
  5. После того, как Android Studio сгенерирует файл, нажмите «Сохранить файл» , чтобы загрузить его.
  6. Загрузите файл assetlinks.json на свой сайт с правами чтения для всех пользователей по адресу https:// yoursite /.well-known/assetlinks.json .

    Important: The system verifies the Digital Asset Links file via the encrypted HTTPS protocol. Make sure that the assetlinks.json file is accessible over an HTTPS connection, regardless of whether your app's intent filter includes https .

  7. Нажмите «Привязать и проверить» , чтобы убедиться, что вы загрузили правильный файл ссылок на цифровые активы в нужное место.

The App Link Assistant can validate the Digital Assets Links file that should be published on your website. For each domain that's declared in the manifest file, the Assistant parses the file on your website, performs validation checks, and provides a detailed explanation on how to fix any errors.

Узнайте больше о связывании вашего веб-сайта с вашим приложением через файл «Ссылки на цифровые активы» в разделе «Объявление о связывании веб-сайтов» .

Проверьте ссылки вашего Android-приложения.

Чтобы убедиться, что ваши ссылки открывают нужное приложение, выполните следующие шаги:

  1. В помощнике по настройке ссылок на приложения нажмите «Проверить ссылки на приложения» .
  2. Введите URL-адрес, который вы хотите протестировать, в поле URL ; например, http://recipe-app.com/recipe/grilled-potato-salad .
  3. Рисунок 3. Диалоговое окно «Проверка ссылок приложения» , показывающее проверяемый URL-адрес и сообщение об успешном завершении.

  4. Нажмите «Запустить тест» .

If the URL mapping isn't set up properly or doesn't exist, an error message appears under the URL in the Test App Links dialog. Otherwise, Android Studio launches your app in the device or emulator at the specified activity without showing the disambiguation dialog ("app chooser") and shows a success message in the App Link Testing dialog, as shown in figure 3.

Если Android Studio не может запустить приложение, в окне «Выполнить» Android Studio появится сообщение об ошибке.

To test Android App Links through the App Links Assistant, you must have a device connected or a virtual device available running Android 6.0 (API level 23) or higher. For more information, read about how to connect a device or create an AVD .