PureTextActivity.java 15.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
package com.people.webview.protocol;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.people.webview.R;
import com.wd.capability.network.utils.NetworkUtil;
import com.wd.capability.router.data.ActionBean;
import com.wd.common.base.BaseActivity;
import com.wd.common.constant.RouterConstants;
import com.wd.foundation.wdkit.view.CustomTitleBar;
import com.wd.foundation.wdkit.view.DefaultView;
import com.wd.foundation.wdkit.constant.DefaultViewConstant;
import com.wd.foundation.wdkit.constant.IntentConstants;
import com.wd.foundation.wdkit.constant.ProtocolConstant;
import com.wd.foundation.wdkit.utils.SpUtils;
import com.wd.foundation.wdkitcore.tools.JsonUtils;
import com.wd.foundation.wdkitcore.tools.StringUtils;

import androidx.appcompat.app.AlertDialog;

/**
 * 协议Activity
 *
 * @author baozhaoxin
 * @version [V1.0.0, 2023/2/27]
 * @since V1.0.0
 */
@Route(path = RouterConstants.PATH_WEB_PROTOCOL)
public class PureTextActivity extends BaseActivity {

    /**
     * TAG
     */
    private static final String TAG = "PureTextActivity";

    /**
     * 标题
     */
    private CustomTitleBar titleBar;

    /**
     * 返回按钮
     */
    private ImageView backBtn;

    /**
     * 标题
     */
    private TextView mTitle;

    /**
     * webview
     */
    private WebView mWebView;

    /**
     * 配置
     */
    private WebSettings settings;

    /**
     * 进度条
     */
    private ProgressBar pb;

    /**
     * 跳转携带的数据
     */
    private JSONObject jsonObject;

    /**
     * 链接
     */
    private String webUrl = "";

    /**
     * web类型
     */
    private String webType = "";

    /**
     * 标题
     */
    private String titleStr;

    private String urlFinish;

    /**
     * 缺省页
     */
    private DefaultView defaultView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pure_text;
    }

    @Override
    protected String getTag() {
        return TAG;
    }

    @Override
    protected void initView() {
        titleBar = findViewById(R.id.title_bar);
        /*backBtn = findViewById(R.id.top_back);
        mTitle = findViewById(R.id.top_title);*/
        pb = findViewById(R.id.pb);
        mWebView = findViewById(R.id.webView);
        defaultView = findViewById(R.id.default_view);

        pb.setMax(100);
        pb.setProgress(0);
        initSettings();

        Object actionBeanObject = getExtrasSerializableObject();
        if (actionBeanObject == null) {
            return;
        }
        jsonObject = JsonUtils.convertJsonToObject(((ActionBean) actionBeanObject).paramBean.params, JSONObject.class);
    }

    @Override
    protected void initData() {
        clearCache();
        if(jsonObject != null){
            webUrl = jsonObject.getString(IntentConstants.WEBSITES_SEARCHURL);
            webType = jsonObject.getString(IntentConstants.TYPE_GUIDE_TO_PURE_TEXT);
        }
        if (NetworkUtil.isNetAvailable()){
            initLoadWebView();
        }else {
            mWebView.setVisibility(View.GONE);
            showDefaultView(defaultView, DefaultViewConstant.TYPE_NO_NETWORK);
        }
    }

    @Override
    public void retryBtnClickListener() {
        super.retryBtnClickListener();
        //重新加载刷新时隐藏缺省页
        if (NetworkUtil.isNetAvailable()){
            mWebView.setVisibility(View.VISIBLE);
            hideDefaultView();
            initLoadWebView();
        }
    }

    private void initLoadWebView(){
        if (!TextUtils.isEmpty(webType)){
            loadWebView();
        } else if (!TextUtils.isEmpty(webUrl)){
            mWebView.loadUrl(webUrl);
        }else {
            finish();
        }
    }

    @Override
    protected void initViewModel() {

    }

    /**
     * 初始化配置信息
     */
    private void initSettings(){
        settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setLoadsImagesAutomatically(true);
        settings.setAllowFileAccess(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        } else {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        saveData(settings);
        newWin(settings);
        mWebView.setWebChromeClient(webChromeClient);
        mWebView.setWebViewClient(webViewClient);

    }

    /**
     * clearCache
     */
    private void clearCache() {
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        mWebView.clearCache(true);
    }

    /**
     * HTML5数据存储
     */
    private void saveData(WebSettings mWebSettings) {
        //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            mWebSettings.setMediaPlaybackRequiresUserGesture(false);
        }

        mWebSettings.setAppCachePath(appCachePath);
    }

    /**
     * 多窗口的问题
     */
    private void newWin(WebSettings mWebSettings) {
        //html中的_bank标签就是新建窗口打开,有时会打不开,需要加以下
        //然后 复写 WebChromeClient的onCreateWindow方法
        mWebSettings.setSupportMultipleWindows(false);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);

    }

    WebViewClient webViewClient = new WebViewClient() {

        private String startUrl;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            startUrl = url;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            urlFinish = url;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                if (url.endsWith("@126.com")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    intent.addCategory("android.intent.category.BROWSABLE");
                    intent.setComponent(null);
                    intent.setSelector(null);
                    startActivity(intent);
                } else {
                    pb.setVisibility(View.VISIBLE);
                    if(startUrl!=null && startUrl.equals(url)){
                        view.loadUrl(url);
                    }else{
                        //交给系统处理
                        return super.shouldOverrideUrlLoading(view, url);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }

        /**
         * 当出行ssl错误时,Webview是默认取消加载当前页面的,只有去掉onReceivedSslError的默认操作,
         * 然后添加后添加SslErrorHandler.proceedceed()才能继续加载出错页面
         * 当Https传输出现SSL错误时,错误只会通过onReceivedSslError回调传过来
         * @param view
         * @param handler
         * @param error
         */
        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(PureTextActivity.this);
            builder.setMessage("ssl_cert_invalid");
            builder.setPositiveButton("continue", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.proceed();
                }
            });
            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    handler.cancel();
                }
            });
            final AlertDialog dialog = builder.create();
            dialog.show();
        }
    };

    WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (!TextUtils.isEmpty(webType)){
                return;
            }
            super.onReceivedTitle(view, title);
            if (TextUtils.isEmpty(titleStr)&&!TextUtils.isEmpty(title)) {
                titleBar.setTitle(title);
            }
        }

        //=========多窗口的问题==========================================================
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(mWebView);
            resultMsg.sendToTarget();
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress >= 100) {
                // 网页加载完成
                pb.setVisibility(View.GONE);
            } else {
                // 加载中
                pb.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    };

    @Override
    protected void onDestroy() {
        releaseWebView(mWebView);
        mWebView = null;
        super.onDestroy();
    }

    /**
     * 释放
     * @param mWebView
     */
    private void releaseWebView(WebView mWebView) {

        ViewParent parent = mWebView.getParent();
        if (parent != null) {
            ((ViewGroup) parent).removeView(mWebView);
        }
//        mWebView.getSettings().setJavaScriptEnabled(false);
        mWebView.stopLoading();
//        mWebView.clearHistory();
//        mWebView.clearView();
        mWebView.loadUrl("about:blank");
        mWebView.removeAllViews();
        mWebView.destroy();
    }

    /**
     * 加载webview
     */
    private void loadWebView() {
        switch (webType) {
            case ProtocolConstant.TYPE_PRIVACY_POLICY:
                //隐私政策
                webUrl = TextUtils.isEmpty(SpUtils.getPrivateAgreeUrl()) ? ProtocolConstant.private_policy_local
                        : SpUtils.getPrivateAgreeUrl();
                showWebView(" ");
                break;
            case ProtocolConstant.TYPE_TERMS_OF_SERVICE:
                //用户协议
                webUrl = TextUtils.isEmpty(SpUtils.getUserAgreeUrl()) ? ProtocolConstant.terms_of_use_local
                        : SpUtils.getUserAgreeUrl();
                showWebView(" ");
                break;
            case ProtocolConstant.TYPE_LOGOUT_OF_SERVICE:
                //注销协议
                webUrl = TextUtils.isEmpty(SpUtils.getLogoutAgreeUrl()) ? ProtocolConstant.LOGOUT_AGREEMENT_H5
                        : SpUtils.getLogoutAgreeUrl();
                showWebView(" ");
                break;
            case ProtocolConstant.TYPE_MESSAGE_BOARD_PRIVATE:
                //留言板-隐私协议
                webUrl = TextUtils.isEmpty(SpUtils.getMessageBoardPrivateUrl()) ?
                        ProtocolConstant.MESSAGE_BOARD_PRIVATE_URL
                        : SpUtils.getMessageBoardPrivateUrl();
                showWebView(" ");
                break;
            case ProtocolConstant.TYPE_MESSAGE_BOARD_USER:
                //留言板-用户协议
                webUrl = TextUtils.isEmpty(SpUtils.getMessageBoardUserUrl()) ?
                        ProtocolConstant.MESSAGE_BOARD_USER_URL
                        : SpUtils.getMessageBoardUserUrl();
                showWebView(" ");
                break;
            case ProtocolConstant.TYPE_MESSAGE_BOARD_PUBLISH:
                //留言板-发布提问规定
                webUrl = TextUtils.isEmpty(SpUtils.getMessageBoardPublishUrl()) ?
                        ProtocolConstant.MESSAGE_BOARD_PUBLISH_URL
                        : SpUtils.getMessageBoardPublishUrl();
                showWebView(" ");
                break;
            case SpUtils.PERSONAL_INFORMATION_OF_SERVICE:
                webUrl = TextUtils.isEmpty(SpUtils.getPersonalInformationUrl()) ?
                        ProtocolConstant.MESSAGE_PERSONAL_INFORMATION_URL
                        : SpUtils.getPersonalInformationUrl();
                showWebView(" ");
                break;
            case SpUtils.THIRD_INFORMATION_OF_SERVICE:
                webUrl = TextUtils.isEmpty(SpUtils.getThirdInformationUrl()) ?
                        ProtocolConstant.MESSAGE_THIRD_INFORMATION_URL
                        : SpUtils.getThirdInformationUrl();
                showWebView(" ");
                break;
            case SpUtils.PERMISSIONS_LIST_URL:
                //权限清单
                webUrl = TextUtils.isEmpty(SpUtils.getPermissionsListUrl()) ?
                        ProtocolConstant.PERMISSIONS_LIST_URL
                        : SpUtils.getPermissionsListUrl();
                showWebView(" ");
                break;
            default:
                showWebView(" ");
        }
    }



    /**
     * 显示
     * @param title
     */
    private void showWebView(String title) {
        if(StringUtils.isEmpty(webUrl)){
            finish();
        }
        if (!StringUtils.isEmpty(title)) {
            titleStr = title;
            titleBar.setTitle(title);
        }
        mWebView.loadUrl(webUrl);
    }

    @Override
    public void onLeftClick() {
        goBack();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 判断是否可以返回操作
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            goBack();
        }
        return false;
    }

    /**
     * 返回逻辑
     */
    private void goBack(){
        if(mWebView == null){
            return;
        }
        if(mWebView.canGoBack()){
            if(mWebView.getUrl().equals(webUrl)){
                finish();
            }else{
                if(webUrl.equals(urlFinish)){
                    finish();
                }else{
                    mWebView.goBack();
                }
            }
        }else {
            finish();
        }
    }
}