Android Studio筆記之webview ——實現播放器全螢幕功能

2020-10-26 12:01:33

這篇文章已經解釋的非常好了
如何實現視訊全螢幕播放
我的程式碼:
webview:

package cn.edu.caztc.myapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

public class MyWebview extends AppCompatActivity {

    private WebView webView;
    private FrameLayout mLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_webview);

        webView = findViewById(R.id.wv_mywv);
        mLayout = findViewById(R.id.fl_video);

        WebSettings settings = webView.getSettings();

        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(true);
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setSupportZoom(true);
/*        settings.setJavaScriptCanOpenWindowsAutomatically(true);*/
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setGeolocationEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setUseWideViewPort(true); // 關鍵點
        settings.setAllowFileAccess(true); // 允許存取檔案
        settings.setSupportZoom(true); // 支援縮放
        settings.setLoadWithOverviewMode(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不載入快取內容
        webView.setVerticalScrollBarEnabled(false); // 取消Vertical ScrollBar顯示
        webView.setHorizontalScrollBarEnabled(false); // 取消Horizontal ScrollBar顯示
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);




        webView.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {


                String url = request.getUrl().toString();

                try {
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        view.loadUrl(url);
                    } else {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    }
                    return true;
                    /* return shouldOverrideUrlLoading(view, request.getUrl().toString());*/

                }catch (Exception e ){
                    return false;
                }

            }
        });
        webView.setWebChromeClient(new WebChromeClient(){
            private CustomViewCallback mCustomViewCallback;
            private View mCustomView;

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);

            }

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

/*    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    webView.setVisibility(View.GONE);*/
/*    super.onShowCustomView(view,callback);*/

                //如果view 已經存在,則隱藏
                if (mCustomView != null) {
                    callback.onCustomViewHidden();
                    return;
                }

                mCustomView = view;
                mCustomView.setVisibility(View.VISIBLE);
                mCustomViewCallback = callback;
                mLayout.addView(mCustomView);
                mLayout.setVisibility(View.VISIBLE);
                mLayout.bringToFront();


                //設定橫屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            }

            @Override
            public void onHideCustomView() {
                super.onHideCustomView();
                if (mCustomView == null) {
                    return;
                }
                mCustomView.setVisibility(View.GONE);
                mLayout.removeView(mCustomView);
                mCustomView = null;
                mLayout.setVisibility(View.GONE);
                try {
                    mCustomViewCallback.onCustomViewHidden();
                } catch (Exception e) {
                }
                /*webView.setVisibility(View.VISIBLE);*/
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//豎屏
            }




        });

        String uri=getIntent().getStringExtra("uri");
        /*webView.setWebViewClient(new WebViewClient());*/

                webView.loadUrl(uri);

    }
    //橫豎屏切換監聽
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
        webView = null;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
            startActivity(new Intent(MyWebview.this, Home.class));
            return true;
        }
        return super.onKeyDown(keyCode,event);

    }
}

layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyWebview"
    >

    <WebView
        android:id="@+id/wv_mywv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></WebView>

    <FrameLayout
        android:id="@+id/fl_video"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />


</androidx.constraintlayout.widget.ConstraintLayout>

home:

package cn.edu.caztc.myapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class Home extends AppCompatActivity {

    TextView tv_yinghua,tv_sili,tv_baidu,tv_bili;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        tv_yinghua = findViewById(R.id.tv_yinghua);
        tv_sili = findViewById(R.id.tv_sili);
        tv_baidu = findViewById(R.id.tv_baidu);
        tv_bili = findViewById(R.id.tv_bili);

        tv_yinghua.setOnClickListener(new MyOnclick("http://m.imomoe.ai/"));
        tv_sili.setOnClickListener(new MyOnclick("http://www.silisili.in/"));
        tv_baidu.setOnClickListener(new MyOnclick("https://www.baidu.com/"));
        tv_bili.setOnClickListener(new MyOnclick("https://www.bilibili.com/"));

        /*final Uri uri=Uri.parse("http://www.imomoe.ai/");
        tv_yinghua.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_VIEW,uri);

                startActivity(intent);
            }
        });*/


/*        tv_yinghua.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Home.this,MyWebview.class);
                //實現activity之間的傳值
                intent.putExtra("uri","http://m.imomoe.ai/");
                startActivity(intent);
            }
        });*/




    }

    class MyOnclick implements View.OnClickListener {

        String uri;

        MyOnclick(String uri){
            this.uri = uri;
        }

        @Override
        public void onClick(View v) {
            Intent intent=new Intent(Home.this,MyWebview.class);
            //實現activity之間的傳值
            intent.putExtra("uri",uri);
            startActivity(intent);
        }
    }
}

home的layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Home">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/sv03"
        android:scaleType="centerCrop"
        android:alpha="0.8"></ImageView>

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:padding="10dp"
        >
        <TableRow>
            <TextView
                android:id="@+id/tv_yinghua"
                android:layout_width="100dp"
                android:gravity="center"
                android:layout_height="35dp"
                android:layout_margin="20dp"
                android:text="櫻花動漫"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="@color/black"
                android:background="@drawable/pink_btn_t"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"

                ></TextView>

            <TextView
                android:padding="5dp"
                android:id="@+id/tv_sili"
                android:layout_width="100dp"
                android:gravity="center"
                android:layout_height="35dp"
                android:layout_margin="20dp"
                android:text="silisili"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="@color/black"
                android:background="@drawable/pink_btn_t"
                ></TextView>

            <TextView
                android:id="@+id/tv_baidu"
                android:layout_width="100dp"
                android:gravity="center"
                android:layout_height="35dp"
                android:layout_margin="20dp"
                android:text="百度"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="@color/black"
                android:background="@drawable/pink_btn_t"
                ></TextView>


        </TableRow>
        <TableRow
            >
            <TextView
                android:id="@+id/tv_bili"
                android:layout_width="100dp"
                android:gravity="center"
                android:layout_height="35dp"
                android:layout_margin="20dp"
                android:text="bilibili"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="@color/black"
                android:background="@drawable/pink_btn_t"
                ></TextView>
        </TableRow>
    </TableLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

以上。