- Открытие URL-ссылок с помощью Android-приложения (Deep Links)
- Что такое Deep Links и как интегрировать их в своё приложение
- Как работает открытие ссылок через приложение и зачем оно вообще нужно?
- Разделение на Deep Links и Android App Links
- 1. Deep Links
- 2. Android App Links
- Постановка задачи
- Реализация
- How to Enable Deep Links on Android
- What Are Deep Links?
- Implementing Deep Links
- Testing Deep Links
- Conclusion
- Navigating with Deep Links
- Deep thoughts on deep links… with Navigation component
- Introduction
- Donut Deep Linking
- Implicit
- Explicit
- Summary
- For More Information
Открытие URL-ссылок с помощью Android-приложения (Deep Links)
Что такое Deep Links и как интегрировать их в своё приложение
Apr 28, 2018 · 3 min read
Как работает открытие ссылок через приложение и зачем оно вообще нужно?
Нередко бывает так, что определённому контенту соответствует и страница на сайте, и экран в приложен и и. В таких случаях пользователю, у которого установлено приложение, удобно будет открывать ссылку на этот контент через приложение. Как пример можно взять интернет-магазин. Пользователь может нажать на ссылку в браузере, после чего ему предложит просмотреть страницу товара через приложение. Также это хорошо используется с шарингом ссылок. Пример: Петя увидел классные кроссовки на сайте и скинул ссылку на них Васе в Telegram. У Васи уже установлено приложение интернет-магазина, поэтому он нажав на ссылку в Telegram попадает на экран приложения, в котором отображается вся информация об этих замечательных кроссовках. Удобно, не правда ли?
Разделение на Deep Links и Android App Links
Перед тем, как мы займемся реализацией, важно понять, что есть два способа обработки ссылок:
1. Deep Links
Глубокие ссылки (Deep Links) — это URL, которые направляют пользователя на определённый контент в вашем приложении. Они реализуются созданием интент-фильтра и извлечением информации из входящих интентов. Если на телефоне установлены приложения, которые могут обрабатывать такие же интенты, то пользователю будет предложено несколько приложений на выбор, и он сможет выбрать через какое открыть ссылку.
2. Android App Links
Android App Links доступны только с Android 6.0 (API 23) и позволяют назначать приложение дефолтным обработчиком ссылок определённого типа. Главное отличие от Deep Links заключается в том, что никакое другое приложение кроме вашего не сможет обработать ссылку.
В этой статье будет рассматриваться первый тип ссылок — Deep Links.
Постановка задачи
Давайте на простом и типичном примере посмотрим как можно добавить обработку глубоких ссылок в приложение.
Допустим, у нас есть сайт с вакансиями, на котором каждой вакансии соответствует ссылка вида https://awesomejobs.com/jobs/
Реализация
- Начнем с добавления нового intent-filter в Activity , на которую мы хотим направлять пользователя. Это нужно для того, чтобы система понимала какого вида ссылки мы хотим обрабатывать. В AndroidManifest.xml нужно добавить следующие строки:
- action android.intent.action.VIEW говорит о том, что Activity предназначена для отображения контента.
- category android.intent.category.BROWSABLE требуется для того, чтобы мобильный браузер смог выполнить открытие ссылки из результатов поиска Google. Без этого аттрибута при клике по ссылке в мобильном браузере она будет открываться в самом же браузере.
category android.intent.category.DEFAULT требуется если вы хотите чтобы приложение обрабатывало ссылку с любого ссылающегося сайта. Интент, который используется при переходе из результатов поиска Google знает, что должен открыть именно ваше приложение, поэтому явно указывает на него как на получателя. Ссылки же с других сайтов не знают ничего о вашем приложении, поэтому категория DEFAULT говорит о том, что приложение способно принять неявный Intent от них.
2. Наше приложение научилось ловить интенты извне, теперь нам нужно написать код для того, чтобы перехватывать их, доставать id вакансии и с ним уже делать всё, что нам захочется (запрашивать с сервера информацию о вакансии с таким id и отображать её, например).
Для этого в метод onCreate активити, которую мы использовали в манифесте, добавим следующий код:
Активити запускается интентом, содержащем в себе ссылку. data — это и есть не что иное, как наша ссылка. Получив её и выполнив необходимые проверки, мы вырезаем из неё id вакансии, подтягиваем её детали с сервера и отображаем на экране. Всё предельно просто.
Источник
How to Enable Deep Links on Android
What Are Deep Links?
Android deep links open a specific page within an app and optionally pass data to it. Developers may find deep links particularly useful for actions, such as clicking a notification or sending an app link via email.
Let’s take an email client as an example. When the user clicks the notification of an email she received, it opens a deep link that takes her to the email in the app. Last but not least, deep links also allow Google to index your app and link to specific sections of your app in searches. The deep link appears as a search result in Google and can take the user to a particular section of your app.
Implementing Deep Links
To add a deep link to your app, you must add it to your android manifest file as an intent filter. Take a look at the following example.
In the above example, navigating to either http://www.mydeeplink.com or tutsplus://deeplink takes the user to the LinkActivity activity. The tags specify the properties of the deep link. Notice that you need to create a separate intent filter for each URI scheme and each activity.
You can create multiple links to the same activity. To differentiate these, you need to parse the intent’s data in your code to differentiate the links. This is usually done in the onCreate() method by reading in the data and acting accordingly.
Testing Deep Links
Android Studio makes it very easy to test deep links. Click Run > Edit Configurations to edit the configuration of the project.
Open the General tab at the top and enter the URI in the Deep Link field in the Launch Options section. When you launch your app using Android Studio, it will attempt to open the specified URI.
Conclusion
Now that you know how to create and use deep links, you can open up new entry points for users to interact with your app. Users may use Google search on their phones to find pages within your app and you can create notifications that open a specific page in your app when clicked.
Источник
Navigating with Deep Links
Deep thoughts on deep links… with Navigation component
This is the fourth in a series of articles about the Navigation component API and tool. These articles are based on content that is also explained in video form, as part of the MAD Skills series, so feel free to consume this material in whichever way you prefer (though the code tends to be easier to copy from text than from a video, which is why we offer this version as well).
If you prefer your content in video form, here it is:
Introduction
This episode is on Deep Links, the facility provided by Navigation component for helping the user get to deeper parts of your application from UI outside the application.
Sometimes you want to make it easy for the user to get to a specific part inside the flow of your application, without having to click-click-click from the start screen to get there. For example, maybe you want to surface ongoing conversations in a chat app, or the user’s cart in a shopping application. You can use deep links to do this, surfacing these links outside of the application, in shortcuts and notifications, that allow the user to click from those other locations and get to those deeper parts of your app.
Navigation component simplifies creating these deep links. To show how they work, we’re going to take another look at the Donut Tracker app that I used in previous episodes. The finished code for the app is on GitHub; feel free to download and open it up in Android Studio to follow along.
Since the code is done, I’ll walk you through the steps I went through to make it all work.
Donut Deep Linking
In Donut Tracker, there are a couple of actions that are useful to get to quickly. For example, if I have a really good donut in the wild, I’d like to be able to add that information into the list without having to launch the app first and then click on the FloatingActionButton to bring up the data-entry dialog. Also, if I’ve just added or edited information about a donut, I’d like to post a notification so that I can quickly get back to editing that recent entry.
I added deep links for both of these actions: one for adding a new donut and another for returning to an ongoing edit. The “add” action uses an “implicit” deep link. Implicit is what we call a link that takes you to a static location inside your hierarchy, one that does not change over time. In my app, the implicit deep link will always take you to the form that allows you to add a new donut to the list.
The “continue editing” action uses an “explicit” deep link. Explicit is what we call a link that takes you to dynamic content inside your application.
Implicit
Let’s start with an implicit deep link to add a new donut.
First, I needed to create the deep link, which I did in the navigation editor. Clicking on the dialog destination shows the properties of that destination on the right:
I clicked on the + next to Deep Links. This brought up a dialog in which I entered a URI (Universal Resource Identifier). In this case, I wanted a URI that is specific to the app (not a general web address that might be picked up by the browser app), so I used “myapp” as an identifier that is specific to our app:
Next, I edited the application manifest to inform the application that I wanted a shortcut for the deep link:
In that meta-data block, I told the activity that there is information about the deep link in the navigation graph. I also referenced a new file in the xml resource directory with information about an app shortcut for this activity.
I then created the xml folder and a new shortcuts.xml file in that new directory. In the shortcuts file, I entered information about the app shortcut, including the URI we saw above:
The important part here is that data item, which uses the same URI string as I entered into the deep link dialog in the navigation tool earlier. This is the connecting glue which causes navigation to happen from the app shortcut to the dialog destination.
And that’s all I needed for an implicit deep link: I told it the destination to navigate to, created the shortcut to do that navigation, and I was done. If you run the app, you can see the shortcut by long-pressing on the app icon. Clicking that shortcut will take you to the form to create a new donut item.
That was implicit deep links. Now let’s create an explicit deep link, which will be created dynamically based on the state of the app.
Explicit
If you’re like me, then donuts are really important to you. When I’m entering information about a new donut find, I probably want to take my time with it. So I’ll start the entry with some information, but I may want to come back later and enter more when I’ve really had a chance to appreciate the experience.
This can be done with notifications: when I enter information about a donut, the app creates a notification that makes it easier to get back to that ongoing entry. There’s not a lot of code necessary to do this; I just needed to create a notification with a PendingIntent to get to the right place in the application.
Most of this happens in DonutEntryDialogFragment , in the onClick() listener for the Done button. We’ve seen this click listener code in a previous episode; this is where we add new or updated data to the ViewModel. I just needed to add an extra step here to create the notification. The parts in bold are the code I had to add to deal with the notification.
First, the code creates arg with the donut id to use. This will be used to tell the destination dialog which donut to retrieve that the user will continue editing.
The code then creates pendingIntent for the deep link using an API in NavigationController . The destination is set to be this dialog fragment. The call also sets the argument which holds the ID and create the intent.
Then the code calls Notifer.postNotification() , a utility class/method I created for handling the details of creating and posting the notification.
First, the code creates the notification builder. Note that it needed a channelId to construct the builder, which is created as necessary in the init() function of Notifier (see the code for those details; it’s standard stuff).
I then supplied the necessary data for the notification, set the intent , and built it. Before posting, existing notifications are canceled (I only wanted to be able to edit the latest donut).
Finally, the new notification is posted and… it’s done. Now every new editing operation (whether for a new donut or an existing donut) will surface a notification that the user can click on to get back to that editing action.
Summary
In this episode, I created both an implicit deep link , which takes the user to a static location in the app where they can enter information about a new donut, and an explicit deep link, which allows the user to continue editing an existing donut where they left off.
This Donut Tracker app is getting better and better. Not as good as a donut, of course… but then nothing is.
That’s it for this time. Go grab a donut — you’ve earned it.
For More Information
For more details on Navigation component, check out the guide Get started with the Navigation component on developer.android.com.
To see the finished Donut Tracker app (which contains the code outlined above, but also the code covered in future episodes), check out the GitHub sample.
Finally, to see other content in the MAD Skills series, check out the video playlist in the Android Developers channel on YouTube.
Источник