6

Update

I have updated my question to hide confidential code.

If still there is some confusion pls msg me in comments.

Question

I have written an custom Webview for playing youtube video embedded in my website to go full Screen.

But its still not Working.. . kindly Help

   public class MainActivity extends Activity  implements OnClickListener {

          final Context context = this;
        private WebView webView;
         private ImageButton btnrefresh;    
         private TextView txtrefresh;
           private myWebChromeClient mWebChromeClient;
         private Menu optionsMenu;
         private WebChromeClient.CustomViewCallback customViewCallback;
            private View mCustomView;       
            private FrameLayout customViewContainer;


        @SuppressWarnings("deprecation")
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            //Tushar
              customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
            //Tushar
            //define button 
            btnrefresh = (ImageButton) findViewById(R.id.imageButton1);

            btnrefresh.setOnClickListener(this);
            btnrefresh.setVisibility(View.GONE);

            //define textView
            txtrefresh = (TextView)findViewById((R.id.textView1));
            txtrefresh.setVisibility(View.GONE);


            if(isConnected())
            {

                webView = (WebView) findViewById(R.id.webView1);
                webView.getSettings().setJavaScriptEnabled(true);       
                   webView.getSettings().setAppCacheEnabled(true);

                    webView.getSettings().setRenderPriority(RenderPriority.HIGH);
                    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                    webView.getSettings().setSaveFormData(true);
            //  webView.getSettings().setPluginState(PluginState.ON);
              webView.setWebViewClient(new WebViewClient()
              {
              @Override
              public boolean shouldOverrideUrlLoading(WebView view, String url) {


                  if (url.startsWith("mailto:")) {
                      sendEmail(url.substring(7));
                      return true;
                  }

                  return false;
              }

            });


                initWebView(webView);                         
                webView.loadUrl("http://Example.com/");             

                }


            else
            {

            RelativeLayout rel = (RelativeLayout)findViewById(R.id.relativelayout1);
            rel.setOnClickListener(new View.OnClickListener(){
               @Override
               public void onClick(View v){
                 refresh();
               }
           });
                btnrefresh.setVisibility(View.VISIBLE); 
                txtrefresh.setVisibility(View.VISIBLE);
                Toast.makeText(getBaseContext(), "No Internet Connection !!", Toast.LENGTH_SHORT).show();


            }       
        }

        public boolean inCustomView() {
            return (mCustomView != null);
        }

        public void hideCustomView() {
            mWebChromeClient.onHideCustomView();
        }

        @Override
        protected void onPause() {
            super.onPause();    //To change body of overridden methods use File | Settings | File Templates.
            webView.onPause();
        }

        @Override
        protected void onResume() {
            super.onResume();    //To change body of overridden methods use File | Settings | File Templates.
            webView.onResume();
        }

        @Override
        protected void onStop() {
            super.onStop();    //To change body of overridden methods use File | Settings | File Templates.
            if (inCustomView()) {
                hideCustomView();
            }
        }

        //tushar
        class myWebChromeClient extends WebChromeClient {
            private Bitmap mDefaultVideoPoster;
            private View mVideoProgressView;

            @Override
            public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
               onShowCustomView(view, callback);    //To change body of overridden methods use File | Settings | File Templates.
            }

            @Override
            public void onShowCustomView(View view,CustomViewCallback callback) {

                // if a view already exists then immediately terminate the new one
                if (mCustomView != null) {
                    callback.onCustomViewHidden();
                    return;
                }
                mCustomView = view;
                webView.setVisibility(View.GONE);
                customViewContainer.setVisibility(View.VISIBLE);
                customViewContainer.addView(view);
                customViewCallback = callback;
            }

            @Override
            public View getVideoLoadingProgressView() {

                if (mVideoProgressView == null) {
                    LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
                    mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
                }
                return mVideoProgressView;
            }

            @Override
            public void onHideCustomView() {
                super.onHideCustomView();    //To change body of overridden methods use File | Settings | File Templates.
                if (mCustomView == null)
                    return;

                webView.setVisibility(View.VISIBLE);
                customViewContainer.setVisibility(View.GONE);

                // Hide the custom view.
                mCustomView.setVisibility(View.GONE);

                // Remove the custom view from its container.
                customViewContainer.removeView(mCustomView);
                customViewCallback.onCustomViewHidden();

                mCustomView = null;
            }
        }
Tushar Narang
  • 1,997
  • 3
  • 21
  • 49

3 Answers3

4

To achieve this you should:

  1. Implement showCustomView and hideCustomView methods of WebChromeClient.
  2. Set android:hardwareAccelerated="true" to your MainActivity in AndroidManifest.xml.

There are two classes that inherit the WebChromeClient in your code (myWebChromeClient and MyWebChromeClient). The first implements showCustomView and hideCustomView methods and it seems fully working with full-screen video. The second one don't. But you (accidentally?) set the second as WebChromeClient to your WebView.

To fix this just change the line

webView.setWebChromeClient(new MyWebChromeClient());

to

mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);

in your initWebView() method.

UPD:

To lock orientation on portrait in normal (not full-screen) mode add following line into onHideCustomView() method:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

To let the system decide the best orientation in full-screen mode add this line to onShowCustomView(View view, CustomViewCallback callback) method:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
erakitin
  • 11,437
  • 5
  • 44
  • 49
  • Sir I have wriiten android:screenOrientation="portrait" > in my manifest. but can i see the video in landscape mode too ?? programitically ? – Tushar Narang Jun 16 '15 at 10:27
  • @tusharnarang Yes, it is possible. See my updated answer. – erakitin Jun 16 '15 at 11:05
  • Sir this is working fine, But the webview is too slow.. takes a minute to load the website – Tushar Narang Jun 16 '15 at 12:52
  • The website I m using is a responsive wordpress site. With heavy Images and database. the issue is the webview does not show a loading bar.. There is a blank white screen for first 20 seconds – Tushar Narang Jun 16 '15 at 13:08
  • Have you tried to optimize you web site and internet connection? – busylee Jun 16 '15 at 13:13
  • Internet is 8 mbps. And website takes much less time in chrome app – Tushar Narang Jun 16 '15 at 13:14
  • In computer browser it takes 10 seconds ||||||||||||||| In chrome app android it takes 20 seconds||||||||||||||||| In my app it takes upto a minute – Tushar Narang Jun 16 '15 at 13:15
  • @erakitin : The app crashes when i try to tilt my phone to landscape mode when playing video full screen – Tushar Narang Jun 16 '15 at 13:21
  • @tusharnarang try to add `android:configChanges="orientation|keyboardHidden|screenSize"` to your `MainActivity` in `AndroidManifest.xml`. It should fix the crash. – erakitin Jun 16 '15 at 13:32
  • Ok sir, Thanks i will try that, can u pls suggest something to show a progress bar and increase speed.. The default spinner of the website shows after 20 seconds in my app – Tushar Narang Jun 16 '15 at 13:34
  • @erakitin : yes the app doesnt crasgh.. But when I press back button the app starts working in landscape mode.. The app should always be in portrait mode except when playing video – Tushar Narang Jun 16 '15 at 13:43
  • @tusharnarang be sure that `setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);` is called. If it is not add this line where it is required. – erakitin Jun 16 '15 at 13:53
  • I have no idea how to increase the speed of `WebView` in your case. The solution depends on the specific situation and it is beyond the scope of this issue. – erakitin Jun 16 '15 at 13:57
  • @erakitin : I m Sire i have called the setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); onHIde – Tushar Narang Jun 16 '15 at 14:06
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/80738/discussion-between-tushar-narang-and-erakitin). – Tushar Narang Jun 17 '15 at 07:10
4

Working Perfectly.

Tested on Android 9.0 version

This is the final thing worked

Set The setWebChromeClient on webview

mWebView.setWebChromeClient(new MyChrome());

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView mWebView;


    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mWebView = (WebView) findViewById(R.id.webView);


        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new MyChrome());    // here
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

       if (savedInstanceState == null) {
          mWebView.loadUrl("https://www.youtube.com/");
       }

    }


    private class MyChrome extends WebChromeClient {

        private View mCustomView;
        private WebChromeClient.CustomViewCallback mCustomViewCallback;
        protected FrameLayout mFullscreenContainer;
        private int mOriginalOrientation;
        private int mOriginalSystemUiVisibility;

        MyChrome() {}

        public Bitmap getDefaultVideoPoster()
        {
            if (mCustomView == null) {
                return null;
            }
            return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
        }

        public void onHideCustomView()
        {
            ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
            this.mCustomView = null;
            getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
            setRequestedOrientation(this.mOriginalOrientation);
            this.mCustomViewCallback.onCustomViewHidden();
            this.mCustomViewCallback = null;
        }

        public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
        {
            if (this.mCustomView != null)
            {
                onHideCustomView();
                return;
            }
            this.mCustomView = paramView;
            this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
            this.mOriginalOrientation = getRequestedOrientation();
            this.mCustomViewCallback = paramCustomViewCallback;
            ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
            getWindow().getDecorView().setSystemUiVisibility(3846 | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

 @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mWebView.restoreState(savedInstanceState);
    }
}

In AndroidManifest.xml

<activity
  android:name=".MainActivity"
  android:configChanges="orientation|screenSize" />

Solution Original Source

Sheharyar Ejaz
  • 2,808
  • 1
  • 14
  • 15
0

Referring to the code Sheharyar Ejaz has posted, I replaced 2 lines to improve the result.

THe first line I replaced is in onShowCustomView, so when user click Youtube fullscreen option of a video, the video will automatically expand into lansdcape fullscreen like native Youtube.

To achieve that, I replaced this line :

this.mOriginalOrientation = getRequestedOrientation();

with this line :

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

The second line I replaced is in onHideCustomView, so when user minimize the fullscreen video, it will revert into the phone's present layout.

What I do is I replaced this line :

this.mOriginalOrientation = getRequestedOrientation();

with this line :

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

But, quite different with the suggestion by erakitin, I did not set android:hardwareAccelerated="true" to my MainActivity/WebView Activity in AndroidManifest.xml.

Gedanggoreng
  • 186
  • 2
  • 11