31

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.

Psypher
  • 10,717
  • 12
  • 59
  • 83
adeltahir
  • 1,087
  • 2
  • 15
  • 31

2 Answers2

53

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!!

Pranav
  • 808
  • 10
  • 10
11

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();
} 
Sachin Varma
  • 2,175
  • 4
  • 28
  • 39
Rohan Kandwal
  • 9,112
  • 8
  • 74
  • 107