Android Studio笔记之webview ——实现app本身打开网页而不跳转到其他浏览器(内置浏览器)

Android Studio笔记之webview

想要了解加载网页视频部分可以点击这里

基本语法

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

实战演练

1.加载本地html

项目结构
在这里插入图片描述注意路径写法
在这里插入图片描述

2.加载网络html

解决点击页面内链接提示打开浏览器问题
在这里插入图片描述
解决返回键退出activity问题
在这里插入图片描述
解决加载时进度条以及标题功能
在这里插入图片描述
使用js实现弹窗
在这里插入图片描述

另外注意在androidmanifest设置网络访问权限

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

以上对应的代码:

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;
                }*/


                String url = request.getUrl().toString();
                if (url.startsWith("http:") || url.startsWith("https:"))//加if是与scheme类的uri区分
                return false;//解决webview没法返回activity界面
                //这个地方我们实现打开其他app 如果你不写会报scheme错误
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;//这个地方写true


            }
        });
        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;
        }else {
            finish();
            return true;
        }
        /*if (keyCode == KeyEvent.KEYCODE_BACK && !webView.canGoBack()) {
            finish();
            return true;
        }*/
        /*return super.onKeyDown(keyCode,event);*/

    }
}
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页