adeltahir
adeltahir

Reputation: 1097

How to enable deep-linking in WebView on Android app?

I'm trying to implement deep linking in android app.

When I click the deep linking of custom url (xxxx://repost?id=12) on Android browser like Chrome, my app opens up and works very well.

Problem is, in the app, there's a webView widget, and I want to the deep-linking work there too.

Currently, it's showing Can't connect to the server error.

Thanks in advance.

Upvotes: 32

Views: 45197

Answers (2)

Rohan Kandwal
Rohan Kandwal

Reputation: 9326

The answer of @pranav is perfect but might cause crash if there are no apps to handle the intent. @georgianbenetatos's solution to prevent that helps

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
if (intent.resolveActivity(getPackageManager()) != null) {
   startActivity(intent);
} else {
   Toast.makeText(this, R.string.no_apps_to_handle_intent, Toast.LENGTH_SHORT).show();
} 

Upvotes: 12

Pranav
Pranav

Reputation: 826

This is the problem with android web view as this treats everything as URL but other browser like chrome on mobile intercepts the scheme and OS will do the rest to open the corresponding app. To implement this you need to modify your web view shouldOverrideUrlLoading functions as follows:

 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
        LogUtils.info(TAG, "shouldOverrideUrlLoading: " + url);
        Intent intent;

        if (url.contains(AppConstants.DEEP_LINK_PREFIX)) {
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);

            return true;
        } 
 }

In above code replace AppConstants.DEEP_LINK_PREFIX with your url scheme eg.

android-app://your package

Hope this helps!!

Upvotes: 55

Related Questions