I have two Applications with two web-views (a web-view in each). to simply explain my requirement with an example consider a user adds few items in his shopping trolley in first web-view in first app and then he press checkout and this will launched second web-view (which is in second app), result : he needs to see same shopping cart (in second web-view too).
I know sharing cookies between two webviews in a single app is not a problem and it is done in background by Android (CookieManager) however my case is different, I need to achieve the same in two different App.
Perhaps what I am looking for is how to share cookies/ session cookies between two webviews in different apps?
Note: I am restricted to targeted API 18
What I tried so far (apart of lots of useless reading) is :
getting cookie of the URL from the first webview and send it through
intent to second APP's activity
mWebView.setWebChromeClient(new WebChromeClient() {
});
mWebView.loadUrl(getPreferedURL().toString());
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!url.contains("openCheckoutPage")) {
return false;
} else {
mCookie = CookieManager.getInstance().getCookieurl);
Intent fullScreenIntent = new Intent("com.bastami1982.webview.app.WebviewPanel_ACTION");
fullScreenIntent.putExtra("mUrl", mUrl);
fullScreenIntent.putExtra("mCookie", mCookie);
startActivity(fullScreenIntent);
return true;
}
}
});
set the cookie in second app webview
private void loadFullWebview() {
mLink = getIntent().getStringExtra("mUrl");
mLinkCookie = getIntent().getStringExtra("mCookie");
mFullScreenWebView = (WebView) findViewById(R.id.webView);
mFullScreenWebView.setWebChromeClient(new WebChromeClient() {
});
WebSettings settings = mFullScreenWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
if (mLinkCookie!=null) {
mCoockieManager.setAcceptCookie(true);
mCoockieManager.setCookie(mLink, mLinkCookie);
mCoockieManager.acceptCookie();
CookieSyncManager.getInstance().sync();
}
mFullScreenWebView.loadUrl(mLink);
mFullScreenWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
}
I can confirm that I will get the cookie in second app but it seems webview is not using the cookie because the shopping cart is still empty.
I hope I explained it good enough to have some feedback , having said that please ask me for more info if it is needed
I checked the logcat in second App and I think this means that items in trolley can not be find (getItem) (I used Argos.co.uk) to test their shopping Trolley in another word I think cookie is not attached to the url correctly at loading ?! just guessing...
12-18 16:18:11.754 14675-14675 I/Web Console: Error while sending custom tracking data at https://d1af033869koo7.cloudfront.net/psp/argos-v1-001/default/20151216103020/pxfwk.gz.js:7
12-18 16:18:11.904 14675-14675 E/Web Console: Uncaught TypeError: Cannot call method 'getItem' of null at https://argospsp.px.247inc.net/pspxd.html#parentdomain=https://www.argos.co.uk&clientkey=argos-v1-001&version=20151216103020&pspv=default&n=1&caller=refloaded&l=1000&s=cookie:5
Try this...
private void loadFullWebview() {
mLink = getIntent().getStringExtra("mUrl");
mLinkCookie = getIntent().getStringExtra("mCookie");
mFullScreenWebView = (WebView) findViewById(R.id.webView);
WebSettings settings = mFullScreenWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
if (mLinkCookie!=null) {
mCoockieManager.removeSessionCookie();
CookieSyncManager.createInstance(this);
mCoockieManager.acceptThirdPartyCookies(mFullScreenWebView,true);
mCoockieManager.setAcceptCookie(true);
mCoockieManager.setCookie(mLink, mLinkCookie);
CookieSyncManager.getInstance().sync();
}
mFullScreenWebView.loadUrl(mLink);
mFullScreenWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
}
It's been a while since this was asked, but I just had to do something similar (for different reasons)...
What worked for me was to create a service to share the values between the apps.
In my particular case, it was for mobile devices that were managed - so we controlled what is installed on the devices. Since we controlled things, I created a separate app install to have a service which was independent from both of the apps that each had an embedded webview.
The webviews would push cookies to the service when they were updated via monitoring the webview's page loads and querying for cookies at that point. They would load cookies up from the service when the app was foregrounded so they would get anything that had been set while they were backgrounded and the other app was active - and those cookies were added to the webview via the CookieManager.
In the case where there is a family of apps on the PlayStore, it could be done similarly, but there would need to be a service in each app for the other app to connect to and listen from.... If there are more than 2 apps, it could get kind of complex - so might need some creative patterns to handle pulling from all the apps when foregrounded, and keeping track of timestamps to sort out which ones were more recently saved so they overwrite the others....
Or, if one app will always be present, it can be the "main" app that contains the "service", and things will work exactly as what I've done.
Sorry no code here, figured I'd share the approach in case anyone else needs the idea.
I realized from working today that there's an easier way to do this, so answer has been edited to give the most complete answer I could.
Granted, this is Xamarin.Android, but it should work the same for Android Java (maybe kotlin too?):
I recommend doing the cookie getting in OnPageFinished override, but you could theoretically do it anywhere you have an Android.Webkit.CookieManager.Instance context. The reason I recommmend doing it in OnPageFinished() is because you should have the full set of cookies after your page loads.
Set your WebView to use a customized WebViewClient as such, which will allow you to override the OnPageFinished() method, thus getting the cookies at just the right time. If you don't want this overhead after you've got the cookies then you can always switch the WebViewClient or WebView to a vanilla unmodified WebViewClient.
Here's setting this client (optional)
FragmentContainerLayout = inflater.Inflate(Resource.Layout.Tab0FragLayout, container, false); }
Wv = FragmentContainerLayout.FindViewById<WebView>(Resource.Id.webView1);
Wv.SetWebViewClient(new LoginWebViewClient());
and here's getting the cookie from
APP SENDING COOKIE:
public class LoginWebViewClient : WebViewClient
{
public override void OnPageFinished(WebView view, string url)
{
RunPageCommands(view);
base.OnPageFinished(view, url);
}
public static void RunPageCommands(WebView w)
{
try
{
//replace this with yourDomain
string exampleDomain = "https://www." + "example.com"+ #"/"; //or .net or .tv etc
// get the cookie header in context
string cookieHeader = Android.Webkit.CookieManager.Instance.GetCookie(exampleDomain);
}
catch { return; /*cookie getting failed, nothing to do*/ }
ShareCookieWithAnotherApp(cookieHeader, exampleDomain);
}
}
if you don't need to get the cookie every time then you would not want to use an extended WebViewClient after you've got the cookie .. as it will slow down your app. You can alternatively just get the cookie header anywhere in the app with the CookieManager and pass it as an argument to any
You can reset the WebViewClient to the stock one by nulling it out WebView.SetWebViewClient(null) then set it back to the unextended version
then, in the context of an Activity, do something like this, which creates an Intent for another app to respond, and be careful here if your cookie has security tokens in it.
App SENDING cookie:
public void ShareCookieWithAnotherApp(string cookie, string domain){
Intent intent = new Intent();
intent.SetClassName("com.appstore", "com.appstore.MyBroadcastReceiver");
intent.SetAction("com.appstore.MyBroadcastReceiver");
intent.PutExtra("CookieSyncExtra", cookie);
intent.PutExtra("CookieDomainExtra", domain);
SendBroadcast(intent);
}
in the app receiving cookie, extend broadcast receiver:
public class MyBroadcastReceiver : BroadcastReceiver {
//this fires when it receives the broadcast from the sending app
public override void OnReceive(Context context, Intent intent) {
// set the CM to accept cookies
CookieManager.Instance.SetAcceptCookie(true);
//and set the cookie from your extras
CookieManager.Instance.SetCookie(intent.GetStringExtra("CookieDomainExtra"), intent.GetStringExtra("CookieSyncExtra"));
}
}
Manifest (receiving app), set the intent-filter :
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="first_app_packagename" />
</intent-filter>
</receiver>
and in your Activity of the receiving app:
//OnCreate
MyBroadcastReceiver MyReceiver = new MyBroadcastReceiver();
//I put this OnResume() but you can experiment with different placements
RegisterReceiver(MyReceiver , new IntentFilter("first_app_packagename"));
then you can use the WebView.LoadUrl(string url) after you've SetCookie in the receiving app
you can also attach the cookie header manually using the Dictionary<string, string> overload
Dictionary<string, string> cookieHeaderDictionary = new Dictionary<string, string>();
cookieHeaderDictionary.Add("Cookie", cookieString);
LoadUrl(url, cookieHeaderDictionary);
source: How to send data between one application to other application in android?
Related
The problem is rather simple.
In the application we want to keep track of the current url being displayed. For that we use shouldOverrideUrlLoading callback from the WebViewClient by saving the url into a class field for every update. Here is the relevant code:
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mCurrentUrl = url;
// If we don't return false then any redirect (like redirecting to the mobile
// version of the page) or any link click will open the web browser (like an
// implicit intent).
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
...
}
});
mWebView.loadUrl(mInitialUrl);
However, there is at least one scenario, where the callback never gets triggered and the mCurrentUrl field doesnt get updated.
The url: https://m.pandora.net/es-es/products/bracelets/556000
Last updated url (shouldOverrideUrlLoading never gets called when clicking the product): https://m.pandora.net/es-es/products/bracelets
I have tried with callbacks like onPageStarted(), but the url also gets filtered and there doesn't seem to be an accessible one upstream since its protected code.
Reading android documentation about WebView I found this:
https://developer.android.com/guide/webapps/migrating.html#URLs
The new WebView applies additional restrictions when requesting resources and resolving links that use a custom URL scheme. For example, if you implement callbacks such as shouldOverrideUrlLoading() or shouldInterceptRequest(), then WebView invokes them only for valid URLs.
But still doesnt make sense since the above url is generic and should meet the standard.
Any alternative or solution to this?
When you click a product on that web page, it loads the new content in with JavaScript and updates the visible URL in the address bar using the HTML5 History APIs.
From the above MDN article:
This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
These are sometimes called single-page applications. Since the actual loaded page doesn’t change, the WebView callback for page loads isn’t called.
In case you know precisely what kind of HTTP request you want to intercept, you could use the shouldInterceptRequest callback that gets called for each request. It’s likely that the web application loads some data from an API, for example when a product is shown, which you could then detect.
If detecting this isn’t possible, but you’re in control of the web application, you could use the Android JavaScript interface to invoke methods within the Android application directly from the web page.
If you’re not in control of the loaded page, you could still try to inject a local JavaScript file into the web page and observe when the history APIs are used, then call methods in your Android application over the JS interface. I tried observing these events in Chrome with the method described in the previous link and it seems to work fine.
Maybe this helps someone, although the signature in the question is correct, but Android Studio suggests the following method signature:
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
which then never called. It took me a while to notice that the right signature is:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Sorry if this not 100% fit the question, but I believe this may help someone in the same situation. It's not always easy to notice that the second parameter is different.
Please omit mWebView.getSettings().setDomStorageEnabled(true);
Then again try, if a new url found then will invoke shouldOverrideUrl()
I had the same problem like you, and I've finished with extending of WebViewChromeClient with listening for callback to
public void onReceivedTitle(WebView view, String title)
mWebView.setWebChromeClient(mSWWebChromeClient);
private WebChromeClient mSWWebChromeClient = new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (!view.getUrl().equals(mCurrentUrl)) {
mCurrentUrl = view.getUrl();
//make something
}
}
};
For me the problem was below line -
mWebView.getSettings().setSupportMultipleWindows(true);
After removing it shouldOverrideUrlLoading was being called.
after stumbling on this problem and searching for solutions, I've found the one that worked perfectly for me
https://stackoverflow.com/a/56395424/10506087
override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
// your code here
super.doUpdateVisitedHistory(view, url, isReload)
}
Another approach you can try: Catch the url by javascript side. Initialize your webView with this:
webView.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
After page is completely loaded (You can use an algorithm to check this like this https://stackoverflow.com/a/6199854/4198633), then:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("(function() {return window.location.href;})", new ValueCallback<String>() {
#Override
public void onReceiveValue(String url) {
//do your scheme with variable "url"
}
});
} else {
webView.loadUrl("javascript:Android.getURL(window.location.href);");
}
And declare your WebAppInterface:
public class WebAppInterface {
Activity mContext;
public WebAppInterface(Activity c) {
mContext = c;
}
#JavascriptInterface
public void getURL(final String url) {
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//do your scheme with variable "url" in UIThread side. Over here you can call any method inside your activity/fragment
}
});
}
}
You can do something like that to get url, or anything else inside the page.
Add
webView.getSetting().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
then shouldOverrideUrl will be triggered.
onProgressChanged is always triggered when reloading, loading new page with userclick or XmlHttpRequest.
Compare the URL of previous load and the current load, you'll know it's reloading or loading a new page. This works perfect in my single page Web App.
First declare a global variable to store last URL.
String strLastUrl = null;
Then override onProgressChanged(WebView view, int progress)
mWebView.setWebChromeClient(new MyWebChromeClient(){
#Override
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
//A fully loaded url will come here
String StrNewUrl = view.getUrl();
if(TextUtils.equals(StrNewUrl,strLastUrl)){
//same page was reloaded, not doing anything
}else{
//a new page was loaded,write this new url to variable
strLastUrl = StrNewUrl;
//do your work here
Log.d("TAG", "A new page or xhr loaded, the new url is : " + strLastUrl);
}
}
super.onProgressChanged(view, progress);
}
});
I've also tried above solutions, but most of them have issue in my case:
doUpdateVisitedHistory sometimes can not return correct url after "#" made by XmlHttpRequest.
My case is a single page web App. The web App uses javascript with
xhr to display new page when user click an item. For example, user is
currently at http://example.com/myapp/index.php , after clicking, the
browser url becomes
http://example.com/myapp/index.php#/myapp/query.php?info=1, but in
this case, doUpdateVisitedHistory returns
http://example.com/myapp//myapp/
onReceivedTitle doesn't work in my case because the response retrieved by XMLHttpRequest does not have <title></title> tag.
The JavascriptInterface method also works, but I'm afraid it will cause
security related issues with javascript.
public class AndroidMobileAppSampleActivity extends Activity {
/** Called when the activity is first created. */
String mCurrentUrl="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView mWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyCustomWebViewClient());
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.loadUrl("https://m.pandora.net/es-es/products/bracelets/556000");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mCurrentUrl = url;
Log.i("mCurrentUrl",""+mCurrentUrl);
view.loadUrl(url);
return true;
}
}
}
try this one...
Scenario
I have a WebView in my Android app which contains a Soundcloud embed (from Embedly). This embed has two buttons: "Play on Soundcloud" and "Listen in browser".
The "Play on Soundcloud" button contains a URL in format intent://tracks:257659076#Intent;scheme=soundcloud;package=com.soundcloud.android;end
Code
My WebView uses a custom WebViewClient (because I need to intercept some URLs for some different stuff).
protected class WebViewClient extends android.webkit.WebViewClient {
public WebViewClient() { }
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
PackageManager packageManager = context.getPackageManager();
// Create an Intent from the URL.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// Find out if I have any activities which will handle the URL.
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
// If we have an app installed that can handle the URL, then use it.
if (resolveInfoList != null && resolveInfoList.size() > 0) {
Intent viewUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(viewUrlIntent);
}
else {
// Do something else.
}
return true;
}
}
Problem
Clicking "Listen in browser" plays the track in the embed itself and works fine. Clicking "Play on Soundcloud" will call into shouldOverrideUrlLoading in the WebViewClient above (as expected). However, my code to find a activity can't find anything that can deal with this Soundcloud URL.
If I don't set my WebViewClient on the WebView (so it just does its own thing), the "Play on Soundcloud" button will work as expected and launch the Soundcloud app.
Temporary (crap) solution
I've managed to make this do what I want it to do by parsing the URL to get the track ID, then building a new URL using a format that Soundcloud definitely accepts (thanks to this SO post). A URL in the format "soundcloud://tracks:[TRACK_ID]" will be accepted by the Soundcloud app.
But WHY?
Either I am doing the whole "find out what activities can handle this URL" thing wrong, or maybe(?!) the default WebViewClient used by the WebView handles this explicitly?! Seems implausible.
I'm just extending the Temporary (crap) solution here, so this is far from a perfect answer, but might still help someone who absolutely needs to get this to work, also with private tracks.
The replace method works if the track is public, but with private tracks this does not work, probably because of the missing secret token in the intent URL.
Unfortunately the embed player does not contain all the necessary pieces of the URL I need to generate, except inside the iframe, which I cannot access due to cross-origin policy. So in addition to the iframe code I also need the share link.
What I ended up doing is making sure that the containing HTML page has the share link as a JS variable. I then read that variable using Java and create a new Intent with that URL. This works, because the official app also registers all soundcloud.com URLs.
So for private tracks this goes to the HTML page:
<script>var soundCloudURL = "https://soundcloud.com/my-profile/my-track/my-secret-token";</script>
Then inside your Android app you would have something like this:
#Override
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (uri.getScheme().contains("intent")) {
openSoundCloudPlayer();
return true;
}
}
private void openSoundCloudPlayer() {
appWebView.evaluateJavascript("(function() { return soundCloudUrl })();", new ValueCallback<String>() {
#Override
public void onReceiveValue(String soundCloudUrl) {
// JS null is converted into a string "null", not Java null.
if (soundCloudUrl != "null") {
// Take out the quotes from the string
soundCloudUrl = soundCloudUrl.replace("\"", "");
Uri newUri = Uri.parse(soundCloudUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, newUri);
startActivity(intent);
}
}
});
}
Trying to redirect local html page in android webview using Javascript redirect, gets denied starting an intent in Logcat:
Testing on android 5.1.1
document.location = "index.html";
Denied starting an intent without a user gesture, URI:
file:///android_asset/index.html
I read the documentation in 1,000 attempts Android.developer and this was my solution
I do not know if you understand, I speak Spanish
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
This worked for me:
webView.setWebViewClient(new WebViewClient());
There are few issues here.
From newest androids, the WebView and Chrome Client is separated application which can be automatically updated without user intention.
From Chrome x >= 25 version, they changed how loading url is working in android application which is using webview component. https://developer.chrome.com/multidevice/android/intents Looks like they are blocking changing url without user gesture and launched from JavaScript timers
Solution here is to force user to activate URL change, for example on button click.
Also, you can override method mentioned above "shouldOverrideUrlLoading" in WebView client.
As alternate, i figured out was to add addJavascriptInterface each button click event fire action to JavascriptInterface
webView.addJavascriptInterface(new java2JSAgent(), "java2JSAgentVar"); //webView webview object
public class java2JSAgent
{
#JavascriptInterface
public String getContacts()
{
String jsonResponse = "{result:'redirected'}";
runOnUiThread(new Runnable() {
#Override
public void run() {
webView.loadUrl("file:///android_asset/index.html");
}
});
return jsonResponse;
}
}
might not be a good approach but atleast its working :-)
Thanks
I'm looking for a way to log the requests and start/end times made by an embedded webview. I'm not able to find a way to do it so far other than rooting the phone and running tcpdump. That works for me, but I need to run this in the field, so that's not really viable. There are lots of ways to log the URL and start time, but I can't see the finish (or, bonus, the full response metadata).
shouldLoadResource could work if I could wrap the current request, but I'd have to fetch it myself with HTTP support in order to return it en masse, because there isn't enough API exposed to fully forward to the inner request. (I don't want to do that for a number of reasons, including that webview on devices doesn't use the same network stack as the HTTP classes, and because it will change the timing of subresources.)
I've been trying to find ways to turn on chromium_net debug flags to do this, but I can't figure out how do do that in the context of the WebView or system properties.
I would really rather not ship my own webcore to do this, but if needs must...
override method shouldInterceptRequest()
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
Log.d(LOG_TAG, "shouldInterceptRequest: " + url);
return super.shouldInterceptRequest(view, url);
}
In that case, you could also add a WebViewClient (see http://developer.android.com/reference/android/webkit/WebViewClient.html). Which would look something like
WebView webView.setWebViewClient(new MyWebViewClient());
.
.
.
public class MyWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// Note time
// Return false to say we want the WebView to handle the url.
return false;
}
#Override
public void onPageFinished (WebView view, String url)
{
super.onPageFinished(view, url);
// Note time
}
}
Note that both shouldOverrideUrlLoading and onPageFinished are only called only for the main frame - they will not be called for iframes or framesets. But this should give you what you need.
-Edit: Solution Found-
Figured it out after some heavy searching - one person (I literally mean one) said they instead used onPageLoad(); which worked perfectly for my purposes. The difference is that onPageLoad() runs later than shouldOverrideUrlLoading, but It doesn't make a difference in my code.
I'm trying to set up Twitter authorization with OAuth for an Android app, and thus far I can successfully send the user to the authorization URL, however, what I am trying to do now is intercept the redirect to the callback (which would just lead to a 404 error, our callback URL isn't going to have an associated page on our servers). What I'm attempting to do is check if the URL is our callback, then extract the OAuth Verifier from the URL. I setup my WebView with this code:
view = (WebView)findViewById(R.id.twitterWbVw);
view.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView wView, String url)
{
String urlHolder;
String[] verifExtrctr;
urlHolder = url.substring(0, url.indexOf('?'));
System.out.println("url");
if(urlHolder.equalsIgnoreCase(CALLBACK_URL))
{
verifExtrctr = urlHolder.split("?");
verifExtrctr = verifExtrctr[2].split("=");
if(verifExtrctr[0].equalsIgnoreCase("oauth_verifier"))
{
params[5] = verifExtrctr[1];
return true;
}
else
{
System.out.println("Inocorrect callback URL format.");
}
}
else
{
wView.loadUrl(url);
}
return true;
}
});
view.loadUrl(urlAuthorize.toExternalForm());
Thing is even System.out.println("url");(which I'm using to debug)doesn't run! So I'm pretty much dry on ideas, and can't find anyone with a similar problem. The authorization URL goes through fine, and I can successfully authorize the app, however the redirect to the callback URL for some reason never get's intercepted. Any help would be appreciated, this is in my onResume() if that matters.
After some research I conclude that despite what most of the tutorials out there say, shouldOverrideUrlLoading() does not get called when:
You load a URL like
loadUrl("http://www.google.com");
The browser redirects the user automatically via an HTTP Redirect. (See the comment from #hmac below regarding redirects)
It does however, get called when you you click on a link inside a webpage inside the webview. IIRC the twitter authorization uses an HTTP Redirect.. Bummer, this would be helpful if it worked how all the tutorials say it does. I think this is from a very old version the Android API...
You might want to consider overriding the onProgressChanged method of a WebChromeClient like here: How to listen for a WebView finishing loading a URL? or the onPageFinished() method of the WebViewClient.
I've found what I think is a reasonable way to do this thanks to the previous answer and comments pointing me in the right direction.
What I did is override onPageStarted and onPageFinished in a custom WebViewClient.
The code goes something like this...
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (pendingUrl == null) {
pendingUrl = url;
}
}
#Override
public void onPageFinished(WebView view, String url) {
if (!url.equals(pendingUrl)) {
Log.d(TAG, "Detected HTTP redirect " + pendingUrl + "->" + url);
pendingUrl = null;
}
}
And of course along with the Log.d you would put any specific code you want to run upon detecting the redirect.
For people stumbling across this, when the method shouldOverrideUrlLoading(WebView view, WebResourceRequest request) is not being called, look up your minSdkVersion. If you use below API 24 you should use shouldOverrideUrlLoading(WebView view, String url).