Android: Redirect to a URL with my custom scheme d

2019-07-19 15:13发布

I guess there are some answers on SOF for such a topic, but still something doesn't work with me. The thing that mattters is that I get a redirect within WebView from some site to a URL kind of "myapp://something". In before, this redirect is made by site's API where the app is already registered to get a URL callback with the scheme mentioned above. Redirect is logged, URL "myapp://something" is confirmed there, but, for example, redirect to http://some.host inside WebView can be led to external browser or (when WebViewClient.shouldOverrideUrlLoading is set to return false) to the same WebView, making it try to open the URL instead of making system send an intent. In both cases mentioned above, a redirect to myapp://something leads to nowhere, although my intent filter for the activity I created for handling it is set up like that:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="myapp" />
</intent-filter>

That's a kind of solution proposed in Android url override doesn't work on redirect and in http://developer.appcelerator.com/question/120393/custom-url-scheme---iphone--android Could someone tell me, is it a bug of WebView with no working redirects or my intent filter is not set up properly?

1条回答
Evening l夕情丶
2楼-- · 2019-07-19 15:45

Okay, I finally got the answer. Someway that's impossible to redirect from WebView to a custom scheme URL. That's why an explicit Intent call should be made, with this custom-schemed URL string as additional data. In code, this looks like that:

WebView.setWebViewClient(new WebViewClient() {

      public boolean shouldOverrideUrlLoading(WebView view, String url) {
      //called for any redirect to stay inside the WebView    

          if (url.contains("myapp")) { //checking the URL for scheme required
                                       //and sending it within an explicit Intent
              Intent myapp_intent = new Intent(Intent.ACTION_VIEW);
              myapp_intent.setData(Uri.parse(url));
              myapp_intent.putExtra("fullurl", url);
              startActivity(myapp_intent);

              return true; //this might be unnecessary because another Activity
                           //start had already been called

          }
          view.loadUrl(url); //handling non-customschemed redirects inside the WebView
          return false; // then it is not handled by default action           
 }

So maybe this is a bug or a feature of WebView, I don't know. But in this case an explicit Intent call is the only thing that works stable and perfectly well.

查看更多
登录 后发表回答