I am working in an Android app and I want to preload splash screen while the webView is loading the webpage BUT i have a local .mp4 video instead of a picture.
So once the user clicks the app, the .mp4 will start playing (4 seconds). During that 4 seconds the webView should pre-load the webpage SO when the video is finished show my web page (if the web page is already loaded), otherwise wait in the splash screen until the webpage is ready and then load it.
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
private WebView webView;
public static final Object SPLASH_LOCK = new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
String myURL = "https://www.testpage.com";
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setAllowContentAccess(true);
/** tell the webView to enable javascript execution */
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webSettings.getAllowFileAccessFromFileURLs();
webSettings.getAllowUniversalAccessFromFileURLs();
/** Load the HTML page */
webView.loadUrl(myURL);
/** Call the JavaScriptInterface within the WebView */
webView.addJavascriptInterface(this, "jsinterface");
startActivity(new Intent(this, AnimationScreenActivity.class));
/** Enable Javascript in WebView
/ callback for browser events */
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished (WebView webView, String url) {
synchronized (SPLASH_LOCK) {
SPLASH_LOCK.notifyAll();
}
}
});
}
}
Here is the AnimationScreenActivity:
public class AnimationScreenActivity extends AppCompatActivity{
private static String TAG = AnimationScreenActivity.class.getName();
private static long MAX_SPLASH_TIME = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.animation_screen);
try {
VideoView videoHolder = (VideoView) findViewById(R.id.videoView1);
Uri video = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myvideo);
videoHolder.setVideoURI(video);
videoHolder.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
jump();
}
});
videoHolder.start();
} catch (Exception ex) { jump(); }
}
private void jump() {
new Thread() {
#Override
public void run() {
synchronized (MainActivity.SPLASH_LOCK) {
// wait for notify or time-out
try {
MainActivity.SPLASH_LOCK.wait(MAX_SPLASH_TIME);
} catch (InterruptedException ignored) {}
}
finish();
}
}.start();
}
}
Here is the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="test.test_android.MainActivity">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Here is the animation_screen_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/animation_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="test.test.AnimationScreenActivity">
<VideoView
android:id="#+id/videoView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
And finally the Manifest.xml where i set MainActivity as LAUNCHER:
<activity android:name=".MainActivity"
android:theme="#style/FullScreenTheme"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".AnimationScreenActivity"
android:theme="#style/FullScreenTheme"
android:screenOrientation="portrait"/>
So what i have until now is that once the user starts the app, the .mp4 starts and when the .mp4 finish THEN it waits for 10 seconds in the AnimationScreenActivity and THEN it loads the webpage.
Any help will be appreciated!
You can have a single Activity that has what you have on the 2 Activities, by having a ViewSwitcher (or ViewAnimator) to switch between the layouts.
This will also remove the need for the SPLASH_LOCK object.
While loading, switch the ViewSwitcher (or ViewAnimator) to the layout of the video, and when you are done loading the page, switch it to the layout of the WebView.
I've made a simple code to make it easier to switch between view. If you wish, you can use it:
public static void setViewToSwitchTo(#NonNull final ViewAnimator viewAnimator, #NonNull final View viewToSwitchTo) {
if (viewAnimator == null)
return;
if (viewAnimator.getCurrentView() == viewToSwitchTo)
return;
for (int i = 0; i < viewAnimator.getChildCount(); ++i)
if (viewAnimator.getChildAt(i) == viewToSwitchTo) {
viewAnimator.setDisplayedChild(i);
break;
}
}
public static void setViewToSwitchTo(#NonNull final ViewAnimator viewAnimator, #IdRes final int viewIdToSwitchTo) {
if (viewAnimator == null)
return;
if (viewAnimator.getCurrentView().getId() == viewIdToSwitchTo)
return;
for (int i = 0; i < viewAnimator.getChildCount(); ++i)
if (viewAnimator.getChildAt(i).getId() == viewIdToSwitchTo) {
if (viewAnimator.getDisplayedChild() == i)
return;
viewAnimator.setDisplayedChild(i);
return;
}
}
Usage:
setViewToSwitchTo(viewSwitcher, R.id.webViewLayout);
or:
setViewToSwitchTo(viewSwitcher, webViewLayout);
You can even have an animation when switching between the views, using "inAnimation" and "outAnimation" attributes.
And, if the code gets too large, you can have fragments instead of views. One for the WebView, and another for the video.
About onPageFinished being called multiple times, you need to check which of them is the one that you consider as really being finished. Since each website is different, and can have multiple frames, you will have to add this logic. If you want, you can monitor onPageStarted, as shown here:
https://forums.xamarin.com/discussion/15293/why-is-onpagefinished-firing-off-three-times-for-one-url-load-request
https://stackoverflow.com/a/25547544/878126
BTW, if you change the orientation in the manifest, do note that since you have a WebView, you will have to think what to do with orientation change, because it doesn't restore its state well.
EDIT:
Here's the layout file:
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/viewSwitcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="test.test_android.MainActivity">
<VideoView
android:id="#+id/videoView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" />
</ViewSwitcher>
in the onCreate, use the code of both of your activities, and add this to go to the video :
setViewToSwitchTo(viewSwitcher, R.id.videoView1);
and this to go to the webView (when it has done loading, in your case) :
setViewToSwitchTo(viewSwitcher, R.id.webView);
After a lot of help from #android developer (many thanks!) and stackoverflow posts, I have combined both activities MainActivity, AnimationScreenActivity in one activity (MainActivity).
Here is the code:
public class MainActivity extends AppCompatActivity {
private String myURL = "https://www.testpage.com";
VideoView videoView;
ViewSwitcher viewSwitcher;
private WebView webView;
private boolean hasFinishedLoadingPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
final VideoView videoView = (VideoView) findViewById(R.id.videoView1);
Uri video = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.myvideo);
videoView.setVideoURI(video);
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (hasFinishedLoadingPage)
setViewToSwitchTo(viewSwitcher, webView);
// else webView.reload();
setViewToSwitchTo(viewSwitcher, webView);
}
});
videoView.start();
} catch (Exception ex) {
}
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setAllowContentAccess(true);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webSettings.getAllowFileAccessFromFileURLs();
webSettings.getAllowUniversalAccessFromFileURLs();
webView.setWebViewClient(new WebViewClient() {
boolean isRedirected;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (!isRedirected) {
setViewToSwitchTo(viewSwitcher, videoView);
}
isRedirected = true;
}
#Override
public void onPageFinished(WebView webView, String url) {
super.onPageFinished(webView, url);
hasFinishedLoadingPage = true;
}
});
/** Callback for web events */
webView.setWebChromeClient(new WebChromeClient() {
});
webView.loadUrl(myURL);
}
public static void setViewToSwitchTo(#NonNull final ViewAnimator viewAnimator, #NonNull final View viewToSwitchTo) {
if (viewAnimator == null)
return;
if (viewAnimator.getCurrentView() == viewToSwitchTo)
return;
for (int i = 0; i < viewAnimator.getChildCount(); ++i)
if (viewAnimator.getChildAt(i) == viewToSwitchTo) {
viewAnimator.setDisplayedChild(i);
break;
}
}
}
My suggestion would be to avoid having 2 activities, I suspect that's one of your problems.
Have only one Activity with the VideoView and the WebView both inside a RelativeLayout so that VideoView is above the WebView.
When the WebView is ready, simply VideoView.setVisibity(View.GONE)
Related
In My activity I have a Webview at the top which plays the video inside it.
below the Webview I have a list of videos to select. For Android versions before Oreo when I select the new video it always plays in the Webview. But in Oreo it doesn't work, It always plays the first video Which i Selected. I have read the document of Oreo it says that
Calling clearFormData() no longer has any effect.
I am looking for some alternative but couldn't find any solution. Below is the my work which I have done so for
private void initViews() {
toolbar = findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.app_name));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
recyclerView = findViewById(R.id.recycler_view);
progressBar = findViewById(R.id.progressBar3);
initWebView();
if (recyclerView != null) {
initRecyclerView(model);
}
AdView adView= findViewById(R.id.ad_view);
admobUtils.loadBannerAd(adView);
}
public void initWebView() {
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setSaveFormData(false);
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.setWebViewClient(new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
view.clearHistory();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
RXEventBusUtils.getInstance().postEvent(new MediaPlayerEvent());
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
}
});
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setDisplayZoomControls(false);
String htmlData;
if (Constants.isFullScreen) {
htmlData = getHtmlDataLanscape(model.getVideo_url());
} else {
htmlData = getHtmlData(model.getVideo_url());
}
webView.loadData(htmlData, "text/html", null);
}
This is where I am selecting the video from list.
public void selectVideo(){
progressBar.setVisibility(View.VISIBLE);
model = new MyModel();
model = ((SelectVideoEvent) event).getModel();
if (model.getVideo_url() != null && !model.getVideo_url().isEmpty()) {
initRecyclerView(model);
initWebView();
Bundle bundleFire = new Bundle();
Application.getFireBaseInstance().logEvent("video_from_list",bundleFire);
}
}
Please can anybody tell me how to change the webview content in Android Oreo
As clearFormData() no longer has any effect in android version Oreo. The best way is to create a Webview as a new view. For that purpose you should use a frameLayout inside xml file, and inside java file, create webview dynamically and add that webview in framelayout as a view.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<FrameLayout
android:id="#+id/myWeb"
android:layout_width="match_parent"
android:layout_height="200dp"
android:alwaysDrawnWithCache="true" />
</RelativeLayout>
public class TestActivity extends AppCompatActivity {
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
frameLayout = findViewById(R.id.myWeb);
setWebView();
/*setWebViewToLoadData*/
}
public void setWebView(){
frameLayout.removeAllViews();
WebView webView = new WebView(this);
webView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
frameLayout.addView(webView);
}
}
And indside your selectVideo method call again setWebView
I need to pull from the top to refresh my web view
I found this on Android Developer site but i don't know how to use it
xml Code
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java code
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
myUpdateOperation();
}
}
);
You gotta put your WebView inside SwipeRefreshLayout:
public class MainActivity extends AppCompatActivity {
WebView webView;
SwipeRefreshLayout swipeRefreshLayout;
String currentUrl = "https://news.ycombinator.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
webView.loadUrl(currentUrl);
webView.setWebViewClient(new MyWebViewClient());
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl(currentUrl);
}
});
}
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
}
swipeRefreshLayout.setRefreshing(false) stops the animation.
To be able to refresh the page with the same URL running
you gotta save your link in ISharedPreferences when page first loaded
public override void OnPageFinished(WebView view, string url)
{
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutString("MyURL", url);
editor.Commit();
}
when you load the URL for reffresh use the saved URL
string SaveURL = prefs.GetString("MyURL", "");
webView.loadUrl(SaveURL);
-- Other Solution is
Webview.Reload(); // This code Refreshes the current page loaded
I have two activities in my android project. Both contents WebView and load same html(which include some javascript code also) file from assets folder.
When I load WebView in first activity it works fine. But after navigating to second activity, same html file doesn't load in WebView.
Activity 1:
public class Activity_1 extends AppCompatActivity {
WebView webView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__1);
webView = (WebView) findViewById(R.id.webview1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Activity_1.this, Activity_2.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
webView.loadUrl("file:///android_asset/sample.html");
}
#Override
protected void onPause() {
super.onPause();
}
}
Activity 2:
public class Activity_2 extends AppCompatActivity {
WebView webView;
ProgressDialog progressDialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
webView = (WebView) findViewById(R.id.webview2);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
}
#Override
protected void onResume() {
super.onResume();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
if (Build.VERSION.SDK_INT >= 19)
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
else
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressDialog.dismiss();
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressDialog.setProgress(newProgress);
}
});
webView.loadUrl("file:///android_asset/sample.html");
progressDialog.show();
}
}
activity_1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<WebView
android:id="#+id/webview1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Next"
android:textSize="22sp"/>
</LinearLayout>
activity_2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<WebView
android:id="#+id/webview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
When I open second activity, I get stuck as,
I don't understand that same html is loading properly in first Activity, but not in the second.
I also tried with clear WebView cache in first activity and destroying WebView in onDestroy of activity 1.
To load html, I tried with following methods:
webView.loadUrl("file:///android_res/raw/sample.html");
OR
Access html from storing as string resource
webView.loadDataWithBaseURL(null, getResources().getString(R.string.html), "text/html", "UTF-8", null);
Edit:
I tried with uninstalling webview updates and its working fine.
Is there any problem with webview updates in android 5.0?
Please let me know what I am doing wrong?
I've done a similar project to try your code. It's working for me :S
Maybe you can try to place you file in src/main/assets and use this line
webView.loadUrl("file:///android_asset/sample.html");
But in my case is working with two options. ¿Can you provide more info about html file please?
I have an activity which is displaying a web page using a WebView. Within that page, there is a link to a YouTube video (so it's not a video I can or need to embed).
The problem is that the video won't play - When i click on the play button, a error page appears saying
" Webpage not available
The webpage at vnd.youtube:SVf8Ghl6d8xx
might be temporarily down and blah blah blah !!!"
Please only answer if you know what i want! I have gone through almost all related posts on stackoverflow so there is no need of references to other posts/question.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add the custom view to the action bar
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
webView.getSettings().setPluginState(WebSettings.PluginState.ON); //Helps flash run on a device
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient ());
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setUseWideViewPort(true);
//webView.getSettings().setUseWideViewPort(false);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.loadUrl(url);
}
The following code make it run in the youtube app but i want the videos to run in my app :(
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add the custom view to the action bar
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2)
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.setWebViewClient(new WebViewClient () {
# Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("vnd.youtube")){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
else return false;
}
});
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setUseWideViewPort(true);
//webView.getSettings().setUseWideViewPort(false);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.loadUrl(url);
}
Go to Google Developer Console and select or create a new project.
On the left sidebar, select APIs under APIs & auth and turn the status ON for YouTube Data API v3.
On the left sidebar, select Credentials and Create new key under Public API access.
When popup comes asking you to choose platform, select Android Key.
Paste the SHA-1 key and your project’s package name separated by semicolon(;).
Click on create. Now you should see the API KEY on the dashboard.
download YouTubeAPI jar from here
https://developers.google.com/youtube/android/player/downloads/
Create a layout like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
android:layout_centerInParent="true" />
</RelativeLayout>
Your activity should look something like this
public class CustomYouTubePlayer extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
private String API_KEY="your key";
private String VIDEO_ID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.youtube_player);
/** Initializing YouTube player view **/
VIDEO_ID = getIntent().getExtras().getString(FinalVariables.YOUTUBE_ID);
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
player.setShowFullscreenButton(false);
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.loadVideo(VIDEO_ID);
}
}
private YouTubePlayer.PlaybackEventListener playbackEventListener = new YouTubePlayer.PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
private YouTubePlayer.PlayerStateChangeListener playerStateChangeListener = new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(YouTubePlayer.ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
finish();
}
#Override
public void onVideoStarted() {
}
};
}
Just pass the video id and that's all simple as that..
Edit
if this is your YouTube link https://www.youtube.com/watch?v=rql_F8H3h9E
then your video_id=rql_F8H3h9E
Extract your video id from YouTube link and sent to this activity as extra variable.
The Best Way you could embed youtube videos in the app is by using Youtube API
The YouTube Android Player API enables you to incorporate video
playback functionality into your Android applications. The API defines
methods for loading and playing YouTube videos (and playlists) and for
customizing and controlling the video playback experience.
For this you will convert the iFrame code of your embed YouTube video to a string and load it to webview as a string in your application.
For example,
String frameVideo = "<html><body>Youtube video .. <br> <iframe width="320" height="315" src="https://www.youtube.com/embed/lY2H2ZP56K4" frameborder="0" allowfullscreen></iframe></body></html>";
then load it to your webview after all the normal webview settings
WebView displayVideo = (WebView)findViewById(R.id.webView);
displayVideo.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = displayVideo.getSettings();
webSettings.setJavaScriptEnabled(true);
displayVideo.loadData(frameVideo, "text/html", "utf-8");
For more information refer this links 1 2 3
I am trying to play html5 video and youtube video within android webview, but can't display video on android webview screen. and play this video.
I have used below code snippet...
layout xml file naming: test.xml contains below code snipet:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:id="#+id/rltvLayoutTest"
android:layout_height="fill_parent">
<WebView android:id="#+id/webViewTest" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
and Activity Class name: Test.java contains code given below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
WebView mWebView = (WebView)findViewById(R.id.webViewTest);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.setWebChromeClient(new chromeClient());
mWebView.setWebViewClient(new WebViewClient(){
});
mWebView.loadUrl("http://broken-links.com/tests/video/");
}
public class chromeClient extends WebChromeClient implements OnCompletionListener, OnErrorListener{
private WebView wv;
private VideoView mVideoView;
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT, Gravity.CENTER);
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (view instanceof FrameLayout) {
wv = (WebView)findViewById(R.id.webViewTest);
mCustomViewContainer = (FrameLayout) view;
mCustomViewCallback = callback;
mContentView = (LinearLayout)findViewById(R.id.rltvLayoutTest);
if (mCustomViewContainer.getFocusedChild() instanceof VideoView) {
mVideoView = (VideoView) mCustomViewContainer.getFocusedChild();
// frame.removeView(video);
mContentView.setVisibility(View.GONE);
mCustomViewContainer.setVisibility(View.VISIBLE);
setContentView(mCustomViewContainer);
mVideoView.setOnCompletionListener(this);
mVideoView.setOnErrorListener(this);
mVideoView.start();
}
}
}
public void onHideCustomView() {
if (mVideoView == null)
return;
// Hide the custom view.
mVideoView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mVideoView);
mVideoView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
public void onCompletion(MediaPlayer mp) {
mp.stop();
mCustomViewContainer.setVisibility(View.GONE);
onHideCustomView();
setContentView(mContentView);
}
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
setContentView(mContentView);
return true;
}
}
I used html5webview to solve this problem.Download and put it into your project then you can code just like this.
private HTML5WebView mWebView;
String url = "SOMEURL";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new HTML5WebView(this);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
mWebView.loadUrl(url);
}
setContentView(mWebView.getLayout());
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
To make the video rotatable, put android:configChanges="orientation" code into your Activity
for example (Androidmanifest.xml)
<activity android:name=".ui.HTML5Activity" android:configChanges="orientation"/>
and override the onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
you haven't added mCustomViewContainer to your view hierarchy
if you are running it on tablet... you add hardwareaccelerated= true in your manifest file and it will certainly work.. also change the sdk version to 11
It worked for me. May help you as well play html videos