Android url redirect to app

Android-приложения являются отражением сайта или сервиса и зачастую представляют собой сходный функционал в удобной оболочке. Из-за этого становится насущным вопрос навигации между страничкой в вебе и установленным клиентом. Для решения этой проблемы были изобретены диплинки (deeplink). Под катом вас ждёт увлекательная история о том, как мы внедряли их у себя и обрабатывали случай, когда у пользователя ещё не было установлено наше приложение.

Диплинки были придуманы так давно, что сейчас уже сложно представить приложение без них. Сама по себе технология не требует свежего Android API, однако если допиливать App Indexing, то можно столкнуться с тем, что работает оно с API 17.

Вернёмся к диплинкам. Их конфигурация представляет собой набор настроек для intent-filter в манифесте приложения, которые описывают паттерны поддерживаемых ссылок.

После этих нехитрых манипуляций при каждом нажатии на ссылку, удовлетворяющую настройкам фильтра, пользователю предлагается выбор между несколькими приложениями, в том числе и вашим. Далее активити, для которой мы задали intent-filter, получит Intent, содержащий в себе линк. Если достать его методом Intent#getData и распарсить необходимые параметры, то можно направить пользователя сразу в интересующий раздел.

После реализации может возникнуть вполне резонный вопрос: что делать, если у пользователя ещё нет приложения? Ответом будут особые диплинки, которые в этом случае умеют направлять человека в Маркет. При должном усердии такую ссылку можно генерировать самим, но нет никаких гарантий, что она будет работать со всеми браузерами и на всех версиях Android. Сейчас довольно много сервисов, предлагающих решение по крайней мере части этих проблем, например, AppsFlyer с их OneLink или Firebase с DynamicLink. Все они работают примерно одинаково, только DynamicLink использует для обработки диплинков предустановленные сервисы Google.

Сам по себе OneLink ведёт на серверы AppsFlyer; они определяют, с какого устройства пользователь вышел в сеть, и перенаправляют его на соответствующий адрес. Можно задать редиректы для десктопа, Android и iOS. Когда Android-приложение установлено, линк прилетает в него через Intent как обычный диплинк. Когда приложения нет, в работу вступают Google Chrome и Google Play.

Наличие приложения проверяется браузером. У Chrome есть спецификация особого формата ссылок, которые потом конвертируются им в Intent и отправляются в систему. Она предусматривает задание ссылки на Google Play в случае, если приложение не установлено. Подробнее с ней можно ознакомиться тут.

Вообще в Google Play можно передать ссылку на приложение таким образом, чтобы после установки и запуска он прокинул часть её дальше. Это реализуется с помощью query-параметра url и будет выглядеть примерно так:

В этом случае best.memes/jokes попадёт внутрь приложения после его установки в виде диплинка. По умолчанию AppsFlyer работает не так: он предлагает получить ссылку через интерфейс библиотеки. Сам диплинк при этом, видимо, передаётся в приложение через серверы сервиса.

Это очень неудобно, потому что, во-первых, мы не можем понять наверняка, надо ли нам ждать какие-то параметры или пользователь просто тыкнул в иконку и параметров не будет. Во-вторых, мы хотим сразу открывать нужный раздел приложения, без лишних блокировок и ожиданий. AppsFlyer же предлагает открывать главный экран, а когда пришли (и если пришли) параметры, то редиректить. Нас такой подход не устроил, поэтому мы сгенерировали свой url в Google Play с параметром для случая, когда пользователь переходит по диплинку с Android-устройства и у него нет приложения. Его мы задали в Onelink, чтобы получать диплинк в приложении без необходимости дожидаться библиотеку.

OneLink работал отлично, пока мы не попробовали пошарить его в Slack. Дело в том, что он открывает ссылки в своём встроенном браузере через Chrome Custom Tabs. Если коротко, то это вкладка браузера, которая открывается в процессе вашего приложения и может быть кастомизирована, чтобы не выбиваться из общего стиля (подробнее можно почитать тут). В этом случае откроется веб-версия Google Play и диплинк в приложение после установки проброшен не будет. Аналогично браузер ведёт себя, если руками скопировать OneLink в адресную строку и перейти по ссылке. Об этом случае разработчики Chrome писали в Release Notes несколько версий назад. Суть в том, что при таком подходе в браузере не срабатывает редирект в Google Play, когда приложение не установлено, и пользователь остаётся в вебе. Силами OneLink побороть это поведение не удалось, поэтому мы обратились к DynamicLink.

Глубокая интеграция Google Play Services в систему позволяет им оптимизировать проверку наличия целевого приложения на устройстве. Это довольно закрытая экосистема, поэтому досконально разобраться в принципах её работы не удалось, однако всё указывает на то, что Chrome открывает активити с прогрессом, принадлежащую Google Play Services, которая определяет, как ей поступить с диплинком. После этого либо происходит редирект либо в Google Play, либо в приложение. При этом диплинк потом попадает в приложение через Intent, то есть без дополнительных библиотечных костылей.

Субъективно, такой подход функционирует не быстрее, чем OneLink, однако он работает при открытии ссылки в Chrome Custom Tabs, что является существенным преимуществом, потому что их используют многие приложения.

Кроме прочего, Firebase позволяет посмотреть схему работы ссылки и куда редиректится пользователь на каждой платформе в каждом случае. Выглядит это примерно так:

Выводы

OneLink. Целевое приложение установлено OneLink. Целевое приложение НЕ установлено DynamicLink. Целевое приложение установлено DynamicLink. Целевое приложение НЕ установлено
Ссылка открывается системой (ACTION_VIEW) + Пришлось «закостылить», чтобы получать диплинк сразу на старте + +
Ссылка открывается в Chrome Custom Tabs + +
По ссылке нажимают в браузере + Пришлось «закостылить», чтобы получать диплинк сразу на старте + +
Ссылку копируют в адресную строку + +

Из таблицы видно, что в реализации с DynamicLinks всё работает без костылей и во всех интересных нам случаях.

Источник

Redirect URLs for Native Apps

Native applications are clients installed on a device, such as a desktop application or native mobile application. There are a few things to keep in mind when supporting native apps related to security and user experience.

The authorization endpoint normally redirects the user back to the client’s registered redirect URL. Depending on the platform, native apps can either claim a URL pattern, or register a custom URL scheme that will launch the application. For example, an iOS application may register a custom protocol such as myapp:// and then use a redirect_uri of myapp://callback .

Читайте также:  Miui 12 android system webview

App-Claimed https URL Redirection

Some platforms, (Android, and iOS as of iOS 9), allow the app to override specific URL patterns to launch the native application instead of a web browser. For example, an application could register https://app.example.com/auth and whenever the web browser attempts to redirect to that URL, the operating system launches the native app instead.

If the operating system does support claiming URLs, this method should be used. This allows the identity of the native application to be guaranteed by the operating system. If the operating system does not support this, then the app will have to use a custom URL scheme instead.

Custom URL Scheme

Most mobile and desktop operating systems allow apps to register a custom URL scheme that will launch the app when a URL with that scheme is visited from the system browser.

Using this method, the native app starts the OAuth flow as normal, by launching the system browser with the standard authorization code parameters. The only difference is that the redirect URL will be a URL with the app’s custom scheme.

When the authorization server sends the Location header intending to redirect the user to myapp://callback#token=. , the phone will launch the application and the app will be able to resume the authorization process, parsing the access token from the URL and storing it internally.

Custom URL Scheme Namespaces

Since there is no centralized method of registering URL schemes, apps have to do their best to choose URL schemes that won’t conflict with each other.

Your service can help by requiring the URL scheme to follow a certain pattern, and only allow the developer to register a custom scheme that matches that pattern.

For example, Facebook generates a URL scheme for every app based on the app’s client ID. For example, fb00000000:// where the numbers correspond to the app’s client ID. This provides a reasonably sure method of generating globally unique URL schemes, since other apps are unlikely to use a URL scheme with this pattern.

Another option for apps is to use the reverse domain name pattern with a domain that is under the control of the app’s publisher. This is also something that can be enforced by the service.

Want to implement OAuth 2.0 without the hassle?

We’ve built API access management as a service that is secure, scalable, and always on, so you can ship a more secure product, faster.

Источник

App not automatically picking up the redirect to App Link url #527

Comments

MJMortimer commented Apr 2, 2020

I’ve just finished setting up an app and when the pop-up browser redirects back to the https URL that I’ve set up as an App Link my app won’t automatically close the browser and continue onto the next activity.
If I click the context menu in the pop-up browser and select Open in chrome, then the disambiguation menu pops open and I can select my app and then it continues as expected.

It seems to work on an emulated android device, but not when running on my physical device.

Anything I might have missed?

The text was updated successfully, but these errors were encountered:

ferdau commented Apr 9, 2020

Same issue here.

adisazhar123 commented Apr 19, 2020

Same here, it works on an emulator. But once it’s run on a physical device, the app doesn’t close the browser activity. Any insights to why this is happening? I can provide more info if needed.

hnljp commented Apr 19, 2020

the problem is that you do not use your own custom uri scheme. if you use http or https as the uri scheme in the redirect uri, then if people have chosen that http or https uri schemes should always be opened on a specified browser, it will not work for your app anymore.

adisazhar123 commented Apr 26, 2020

@hnljp Can you elaborate further? I have trouble understanding. We’re using HTTPS.

hnljp commented Apr 26, 2020

@hnljp Can you elaborate further? I have trouble understanding. We’re using HTTPS.

Do like the demo app, and use the applicationId as its appAuthRedirectScheme

‘ appAuthRedirectScheme ‘ : ‘ net.openid.appauthdemo ‘

That will limit the possibility for other apps to catch the redirect uri.

So the demoapp is using something like:
net.openid.appauthdemo://[. ]
where you are using:
https://[. ]

iainmcgin commented May 27, 2020

@MJMortimer / @adisazhar123 Can you share your app manifest? In particular, I would like to confirm that the HTTPS URI you are using is correctly registered as an app link for your app. It has been a while since I’ve tested app links with AppAuth, I just want to confirm there has not been some significant change in handling of deep links like @hnljp seems to imply.

gary-archer commented Jun 8, 2020 •

Out of interest I used AppLinks for a recent Kotlin code sample of mine. AppAuth libraries work fine but you need an interstitial page to receive responses, as in Iain’s Advanced Sample. Implementing a complete + reliable solution is pretty tricky.

cpednekar commented Oct 29, 2020 •

the problem is that you do not use your own custom uri scheme. if you use http or https as the uri scheme in the redirect uri, then if people have chosen that http or https uri schemes should always be opened on a specified browser, it will not work for your app anymore.

some oauth2 providers like Shopify for example mandate redirect url to have https or http schemes.
Their portal does not accept any custom scheme at all.
And that’s where it redirects to after auth..

agologan commented Dec 8, 2020

The other contributors have correctly pointed out that for https links to work, you need to correctly define an AppLink otherwise these will be handled by your default browser association.

As @gary-archer suggested it’s also possible to have a hosted service which receives your https redirect and than transforms that request into your custom redirect uri.

Closing this issue as neither reporters have replied since originally posted in April.
Feel free to open a new issue if it still doesn’t work providing an example configuration that we can look at.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

How to Stop Redirects on Android [New Research 2021]

» d=»M24.76888,20.30068a4.94881,4.94881,0,0,1,2.35656-4.15206,5.06566,5.06566,0,0,0-3.99116-2.15768c-1.67924-.17626-3.30719,1.00483-4.1629,1.00483-.87227,0-2.18977-.98733-3.6085-.95814a5.31529,5.31529,0,0,0-4.47292,2.72787c-1.934,3.34842-.49141,8.26947,1.3612,10.97608.9269,1.32535,2.01018,2.8058,3.42763,2.7533,1.38706-.05753,1.9051-.88448,3.5794-.88448,1.65876,0,2.14479.88448,3.591.8511,1.48838-.02416,2.42613-1.33124,3.32051-2.66914a10.962,10.962,0,0,0,1.51842-3.09251A4.78205,4.78205,0,0,1,24.76888,20.30068Z» style=»fill: #fff»>

» d=»M22.03725,12.21089a4.87248,4.87248,0,0,0,1.11452-3.49062,4.95746,4.95746,0,0,0-3.20758,1.65961,4.63634,4.63634,0,0,0-1.14371,3.36139A4.09905,4.09905,0,0,0,22.03725,12.21089Z» style=»fill: #fff»>

No one ever wanted to open that shady web page with a lot of annoying ads. But here it is, against our will, and all thanks to redirects. Only God knows how much traffic we already provided to the worthless websites that only exist to create chaos in people’s browsers. But the danger of redirects spreads far beyond just opening some random pages stuffed with ads, often launching a low-profile malware installation in the background. This is how millions of confiding users get the most dangerous viruses without even noticing, well until the latter eat both their device’s system and their nerves up.

Читайте также:  Windows не удается найти android

All in all, unlawful redirects are some of the most wanted criminals out there in the digital world. Thus, we felt that research on the ways to detect and remove them would do a great deal of help to our readers. So welcome on board if you are down to figure out what’s the best way to stop redirects on an Android phone or tablet.

Redirects: How They Work?

Forced redirects load within an IFrame (Inline Frame) on a web page to then simply click themselves and burst out. This way, instead of accessing the desired content, you get sent away to viewing new pages or interacting with any sort of pop-ups. Mostly, not the good ones, that’s why URL redirection is notorious for the potential harm it brings.

Another major purpose of redirects is to make web pages available under multiple URLs. It’s not rare when firms and individuals register a range of domain names in a batch, specifically the “misspelled” ones. What is that for?

Let’s imagine an “ Example Company ” and its web page called “ example.com ”. The company would want to register all domains that can be accessed by users misspelling the actual name of their firm, including “ exmple.com ”, “ exampl.com ”, and so on. So whenever a user makes a typo and is approaching “exampl.com” the URL redirecting function would send them to the right location — “ example.com ” in our case.

Other purposes of URL redirecting include but not limited to:

  • URL shortening;
  • Prevention of broken links;
  • Device targeting/Geotargeting;
  • Advertising; etc.

Are Redirects Dangerous?

URL forwarding plays a massive role on the Internet as a whole. Without redirecting there would be no web browsing as we know it. But it often becomes a tool for all the possible types of cybercriminals and scammers , and that’s where the danger hides. With the help of redirects, they distribute malware so sneakily that nine out of ten users don’t have any clue that their device is infected. The regretful effects of a malware infection don’t take long to appear, though. Constant redirects to some dubious pages, loads of adverts popping up here and there, unexplainable changes in your home or start page, new apps that you don’t remember installing — these are all main signs of a redirect virus on your Android.

It gets extremely hard to bring the system back to normal when the device’s infection is in a full swing. The choices to eliminate the problem are quite limited, and often require that you give up some of the files or apps, if not to even accept hard reset as a last resort. Therefore, you must prevent virus infection on your device at all costs before it actually occurs. Block redirect ads on Android first, instead of dealing with the consequences, that’s the deal.

How to Prevent Redirects on Android Using AdLock

Nothing can beat intrusive advertising and malicious redirects better than ad blocking software. While ad-blocking solutions present on the market vary in their performance and reliability, we proudly put AdLock forward as the best-in-class ad blocker you can find.

Why AdLock?

Developed by a team of inspired professionals with years of digital privacy experience, AdLock is the ultimate solution for all things anti-ad. Even the most sophisticated advertising technologies and the most advanced adblock detectors bow their heads to AdLock’s performance. With the system-wide protection layer, it is capable of blocking ads in all browsers, apps, messengers, and games on your Android, doing it seamlessly in the background.

If you got enough of disruptions, false redirects, and watching hours of autoplay video ads, simply download AdLock on your Android device and follow the installation instructions below.

You have a chance to try AdLock out completely free for 14 days and experience all the advantages it brings into your digital routine. No one is going to force you into paying until you recognize the value of this product on your own, and if so then welcome to the community!

There are just two little tweaks required to bring your AdLock to the maximum performance once you have downloaded and installed it:

Launch the app, tap the overflow menu at the top right corner and choose “Check updates”. In a new menu tap on “UPDATE ALL”

Switch to the AdLocker tab and enable this filtering feature. In a pop-up window tap OK. You will be then prompted to set a graphic key to verify your ownership for all future actions.

Note, that HTTPS filtering is crucial when dealing with malicious redirects and ads on Android. In the process you will most likely get a warning prompt from Google — they really don’t like users getting out of the advertising trap on their devices using this technology. Disregard the warning, as this is just a formality: AdLock deliberately states that no users’ data will be collected, processed, or sent to any third party. So you can turn on HTTPS filtering without any doubts, otherwise, ad blocking performance would be just average or not possible at worst.

How Do I Stop an App From Redirecting?

Scheme-based mobile app deep linking is one of the basic principles of how Android works. Links associated with the specific app on your phone will be opened in the native app, instead of a web browser like on a desktop. Although this is meant for your convenience, often app redirect rules get messed up and many users look for ways to stay within their web browser loading their desired content. If that’s the case for you, we recommend following these three best ways to stop redirecting to app from your mobile browser:

This is a relatively new feature that lets you use the functionality of a native Android app without actually installing it. Links associated with this app will launch a quick process of opening the “light” app version which, based on our experience, is not always convenient. To opt-out of Instant Apps go into your Settings > Google > Settings for Google Apps > Google Play Instant > switch toggle to OFF .

Services or features are assigned to the specific apps that you’ve installed on your Android. Sometimes, these rules come out of a mistake and cause a lot of headaches to the device owner: a taxi app is set as a default for every navigation purpose, for example. You can set a new vault for each app individually: go to Settings > Apps > Default apps > choose the function and select the necessary app to serve it or Chrome to always stay in the browser.

Читайте также:  Vpn для самсунг андроид

The two steps above can normally solve the false app redirect issues. But if the problem persists, there is a more radical way to remove all the deep linking settings: reset your apps preferences altogether. This won’t affect your apps or data but rather bring the app linking as well as permissions back to the default state — like when you had to assign apps to actions for the first time. Simply go to your Settings > Apps > tap on the three-dots icon on top > Reset app preferences .

How to Stop Redirects in Chrome?

Given that Android users are the ones mainly affected by this problem, Google has introduced a built-in feature that disables redirects in Chrome. Honestly speaking, the performance of this tool is questionable and often is as worthless as the default Chrome ad blocking settings. However, you can still give it a go by editing the Chrome parameters on your Android:

  1. Launch Chrome on your device and tap the three-dot icon on the top right;
  2. Look for Settings in the drop-down menu and scroll down to the Advanced section;
  3. Go to Site Settings and find Pop-ups and redirects ;
  4. Make sure that the toggle next to “ Block sites from showing pop-ups and redirects (recommended) ” is greyed out. If it is blue and says Allowed , make sure to switch the toggle to OFF . While this feature is set as a default in the newest versions of Chrome, it may happen that you need to turn the protection on manually.

So, will it work like voila?

There’s no guarantee that this method would block redirects on an Android device you have. Relying on the built-in Chrome security features is more like playing a lottery. You are free to experiment but what is already clear is that this setting has nothing to do with the potential redirect virus infections on your mobile. In such situations, the browser rules can be easily overturned by the malicious code and the only way to restore the normal order of things would be to perform a device hard reset, particularly when antivirus software did not help.

Searching for more info on the topic, looking for ways to block all ads on Android without a hassle? Look no further, you’ve come to the right place.

How to Block Redirects on Firefox for Android

Firefox is also offering a built-in safe browsing mode on Android devices, but just like in Chrome, its performance is questionable. While safe mode can stop some redirects in your Firefox, this isn’t a 100% reliable solution. Still, this browser is great so if there was a way to tweak it to the safer side, that’d made it just perfect.

AdLock is the solution you might be looking for. Once installed, this powerful ad blocker makes your device bulletproof against malicious attacks, stops redirects in all browsers , as well as makes all of your other apps and games completely safe to use with no ads in sight.

Scan Your Phone for Malicious Software

Viruses can be fatal for your device and your data. So if you start suspecting a malware infection on your Android, it is time to run a check with some quality antivirus program.

There are plenty of good antivirus apps to choose from on Google Play. All you need to do is to pick the one you trust, download and install a client on your mobile, as well as to launch the deep system scan. Once all the files, apps, and games are checked for potential threats, open the scan report and see the result.

Antivirus would move all the compromised files to quarantine automatically, giving you a chance to then take a needed action: whether to delete, clear, ignore the alert, and so on. You can consult the Internet experts, whenever there are doubts, otherwise, just follow the gut feeling about what the scan report says.

Because of the huge variety of antiviruses available on Google Play it might be not easy to pick one that you could trust, especially for the first-timer. Feel free to check out the top three picks from our authors right below in the next section. Note, that we’re neither affiliated nor endorsed by any antivirus developer, and this selection is based only on our personal experience as well as users’ reports available online. If you know a better antivirus solution, please go ahead and share your tip with us in the comment section, we will be there for you to chat.

Avast Mobile Security

Featuring over 100 million installs, Avast Mobile Security is definitely the top choice for those seeking a trustworthy no-nonsense antivirus app for Android. It notifies you about any incoming threats or suspicious requests in real-time, while the virus scan reaches even the darkest corners of your device’s memory letting you choose an action based on the app’s analysis. Avast is the app that won’t go into a complete standby until the next virus threat, as it also serves as a multi-functional tool for all things Android security like:

  • App Lock;
  • Anti-Theft;
  • Photo Vault;
  • VPN;
  • Privacy Permissions;
  • Firewall (for rooted Android only);
  • Wi-Fi speed check, and more.

This antivirus app also has more than 100 million installs worldwide making it one of the most popular mobile apps ever existed, and for a reason. Users trust AVG Mobile antivirus, above all, due to its proven effectiveness against the most common viruses and malware types. But it’s also worth noting, that AVG is extremely easy to use although it has many extra features like:

  • Scheduled scans;
  • Wi-Fi security;
  • Junk cleaner;
  • RAM booster;
  • Photo Vault;
  • Call and SMS blocker;
  • Power saver, and many more.

Norton Mobile Security

For many, Norton was the first antivirus they’ve ever had on their PC. It served well enough for millions of people to gladly install the Norton mobile version on their Androids, and not to be disappointed. As of today, Norton has established itself as a top-notch mobile antivirus with a great detection mechanism for all malicious threats, unique anti-theft features, and some nice extras like:

  • Wi-Fi security;
  • Surveillance App Protection;
  • Safe Search;
  • Call and SMS Blocking;
  • Android System Advisor, etc.

You may decide on using any antivirus from or outside this list but remember, that only in combination with a reliable ad blocker this would eliminate redirects problem for good and all.

Источник

Оцените статью