Android uses WebView to realize the function of full screen switching and playing web video

Time:2021-1-16

First write the layout file activity_ main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/container"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical">
  <FrameLayout
    android:id="@+id/video_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"
    ></FrameLayout>
  <Button
    android:id="@+id/video_landport"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text= "Do not display this button in full screen, click to switch to horizontal screen"
    android:gravity="center"
    />
  <WebView
    android:id="@+id/video_webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
  </LinearLayout>

Principle: when realizing full screen, put the video in WebView into a view (video in layout)_ View control), and then hide WebView! In this way, full screen playback is realized!

Now let’s see how it is implemented

Put the code first MainActivity.java :

public class MainActivity extends Activity {
   Private FrameLayout videoview; // video loading view in full screen
  private Button videolandport;
  private WebView videowebview;
  Private Boolean islandport = true; // true means vertical screen, and false means horizontal screen.
  private View xCustomView;
  private xWebChromeClient xwebchromeclient;
  private String url = "http://look.appjx.cn/mobile_api.php?mod=news&id=12604";
  private WebChromeClient.CustomViewCallback   xCustomViewCallback;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature( Window.FEATURE_ NO_ Title); // remove the application title
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
    initwidget();
    initListener();
    videowebview.loadUrl(url);
  }
  private void initListener() {
    // TODO Auto-generated method stub
    videolandport.setOnClickListener(new Listener());
  }
  private void initwidget() {
    // TODO Auto-generated method stub
    videoview = (FrameLayout) findViewById(R.id.video_view);
    videolandport = (Button) findViewById(R.id.video_landport);
    videowebview = (WebView) findViewById(R.id.video_webview);
    WebSettings ws = videowebview.getSettings();
    /**
     *Setallowfileaccess enables or prevents WebView from accessing file data. Does setblocknetworkimage display network image
     *Setbuiltinzoomcontrols sets whether scaling setcachemode is supported and sets the buffering mode
     *Setdefaultfontsize sets the default font size. Setdefaulttextencodingname sets the default encoding to use when decoding
     *Setfixedfontfamily sets the font for fixed use. Setjavascript enabled sets whether JavaScript is supported
     *Setlayoutalgorithm sets the layout mode setlighttouchenabled sets the mouse enabled option
     *Setsupportzoom sets whether zoom is supported
     * */
    ws.setBuiltInZoomControls (true); // hide zoom button
    ws.setLayoutAlgorithm ( WebSettings.LayoutAlgorithm.NARROW_ Columns); // the typesetting adapts to the screen
    ws.setUseWideViewPort (true); // it can be scaled at any scale
    ws.setLoadWithOverviewMode (true); // the setusewideviewport method sets the recommended window for WebView. The setloadwithoverviewmode method sets the mode of the page loaded by WebView.
    ws.setSavePassword(true);
    ws.setSaveFormData (true); // save the form data
    ws.setJavaScriptEnabled(true);
    ws.setGeolocationEnabled (true); // enable geolocation
    ws.setGeolocationDatabasePath ("/data/data/ org.itri.html5webview/databases/ "); // set the location database path
    ws.setDomStorageEnabled(true);
    xwebchromeclient = new xWebChromeClient();
    videowebview.setWebChromeClient(xwebchromeclient);
    videowebview.setWebViewClient(new xWebViewClientent());
  }
  class Listener implements OnClickListener {
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
      switch (v.getId()) {
      case R.id.video_landport:
        if (islandport) {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
          videolandport.setText (click to switch the horizontal screen if the button is not displayed in full screen);
        }else {
          setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
          videolandport.setText ("do not display this button in full screen, click to switch to vertical screen");
        }
        break;
      default:
        break;
      }
    }
  }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (inCustomView()) {
          hideCustomView();
          return true;
        }else {
        videowebview.loadUrl("about:blank");
//          mTestWebView.loadData("", "text/html; charset=UTF-8", null);
        MainActivity.this.finish();
          Log.i("testwebview", "===>>>2");
      }
      }
      return true;
    }
    /**
    *Judge whether it is full screen or not
    * @return
    */
    public boolean inCustomView() {
       return (xCustomView != null);
     }
     /**
     *When the screen is full, press the back plus key to exit the full screen
     */
     public void hideCustomView() {
       xwebchromeclient.onHideCustomView();
     }
  /**
   *Handle JavaScript dialog box, website icon, website title and page loading progress
   * @author
   */
  public class xWebChromeClient extends WebChromeClient {
    private Bitmap xdefaltvideo;
    private View xprogressvideo;
    @Override
    //Method that full screen will be called when playing network video
    public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
    {
      if (islandport) {
      }
      else{
//        ii = "1";
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      }
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      videowebview.setVisibility(View.GONE);
      //If a view already exists, terminate immediately and create a new one
      if (xCustomView != null) {
        callback.onCustomViewHidden();
        return;
      }      
      videoview.addView(view);
      xCustomView = view;
      xCustomViewCallback = callback;
      videoview.setVisibility(View.VISIBLE);
    }
    @Override
    //Video playback exit full screen will be called
    public void onHideCustomView() {
      If (xcustomview = = null) // not playing in full screen
        return;           
      // Hide the custom view.
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      xCustomView.setVisibility(View.GONE);
      // Remove the custom view from its container.
      videoview.removeView(xCustomView);
      xCustomView = null;
      videoview.setVisibility(View.GONE);
      xCustomViewCallback.onCustomViewHidden();
      videowebview.setVisibility(View.VISIBLE);
      //Log.i(LOGTAG, "set it to webVew");
    }
    //Add default icon for video loading
    @Override
    public Bitmap getDefaultVideoPoster() {
      //Log.i(LOGTAG, "here in on getDefaultVideoPoster"); 
      if (xdefaltvideo == null) {
        xdefaltvideo = BitmapFactory.decodeResource(
            getResources(), R.drawable.videoicon);
      }
      return xdefaltvideo;
    }
    //Process loading during video loading
    @Override
    public View getVideoLoadingProgressView() {
      //Log.i(LOGTAG, "here in on getVideoLoadingPregressView");
      if (xprogressvideo == null) {
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        xprogressvideo = inflater.inflate(R.layout.video_loading_progress, null);
      }
      return xprogressvideo;
    }
    //Page title
     @Override
     public void onReceivedTitle(WebView view, String title) {
      (MainActivity.this).setTitle(title);
     }
//     @Override
//// update window progress when WebView progress changes
//     public void onProgressChanged(WebView view, int newProgress) {
//       (MainActivity.this).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
//     }   
  }
  /**
   *Handle all kinds of notification, request and other events
   * @author
   */
  public class xWebViewClientent extends WebViewClient {
     @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Log.i("webviewtest", "shouldOverrideUrlLoading: "+url);
        return false;
      }
  }
  /**
   *This method is called when the horizontal and vertical screens are switched
   * @author
   */
  @Override
  public void onConfigurationChanged(Configuration newConfig) {
    Log.i("testwebview", "=====<<< onConfigurationChanged >>>=====");
     super.onConfigurationChanged(newConfig);
     if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
       Log. I ("WebView", "now horizontal screen 1");
       islandport = false;
      }else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
       Log. I ("WebView", "now vertical screen 1");
       islandport = true;
      }
  }
}

Finally AndroidManifest.xml set up;
Access to the network plus this sentence


<uses-permission android:name="android.permission.INTERNET"/>

When switching between horizontal and vertical screens, in order not to call oncreate and other methods again, add this sentence:

android:configChanges=”orientation|keyboardHidden|screenSize”

summary

The above is Xiaobian’s introduction to Android, which uses WebView to realize the function of full screen switching to play web video. I hope it can help you. If you have any questions, please leave me a message, Xiaobian will reply you in time!

Recommended Today

MySQL partition

MySQL partition Advantages of partitioning Store more data To optimize the query, only scan one or more necessary partitions. For count () and sum (), only summarize the partition statistics For data that is out of date or does not need to be saved, partitioning is faster Data queries are distributed across multiple disks to […]