I have been working on an appliction, the requirement states that i need to open a Youtube link on the web view. Once clicked on the video i need to open the Youtube application to play the video.
After lots of try had not been quite successful to achieve this goal!
Looking forward for sugestions.
this is what i tried.
wb = (WebView)findViewById(R.id.web);
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new MyClient());
wb.getSettings().setPluginsEnabled(true);
wb.getSettings().setPluginState(PluginState.ON_DEMAND);
wb.getSettings().setAllowFileAccess(true);
wb.getSettings().setAppCacheEnabled(true);
wb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wb.loadUrl("http://m.youtube.com");
private class MyClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mHandler.post(new Runnable() {
public void run() {
if(!pgd.isShowing()){
pgd.show();
}
}
});
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i("url loaded", "url::: " + url);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
mHandler.post(new Runnable() {
public void run() {
if(pgd !=null && pgd.isShowing()){
pgd.dismiss();
}
}
});
super.onPageFinished(view, url);
}
}
Any pointers will be highly appreciated.
Thanks.
Well if you have the URL of video and also have youtube's application installed on android device, I have better idea.
Use startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("url of youtube video")));
This will pop up user and will display option of browser and YouTube, and if YouTube is selected the video will be played in YouTube player.
I faced the same issue and got the solution by adding this line:
wb.getSettings().setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
Hope it works for you as well.
Try this in onCreate():
WebView webview = new WebView(this);
String htmlString = "<html> <body> <embed src=\"link of youtube video\"; type=application/x-shockwave-flash width="+DeviceWidth+" height="+DeviceHeight+"> </embed> </body> </html>";
webview.loadDataWithBaseURL(null,htmlString ,"text/html", "UTF-8",null);
webview.setWebViewClient(new MyClient());
You need to implement the WebChromeClient and set it as the client of the webview. Then handle the video playback in the onShowCustomView callback.
If you want more control over where a clicked link loads, create your own WebViewClient that overrides the shouldOverrideUrlLoading() method. MyWebViewClient is an inner class of Activity.
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if ("www.example.com".equals(request.getUrl().getHost())) {
// This is my website, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
startActivity(intent);
return true;
}
}
Related
I am new in android and I am displaying a news link in a webview. News link contains a video. Problem is that, After opening a link i have to click on video then video is playing but i want that video should be play automatically.
Thanks in advance.
My code is:
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setPluginState(PluginState.ON);
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) { web.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
myWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("http://aajtak.intoday.in/livetv.html");
myWebView.getSettings().setMediaPlaybackRequiresUserGesture(false);
https://developer.android.com/reference/android/webkit/WebSettings.html#setMediaPlaybackRequiresUserGesture(boolean)
Note: Only for API level 17 and above.
This works for me.
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
using above, after opening a link no need to click on video, the video is playing automatically.
video on webview didn't support 'autoplay'.
so we shoud start video by hand:
android:
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:onPageFinished();");
}
JS:
function onPageFinished() {
var video = document.getElementById("video");
video.play();
}
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {web.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()"); }
});
You should implement loadUrl on the WebView...
Simply replace web.loadUrl with view.loadUrl and it should work just fine
Just make your webview thinking he is running in PC instead mobile
Insert this os MainActivity file
webView.getSettings().setUserAgentString("1");//for desktop 1 or mobile 0.
I have a "NewsActivity" with a webview. When I start it from my main activity, links are opened in the webview correctly but, for some reason, some url's cause the webview to open but then to immediately launch the external browser. Checking the debug console I have not found any exception or other message thrown by webview as not being able to handle the url.
Please note that I am not talking about a link clicked after the webview has loaded the url/page.
I have also tried to activate javascript in the webview but to no avail.
Also, this happens for just some urls from the same domain (specifically a news website; also, I have no block url or override in place).
Here is one of the urls that fail to open in the webview: url_not_loaded
Here is the code that calls the "NewsActivity"
Intent intent = new Intent(this, NewsActivity.class);
intent.putExtra(MainActivity.EXTRA_MESSAGE, url);
startActivity(intent);
And here is the code in "NewsActivity"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
mWebview = (WebView) findViewById(R.id.newsv);
Log.d(MainActivity.LOG_TAG, "URL: " + url);
mWebview.loadUrl(url);
}
If someone has a clue as to what may be happening or can suggest any idea, I'll be grateful.
Thanks!
Your URL's might have redirects. I encountered a similar problem.
Add this to your activity with the webview.
webView.setWebViewClient(new Callback());
Add this outside of onCreate.
private class Callback extends WebViewClient{ //Helps to open in webview instead of browser
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (false);
}
}
It's not a bug.
You need to use WebViewClient.
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
System.out.println("hello");
return false;
}
});
//Toast.makeText(this, "", Toast.LENGTH_SHORT);
mWebView.loadUrl(url);
You can set a newWebViewClient like this:
webView.setWebViewClient(new WebViewClient());
But to be more precisely you need to override the shouldOverrideUrlLoading method like this:
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}});
There are two types of links in the HTML file:
(1) A normal link like http://www.bbb.com/q?type=normal
(2) A short link like /q?type=short.
For the first kind, just load the url. For the second kind, I should prepend it with a fixed address like http://www.abc.com before loading the url.
I am trying to do this with overriding the shouldOverrideUrlLoading() function in WebViewClient. However this function doesn't gets called for the second type of link. I tried prepending the "http://www.abc.com" to the second type of links in the HTML file. Then the function does get called when I click the second kind of link.
I think what's happening is WebView will first check if the link is a valid url. Only if it is valid will the function gets called. Am I right? How can I solve this? Thanks in advance.
contentWebView = new WebView(context);
webViewClient = new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// String not in Logger.
Log.d(TAG, "Here!");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (hosted) {
contentWebView.setVisibility(VISIBLE);
} else {
summaryTextView.setVisibility(VISIBLE);
articleLinkButton.setVisibility(VISIBLE);
}
progressBar.setVisibility(View.GONE);
}
};
contentWebView.setWebViewClient(webViewClient);
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.loadData(fullString, "text/html", "utf-8");
contentWebView.setVisibility(GONE);
More on this:
I tried changing
contentWebView.loadData(fullString, "text/html", "utf-8");
to
contentWebView.loadDataWithBaseURL("http://www.abc.com", fullString, "text/html", "utf-8", null);
Then the function gets called.
If I change the short link to a full link in the html string manually. Then the function also gets called.
So I think this is probably what is happening: The WebView checks if the link URL is valid. Only when the URL is valid will the shouldOverrideUrlLoading() be called.
You're probably using the KitKat WebView. This is a known issue (I think it's outlined in the migration guide) where URLs that can't be resolved against the base URL are dropped on the floor (you won't get any callbacks for them, neither shouldOverrideUrlLoading nor onPageStarted).
The problem is that your base URL is a data url, so you're trying to resolve '/q?type=short' against 'data:text/html,...' which doesn't make much sense and so the whole attempt to navigate to the URL gets ignored.
This was different for the pre-KK WebView which used KURL instead of GURL for URL processing. GURL is generally more strict (and more secure) than KURL, which is the cause for some incompatibility between the two WebView versions.
Maybe try using onPageStarted method
solution that worked for me was to use loadDataWithBaseURL with an invalid baseUrl and detect that and remove it and replace with "http://" during setWebViewClient
public class MyActivity
extends Activity
{
private static final String badurl = "http://myappname.invalid/";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
WebView wv = ((WebView)findViewById(R.id.webview));
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(false);
settings.setSupportMultipleWindows(true);
wv.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
{
handleUrlview.getHitTestResult().getExtra());
return true;
}
});
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
handleUrl(url);
return true;
}
});
wv.loadDataWithBaseURL(badurl,text,"text/html","utf-8",null);
}
private void handleUrl(String url)
{
if (url.startsWith(badurl))
url = "http://"+url.substring(badurl.length());
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch (ActivityNotFoundException e) { }
}
}
i faced this problem too and solved it by replacing my html response. In my html response there is no any host in "href" html tags. Then i replaced it following codes and thats working like a charm now :)
String htmlString = AppCache.homePageResponse.showcaase.replace("href=\"/", "href=\"" + "evidea://" );
I found that if your page runs in an iframe, clicking on external (http://www...) links does NOT trigger shouldOverrideUrlLoading() !
See shouldOverrideUrlLoading() not called for external links from iframe
Try this
private static WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //should be activity_main
webView = (WebView) findViewById(R.id.web);
webView.setWebViewClient(new webviewclient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.yahoo.com");
}
public class webviewclient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.toString());
return true;
}
I have searched and read a lot of posts but can not figure out how to do it in my code.
I want to use geolocation in my app and need to view in webChromeClient in stead of webViewClient which I use for the html files now and the links does stay in the same view.
When I change this to webChromeClient, the html links, like <a href="http://url/file.php?q=123", are suddenly opening in the browser!
How can I prevent this?
myWebView = new WebView(this);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setGeolocationEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onGeolocationPermissionsShowPrompt(String origin, android.webkit.GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false); }
});
myWebView.loadUrl("file:///android_asset/HTML/index.html");
setContentView(myWebView);
WebChromeClient doesn't contain the shouldOverrideUrlLoading method, the WebViewClient does. Remember the "WebView" can and does use both WebViewClient and WebChromeClient at the same time if specified. The WebViewClient adds methods not available to you with no client assigned (keeping navigation in the webview). The same with the WebChromeClient has specific methods it can use (get page title on load for example).
So you can build your code like this:
WebView web = (WebView)findViewById(R.id.web);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setSupportMultipleWindows(true); // This forces ChromeClient enabled.
web.setWebChromeClient(new WebChromeClient(){
#Override
public void onReceivedTitle(WebView view, String title) {
getWindow().setTitle(title); //Set Activity tile to page title.
}
});
web.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
I was able to get around this by setting a dummy WebViewClient in addition to the WebChromeClient. Not sure why, but when I take out this line the web page starts opening in the browser again.
mBrowser.setWebViewClient(new WebViewClient());
To open links in the browser you can use an intent in the shouldOverrideUrlLoading method to launch the URL in a browser versus using your webview to handle the link:
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("http://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
If you want to load in the webview use:
WebViewClient yourWebClient = new WebViewClient()
{
// Override page so it's load on my view only
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// This line we let me load only pages with an anchor tag
if ( url.contains("url") == true )
//Load new URL Don't override URL Link
return false;
// Return true to override url loading (In this case do nothing).
return true;
}
};
i am developing a new android application,and using a webview to view my website in one the website pages there is a link for login with facebook
after logging directly, it returns a blank and embty webview
i have seen couple of topics here regarding the same issue but it is not exactly like mine
please note that if i am using normal desktop browser the issue is not there
I assume that there is a property of the webview should be adjusted , below my webview code
webView1=(WebView)findViewById(R.id.webView1);
webView1.setWebViewClient(new MyWebViewClient());
WebView webView1 = (WebView) findViewById(R.id.webView1);
webView1.setWebChromeClient(new WebChromeClient());
webView1.getSettings().setAppCacheEnabled(true);
webView1.getSettings().setDatabaseEnabled(true);
webView1.getSettings().setDomStorageEnabled(true);
webView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView1.getSettings().setGeolocationEnabled(true);
webView1.loadUrl("http://www.myactivepoint.com/mobile/maplp.asp");
i really approciate your support
I had a similar experience with you. I solved the problem by the following methods.
public class CustomWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
if(url.startsWith("https://m.facebook.com/dialog/oauth")){
String redirectUrl = "http://www.mydomain.com/myReturnUrl";
view.loadUrl(redirectUrl);
return;
}
super.onPageFinished(view, url);
}}
and just add it to your WebView
webview.setWebViewClient(new CustomWebViewClient());
This is my solution. After successfull login you have to redirect the page. You can get the address from refsrc parameter in the Facebook URL, but sometimes (e.g. next try to log in) refsrc is missing so I use domain parameter. You can override the URL address if you need. See the code:
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(final WebView view, final String url)
{
if(getActivity()!=null)
{
if(url.contains("facebook.com") && url.contains("dialog/oauth") &&
(url.contains("&refsrc") || url.contains("&domain")))
{
Uri uri = Uri.parse(url);
String callbackUrl = uri.getQueryParameter("refsrc");
if(callbackUrl==null)
callbackUrl = "http://" + uri.getQueryParameter("domain");
view.loadUrl(callbackUrl); // callback URL
}
}
}
}