I'm trying to embed a Youtube video in a WebView, and I want to support Android version 2.
Since Google owns both Android and Youtube, I thought it would be easy, but apparently it's not. I've seen similar questions but they didn't help.
On Android 2.1 when I tap the play button, I have the message "An error occurred, please try again later."
On Android 2.3 I have player buttons but the video does not start.
Here is my code:
public class YoutubeActivity extends Activity {
private WebView webView;
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
webView = new WebView (this);
setContentView (webView);
webView.getSettings ().setJavaScriptEnabled (true);
webView.setWebChromeClient (new WebChromeClient ());
webView.setWebViewClient (new WebViewClient () {
public boolean shouldOverrideUrlLoading (WebView view, String url) {
view.loadUrl (url);
return true;
}
});
if (Build.VERSION.SDK_INT < 8) {
webView.getSettings ().setPluginsEnabled (true);
}
else {
webView.getSettings ().setPluginState (PluginState.ON);
}
webView.loadUrl ("http://youtube.com/embed/NAg4qXsk99c?rel=0");
}
protected void onPause () {
super.onPause ();
webView.loadUrl ("about:blank");
}
}
I also added android:hardwareAccelerated="true" in AndroidManifest.xml.
The Youtube Android Player API is not an option for me because I also want to support platforms without the Youtube app (like Amazon, Blackberry...).
I also tried with RTSP links but the quality is too bad.
Thanks for your help.
Related
I want to make an app where the user can get random youtube videos in a webview by clicking a button.
I already can show a video in my webview with the url but I want to get any random video from youtube by clicking my button.
In my xml file I have a webview and a button
´´´
MainActivity.java
´´´
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path = "https://www.youtube.com/watch?v=1uwvxTT5V5M";
String dataUrl =
"<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
WebView showYoutubeVideo = (WebView) findViewById(R.id.zufallvideo);
showYoutubeVideo.setWebViewClient(new WebViewClient(){
public boolean shouldoverloadUrlLoading(WebView view, String url) {
return false;
}
});
showYoutubeVideo.getSettings().setJavaScriptEnabled(true);
showYoutubeVideo.loadData(dataUrl,"text/html", "utf-8");
}
}
TL;DR: it's complicated.
Until Youtube exposes an endpoint in their API to do this, you're gonna need to find a workaround.
Some would suggest to query a search with "IMG" followed by a random integer (ex. "IMG 22930"). The end result is quite surprising, since tons of videos are uploaded without renaming.
Here's an example of this workaround implementation in python: https://github.com/0x01h/random-youtube-video-generator
I am developing a browser in Android webview,
How can I detect if a website is asking for location permission and have custom control to give it or not.
write below line in onCreate
webView.setWebViewClient(mWebViewClient);
write below methode in your class
private WebChromeClient mWebChromeCient = new WebChromeClient() {
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
}
};
For more detail click tutorials link
Context: I'm trying to link an authenticated user in my android app to a Facebook fanpage PSID using the "Send to Messenger" Plugin to be able to send messages to that specific user on certain events that responds to the user actions in other systems.
I figured the best way to achieve this (since said plugin only works with the Facebook Javascript SDK) was to open a WebView Activity in my app, loading a website with the plugin button.
The website includes the following to load the SDK and the button:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<<Here I put my FB App ID>>',
autoLogAppEvents : true,
xfbml : true,
version : 'v2.12'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-send-to-messenger"
messenger_app_id="<<Same FB App ID>>"
page_id="<<FB fanpage ID>>"
data-ref="<<user identification>>"
color="blue"
size="standard">
</div>
Here's the onCreate method of the Webview Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(webview);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WebView.setWebContentsDebuggingEnabled(true);
}
webview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d("WEBVIEW_CONSOLE", consoleMessage.message() + " -- From line "
+ consoleMessage.lineNumber() + " of "
+ consoleMessage.sourceId());
return super.onConsoleMessage(consoleMessage);
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl(getString(R.string.authenticated_webview_url_example), headers);
Expectation: The facebook Send to Messenger Button should load in the WebView, allowing the user to register a PSID on my Facebook fanpage/App.
Problem: When I load the website on the Android WebView, the button is not shown.
Details: Using Chrome Remote Debugging, I was able to determine the Facebook SDK was working and almost all the elements of the buttons were loaded, except for the content of the iframe generated.
Tested the Facebook jssdk by using a Like button, which worked and was shown.
No errors in website console or logcat.
Why is WebView not showing that particular button?
Testing website: https://www.vsdesigns.cl/debug/login.php
Edit:
Here is an image of the testing website from a desktop browser. It shows the button.
Here is another image with the testing website being loaded by the WebView. It's actually a representation of the chrome remote debugger, but it's the same as what my smartphone screen shows. It doesn't show the button.
Thanks in advance.
I figured out the Facebook Cookies weren't loading at all, and Facebook doesn't render the plugin if the App is in development and the user is not previously logged in, so I implemented the following code to accept Third party cookies. (Only works on SDK version 21 Lollipop and up)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setAcceptThirdPartyCookies(mWebview,true);
}
mWebview would be the variable storing the actual WebView.
I've been reading answers, questions, forums and blogs for 2 days now but can't fix my issue.
I've an AngularJS webApp working in a Native (SDK) Android App with a WebView.
Everything seems to work but when my application calls services that responds with the "Set-Cookie" header those cookies are not setted in the webview and, of course are neither sent in the next calls, so my app explodes.
The app works flawlessly in browser and cordova and "document.cookie" returns an empty string, so i know this is where it fails.
My webview is initialized like this:
public class Main extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new mWebViewClient());
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setSavePassword(true);
webview.getSettings().setAllowFileAccessFromFileURLs(true);
webview.getSettings().setAllowContentAccess(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUserAgentString(...);
webview.loadUrl("file:///android_asset/www/index.html");
javascriptAPI = new JavascriptAPI(this);
webview.addJavascriptInterface(javascriptAPI, "jsAPI");
...
}
...
}
I've tried also with chunks of code from here and there like:
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().run();
CookieManager.getInstance().setAcceptCookie(true);
But it doesn't work neither.
My app is calling to some services that use redirect, so fetching the cookies from JS and setting them is not an option, i need the webview to work like a browser would.
This is my first SDK Android App and i'm not sure at all what info could be relevant to answer the question (manifest, jsAPI, etc) so don't hessitate to say and i'll post whatever else is needed
SOLVED
Thank you #Mark, this fixed my code:
(inside Activity onCreate)
...
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(this);
}
^^^^^^^
THIS
WebView webview = (WebView) findViewById(R.id.webview);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().run();
CookieManager.getInstance().setAcceptCookie(true);
CookieManager.getInstance().setAcceptFileSchemeCookies(true); <- THIS
CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true); <- THIS
webview.setWebViewClient(new mWebViewClient());
webview.getSettings().setAppCacheEnabled(true);
...
There are three acceptCookie methods you need to worry about, and different behavior across several versions of Android to take into consideration.
1) I noticed your initial url is a file:// url. You may need to call CookieManager.getInstance().setAcceptFileSchemeCookies(true);.
2) In Android Lollipop and greater, you may need to call CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
3) For Android versions < Lollipop, if you want cookies to be persisted (e.g., survive rotation), you have to take some steps to manually manage syncing.
First, to ensure that CookieSyncManager is initialized during application startup by adding it your appplication class' onCreate(), or extend this one.
public class CookieApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.createInstance(this);
}
}
}
Second, you need to setup syncing for pre-lollipop devices, and finally to enable cookies. Here's an example activity that you could extend that sets up all the syncing for pre-Lollipop devices, and provides an enablesCookies(webView) that should turn on all cookie types regardless of Android version (be advised there are security considerations to be made when calling these methods!). Note that all of the CookieManager.getInstance().set*Cookie*() methods must be called after the webView is initialized.
public class AppCompatCookieActivity extends AppCompatActivity {
#Override
public void onResume() {
super.onResume();
// start cookie syncing for pre-lollipop devices
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.getInstance().startSync();
}
}
#Override
public void onPause() {
// stop cookie syncing for pre-lollipop devices
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.getInstance().sync();
}
super.onPause();
}
public final void enableCookies(WebView webView) {
// enable javascript (has security implications!)
webView.getSettings().setJavaScriptEnabled(true);
// enable cookies.
CookieManager.getInstance().setAcceptCookie(true);
// enable fileScheme cookies (has security implications!)
// it is recommended to comment this out should you find it not necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
CookieManager.getInstance().setAcceptFileSchemeCookies(true);
}
// enable third party cookies
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
}
}
}
Right now when I push a specific button it starts an intent to open a web page into a webView, but instead it opens a Browser Application, revealing the address bar which is not what I want.
After doing some research I found out I can use the shouldOverrideUrlLoading() method to stop this from happening and just open the page in a webView, but I don't know how to implement this method in my code, help would be greatly appreciated!
This is what I have in the class where I'm opening the web page:
public class Codes extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.codes);
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.rgb(228, 108, 10));
}
}
WebView codes = (WebView)findViewById(R.id.codesWebView);
codes.getSettings().setJavaScriptEnabled(true);
codes.loadUrl("http://dev10.affirmaconsulting.com:24009/keyentry");
shouldOverrideUrlLoading(codes, "http://dev10.affirmaconsulting.com:24009/keyentry");
}
}
I had this same problem, that pages were not loading in my webview but instead via the browser application. I resolved the issue by implementing a WebViewClient class and overriding the shouldOverrideUrlLoading method.
WebViewClient webClient = new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
return false;
}
};
webView.setWebViewClient(webClient);
The following link proved to be helpful:
http://www.firstdroid.com/2010/08/05/override-url-loading-in-webview-android-tutorial/
We do this exact task in one of our activities and haven't ran into this issue. Here is what ours looks like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.document_viewer_activity);
WebView wv = (WebView) findViewById(R.id.documentViewerWebview);
wv.getSettings().setJavaScriptEnabled(true);
String url = getString(R.string.document_viewer_url) +
getIntent().getExtras().getString("media");
wv.loadUrl(url);
}
With the webview defined in the layout file looking like this:
<WebView
android:id="#+id/documentViewerWebview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
Hope this helps.