NewH5Activity.java 59.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package com.ydl.webview;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
11
import android.graphics.Color;
12 13 14 15 16 17 18 19 20 21 22
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
23

24 25 26 27 28
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
29
import com.tencent.smtt.sdk.CookieSyncManager;
30
import com.tencent.smtt.sdk.ValueCallback;
31 32 33 34
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
35 36
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
37
import com.ydl.utils.PopUtils;
YKai committed
38
import com.ydl.utils.ProxyCheckUtils;
39
import com.ydl.utils.WebUrlParamsUtils;
40
import com.ydl.view.ArticleDialogFragment;
范玉宾 committed
41
import com.ydl.view.ShareMeditationDialog;
42 43 44
import com.ydl.ydl_router.manager.YDLRouterManager;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.base.BaseApp;
范玉宾 committed
45
import com.ydl.ydlcommon.bean.ShareData;
46
import com.ydl.ydlcommon.bean.StatusBarOptions;
范玉宾 committed
47
import com.ydl.ydlcommon.event.MeditationEvent;
徐健 committed
48
import com.ydl.ydlcommon.modular.ModularServiceManager;
49
import com.ydl.ydlcommon.ui.LogoLoadingView;
徐健 committed
50
import com.ydl.ydlcommon.utils.ActivityManager;
51 52 53 54 55
import com.ydl.ydlcommon.utils.BuryPointUtils;
import com.ydl.ydlcommon.utils.LogUtil;
import com.ydl.ydlcommon.utils.NetWorkSpeedUtils;
import com.ydl.ydlcommon.utils.StatusBarUtils;
import com.ydl.ydlcommon.utils.URLUtils;
56
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils;
57
import com.ydl.ydlcommon.utils.log.AliYunLogConfig;
58
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper;
59
import com.ydl.ydlcommon.view.TitleBar;
徐健 committed
60
import com.ydl.ydlcommon.view.dialog.YDLCommonDialog;
61 62 63 64
import com.ydl.ydlcommon.view.dialog.YDLShareDialog;
import com.yidianling.common.tools.RxDeviceTool;
import com.yidianling.common.tools.RxImageTool;
import com.yidianling.common.tools.ToastUtil;
65
import com.yidianling.dynamic.api.IDynamicService;
konghaorui committed
66
import com.yidianling.user.api.event.UserBindPhoneEvent;
67
import com.yidianling.user.api.event.UserLoginEvent;
徐健 committed
68
import com.yidianling.user.api.service.IAppService;
69

70 71 72 73 74 75 76 77 78
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

79 80 81 82 83 84 85 86
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

87 88 89 90 91 92 93
import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * 通用h5显示页面
 * 跳转此h5页面,请使用唯一参数 H5ParamsBaseActivity
 */
94
@Route(path = "/new_h5/h5")
95 96 97
public class NewH5Activity extends BaseActivity implements PtrHandler {

    public static final String PARAMS = "h5Params";
98
    /*** 路由传递过来的参数*/
99 100
    public static final String ROUTER_PARAMS = "routerParam";

101
    /***下单选择时间请求吗*/
102 103
    public static final int ORDER_TIME_REQUEST_CODE = 110;

104 105 106
    /***启动类型  0正常模式 1从下至上打开页面*/
    private int startType = 0;
    /***右侧按钮文字*/
107 108 109
    private String rightText = "";

    protected TitleBar tb_title;
徐健 committed
110
    protected View tb_title_cover_v;
111 112 113 114
    protected ImageView backgroundView;
    protected ProgressWebView wv_content;
    protected PtrFrameLayout store_house_ptr_frame;
    protected SafeTipView safeTipView;
115
    /***接收参数*/
116
    private H5Params h5Params;
117 118
    /***分享到发布需要的url*/
    protected String purl;
119 120 121 122
    protected String shareUrl;
    protected String shareTitle;
    protected String shareDesc;
    private String cover;
123 124
    private String miniId;
    private String miniPath;
范玉宾 committed
125 126
//    评价2.0新增字段  区分评价列表
    private H5JsBean.H5JsCmd.Params paramsForCommentList;
127
    private boolean isShareCommentList;
128

范玉宾 committed
129 130 131
    private boolean isDarkMode = false;

    private ShareMeditationDialog shareMeditationDialog;
范玉宾 committed
132
    private ArticleDialogFragment commentArticleDialog;
范玉宾 committed
133

134 135 136 137 138
    protected PopupWindow popupWindow;

    protected ValueCallback<Uri> uploadMessage;
    protected ValueCallback<Uri[]> uploadMessageAboveL;
    private boolean shouldClearHistory = false;
139
    /***要分享出去的url*/
140
    private String shareToUrl;
141
    /*** 拍照/选择文件请求码*/
142 143 144 145 146 147 148
    protected final static int FILE_CHOOSER_RESULT_CODE = 10000;

    protected IJavascriptHandler jtoJHandle;
    private boolean loadFailed;

    private LinearLayout llWebView;

149 150 151 152 153 154 155 156
    /***加载url开始的时间*/
    private long loadStartTime = 0;
    /***webview初始化开始的时间*/
    private long initStartTime = 0;
    /***webview初始化耗时*/
    private long initDuration = 0;
    /***加载url耗时*/
    private long loadDuration = 0;
157
    private NetWorkSpeedUtils workSpeedUtils;
158 159 160
    /***部分机型中webview加载完成回调方法会调用多次,增加本地标识符*/
    private boolean hasLoad = false;
    /***是否跳转到动态*/
161 162 163
    private boolean isToTrend = false;

    private LogoLoadingView v_loading;
164 165 166 167 168 169 170 171 172 173 174 175
    /***是否超时*/
    private boolean isTimeOut = false;
    /***超时处理handler*/
    private Handler mTimeOutHandler = null;
    /***超时限定时间*/
    private int timeOutLong = 15000;
    /***超时消息*/
    private int TIME_OUT_TYPE = 0x1000;
    /**
     * 设置微信 H5 支付调用 loadDataWithBaseURL 的标记位,避免循环调用,
     * 再次进入微信 H5 支付流程时记得重置此标记位状态
     */
176 177 178
    boolean firstVisitWXH5PayUrl = true;
    private String WX_H5_PAY_HOST = "http://testnewm.ydl.com";

179
    /*** 当前页面类型*/
徐健 committed
180
    private int selfPageType = -1;
181 182
    /***测评题页面*/
    private int TEST_QUESTIONS_PAGE_TYPE = 1000001;
徐健 committed
183 184

    private YDLCommonDialog testQuestionsPageReturnDialog = null;
185 186 187 188
    /*** 标题栏是否被覆盖隐藏*/
    private boolean isTitleBarCover = false;
    private static IWebRightClickListener webRightClickListener = null;

徐健 committed
189 190 191 192 193 194 195 196 197 198 199
    /**
     * 设置当前h5页面类型
     *
     * @param pageType
     */
    public void setSelfPageType(int pageType) {
        selfPageType = pageType;

        // 如果是测试题页面
        if (selfPageType == TEST_QUESTIONS_PAGE_TYPE) {
            if (null != tb_title) {
徐健 committed
200
                tb_title.setImageListener(v -> {
徐健 committed
201 202 203
                    if (!isTitleBarCover) {
                        showTestQuestionPageReturnDialog();
                    }
徐健 committed
204 205
                });
                tb_title.setOnLeftTextClick((view, isActive) -> {
徐健 committed
206 207 208
                    if (!isTitleBarCover) {
                        showTestQuestionPageReturnDialog();
                    }
徐健 committed
209 210 211 212
                });
            }
        }
    }
213 214 215 216 217

    public static void start(Context context, H5Params h5Params1) {
        if (null == context) {
            return;
        }
218

219 220 221 222 223 224 225 226
        Intent intent = new Intent(context, NewH5Activity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(PARAMS, h5Params1);
        context.startActivity(intent);
    }

227
    public static void start(Context context, H5Params h5Params1, String rightText, IWebRightClickListener listener) {
konghaorui committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        if (null == context) {
            return;
        }

        webRightClickListener = listener;

        Intent intent = new Intent(context, NewH5Activity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra("rightText", rightText);
        intent.putExtra(PARAMS, h5Params1);
        context.startActivity(intent);
    }

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
    public static void start(Context context, H5Params h5Params, TellData tellData) {
        if (null == context) {
            return;
        }
        Intent intent = new Intent(context, NewH5Activity.class);
        intent.putExtra(PARAMS, h5Params);
        intent.putExtra("tell_data", tellData);
        context.startActivity(intent);
    }

    public static void start(Activity context, H5Params h5Params1, int startType, String rightText) {
        if (null == context) {
            return;
        }
        Intent intent = new Intent(context, NewH5Activity.class);
        intent.putExtra("startType", startType);
        intent.putExtra("rightText", rightText);
        intent.putExtra(PARAMS, h5Params1);
        context.startActivity(intent);

    }

    public static void startForResult(Activity context, H5Params h5Params1, int requestCode) {
        if (null == context) {
            return;
        }
269 270 271

        WebModularServiceUtils.Companion.getUserService().isLogin();

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        Intent intent = new Intent(context, NewH5Activity.class);
        intent.putExtra(PARAMS, h5Params1);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startForResult(Activity context, H5Params h5Params1, int requestCode, int startType, String rightText) {
        if (null == context) {
            return;
        }
        Intent intent = new Intent(context, NewH5Activity.class);
        intent.putExtra(PARAMS, h5Params1);
        intent.putExtra("startType", startType);
        intent.putExtra("rightText", rightText);
        context.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int layoutResId() {
konghaorui committed
290
        return R.layout.web_activity_h5_new;
291 292 293 294 295 296 297 298
    }

    public String successPage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        initStartTime = System.currentTimeMillis();
        super.onCreate(savedInstanceState);
konghaorui committed
299
        overridePendingTransition(R.anim.platform_activity_anim_in,
konghaorui committed
300
                R.anim.platform_activity_anim_out);
301 302
    }

范玉宾 committed
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    private void initTimeOutHandler() {
        mTimeOutHandler = new Handler(msg -> {
            if (wv_content.getProgress() < 100) {
                isTimeOut = true;

                llWebView.setVisibility(View.GONE);
                v_loading.setVisibility(View.VISIBLE);
                v_loading.setViewType(LogoLoadingView.TYPE_NET_LOSS, null);
            }
            return false;
        });
        sendNetLossMessage();
    }

    /**
     * 15秒后发送一条消息通知展示无网络页面
     */
    private void sendNetLossMessage() {
322
        if (null != mTimeOutHandler) {
323
            mTimeOutHandler.sendEmptyMessageDelayed(TIME_OUT_TYPE, timeOutLong);
324
        }
325 326 327 328 329 330
    }

    /**
     * 取消预定15秒后发送的消息
     */
    private void cancelSendNetLossMessage() {
331 332 333
        if (null != mTimeOutHandler) {
            mTimeOutHandler.removeMessages(TIME_OUT_TYPE);
        }
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
    }

    private void initLoadingView() {
        wv_content.setBackgroundColor(0);
        wv_content.getBackground().setAlpha(0);
        v_loading = findViewById(R.id.v_loading);
        v_loading.setListener(new LogoLoadingView.LogoLoadingListener() {
            @Override
            public void onDataResetClick() {
                sendNetLossMessage();
                isTimeOut = false;
                llWebView.setVisibility(View.VISIBLE);
                v_loading.setVisibility(View.VISIBLE);
                v_loading.setViewType(LogoLoadingView.TYPE_LOADING, null);

                loadUrl(h5Params.getUrl());
                shouldClearHistory = true;
            }

            @Override
            public void onBackClick() {
                finish();
            }
        });
    }

    private void getParam() {
        if (null != getIntent()) {
            //正常获取入参
            h5Params = (H5Params) getIntent().getSerializableExtra(PARAMS);
            //路由传递的入参
            if (getIntent().hasExtra(ROUTER_PARAMS)) {
                String json = getIntent().getStringExtra(ROUTER_PARAMS);
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    h5Params = new H5Params(jsonObject.getString("url"), "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
380
        return new StatusBarOptions(true, true);
381 382 383 384 385 386 387 388 389 390
    }

    @Override
    protected void initDataAndEvent() {
        getParam();
        TellData tellData = (TellData) getIntent().getSerializableExtra("tell_data");
        if (tellData == null) {
            tellData = new TellData();
        }
        initView();
YKai committed
391 392 393 394
        if (!BaseApp.instance.getGlobalConfig().getAppDebug()&& ProxyCheckUtils.INSTANCE.isWifiProxy(this)){
            ToastUtil.toastShort("网络设置错误");
            return;
        }
395 396 397 398
        startType = getIntent().getIntExtra("startType", 0);
        rightText = getIntent().getStringExtra("rightText");
        if (h5Params == null) {
            ToastUtil.toastShort("参数错误");
399
            AliYunRichLogsHelper.Companion.getInstance().sendRichLog(AliYunLogConfig.WEB, "参数错误 Params == null");
400 401 402
            finish();
            return;
        }
YKai committed
403

404 405
        setUrlHeightParams();
        EventBus.getDefault().register(this);
406
        jtoJHandle = WebModularServiceUtils.Companion.getWebService().getJavascripHandler(this, wv_content, tellData);
407 408 409 410 411 412 413 414 415

        init();
        if (startType == 1) {
            tb_title.setImageVis(0);
            tb_title.setLeftTextVisible(View.GONE);
            tb_title.setmRightText(rightText);
            tb_title.setOnRightTextClick((view, isActive) -> {
                finish();
            });
416
        } else if (!TextUtils.isEmpty(rightText) && webRightClickListener != null) {
konghaorui committed
417 418 419 420
            tb_title.setmRightText(rightText);
            tb_title.setOnRightTextClick((view, isActive) -> {
                webRightClickListener.onCLick(view);
            });
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
        }
        llWebView = findViewById(R.id.ll_web_view);
        initLoadingView();
        initTimeOutHandler();
    }

    /**
     * 专家详情页改版 需要url后面拼接状态栏高度 并且隐藏导航栏
     */
    private void setUrlHeightParams() {
        String url = h5Params.getUrl();
        //兼容课程详情页url
        if (!TextUtils.isEmpty(url) && url.contains("course/Detail/") && !url.contains("course/Detail/v2/")) {
            url = url.replace("course/Detail/", "course/Detail/v2/");

            //再次替换  方哥那边解决不了域名的问题 app中强行匹配修改
            if (url.contains("fe-app-yidianling")) {
                int index = url.indexOf("course/Detail");
                String newUrl = url.substring(index, url.length());
                if (url.contains("test")) {
                    newUrl = "https://testnewm.ydl.com/" + newUrl;
                } else {
                    newUrl = "https://m.ydl.com/" + newUrl;
                }
                url = newUrl;
            }
        }

        url = pinjie(url);
        h5Params.setUrl(url);
    }

    /**
     * 专家详情页改版 需要url后面拼接状态栏高度 并且隐藏导航栏
     *
     * @param url
     * @return
     */
    private String setUrlHeightParams(String url) {
        String resultUrl = url;
        try {
            Uri uri = Uri.parse(url);
            String host = uri.getHost();
464
            if (!TextUtils.isEmpty(host) && host.contains("nodeapi.ydl")) {
465
                //马亮的需求,在nodeapi.ydl.com 地址后面拼上公共参数,用于判断是否为app
466
                String uriAppendSuffix = jtoJHandle.getUriAppendSuffix();
467
                resultUrl = WebUrlParamsUtils.getSuffix(url, uriAppendSuffix);
468 469 470 471 472 473 474
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pinjie(resultUrl);
    }

475 476
    private String pinjie(String jumpUrl) {
        if (jumpUrl.contains("hideNavBar=1")) {
477 478
            hideJavaTitleBar();
            return jumpUrl;
479
        } else if (jumpUrl.contains("hideNavBar=2")) {
480 481 482 483 484
            showTitleBar();
            return jumpUrl;
        }
        String useUrl = new StringBuffer().append(jumpUrl).toString();
        Resources res = getResources();
konghaorui committed
485
        String[] doctorUrlArray = res.getStringArray(R.array.platform_doctorUrls);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
        for (String url : doctorUrlArray) {
            if (useUrl.contains(url)) {
                String lastUrl = useUrl.replaceAll(url, "");
                if (lastUrl.contains("?")) {
                    lastUrl = lastUrl.substring(0, lastUrl.indexOf("?"));
                }
                try {
                    //不报错就说明可以转成long,就说明是专家详情页地址
                    Long.parseLong(lastUrl);
                    if (!lastUrl.contains("/")) {
                        if (useUrl.endsWith("?")) {
                            useUrl = useUrl.substring(0, useUrl.indexOf("?"));
                        }
                        if (!useUrl.contains("barHeight")) {
                            String paramsStr = useUrl.contains("?")
                                    ? "&barHeight=" + String.valueOf(StatusBarUtils.Companion.getStatusBarHeight(NewH5Activity.this))
                                    : "?barHeight=" + String.valueOf(StatusBarUtils.Companion.getStatusBarHeight(NewH5Activity.this));
                            useUrl = new StringBuffer().append(useUrl).append(paramsStr).toString();
                        }
                        hideJavaTitleBar();
                    }
                } catch (NumberFormatException e) {
508
                    e.printStackTrace();
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
                }
            }
        }
        return useUrl;
    }

    public void hasShowDownRefresh(boolean isVisible) {
        store_house_ptr_frame.post(() -> store_house_ptr_frame.setEnabled(isVisible));
    }

    public void refresh() {
        store_house_ptr_frame.autoRefresh();
    }

    public void showShareMenu(H5JsBean.H5JsCmd.Params params) {
        LogUtil.d("showShareMenu");
        if (params.getShare() != null) {
            LogUtil.d("params.getShare() not null");
            purl = params.getShare().getUrl();
            shareUrl = params.getShare().getShare_url();
            shareTitle = params.getShare().getTitle();
            shareDesc = params.getShare().getDesc();
            cover = params.getShare().getCover();
范玉宾 committed
532
            paramsForCommentList = params;
533 534 535 536 537 538 539
            LogUtil.d("title: " + shareTitle + " url: " + shareUrl + " desc: " + shareDesc + " cover: " + cover);
            new Handler(getMainLooper()).post(() -> initShareMenu());
        }
    }

    public void openRightTopMenu() {
        popupWindow = PopUtils.showMoreItem(this,
540
                tb_title.getRootView(), jtoJHandle);
541 542 543 544
    }

    public void openShareMenu(H5JsBean.H5JsCmd.Params params) {
        if (params.getShare() != null) {
545
            if ("Meditation".equals(params.getShare().getType())){
范玉宾 committed
546 547 548 549
                shareUrl = params.getShare().getShare_url();
                shareTitle = params.getShare().getTitle();
                shareDesc = params.getShare().getDesc();
                cover = params.getShare().getCover();
550 551
                miniId = params.getShare().getMinProgramId();
                miniPath = params.getShare().getMinProgramPath();
范玉宾 committed
552
                isDarkMode = params.getShare().isDarkMode();
范玉宾 committed
553
                if (shareMeditationDialog == null) {
范玉宾 committed
554
                    shareMeditationDialog = ShareMeditationDialog.Companion.newInstance(isDarkMode,
范玉宾 committed
555
                            shareUrl, shareTitle, shareDesc, cover, miniId, miniPath);
范玉宾 committed
556
                }
范玉宾 committed
557 558
                if (shareMeditationDialog != null && !shareMeditationDialog.isAdded()) {
                    shareMeditationDialog.show(getSupportFragmentManager(), "share_meditation");
范玉宾 committed
559
                }
560
            }else {
范玉宾 committed
561 562 563 564 565 566 567 568 569
                purl = params.getShare().getUrl();
                shareUrl = params.getShare().getShare_url();
                shareTitle = params.getShare().getTitle();
                shareDesc = params.getShare().getDesc();
                cover = params.getShare().getCover();
                LogUtil.d("title: " + shareTitle + " url: " + shareUrl + " desc: " + shareDesc + " cover: " + cover);
                String base64DataStr = params.getImageBase64();
                share(base64DataStr, params);
            }
570 571 572 573 574 575
        }
    }


    private void initView() {
        tb_title = (TitleBar) findViewById(R.id.tb_title);
徐健 committed
576
        tb_title_cover_v = (View) findViewById(R.id.tb_title_cover_v);
konghaorui committed
577
        tb_title.setPaddingLeft(10);
578 579 580 581 582 583 584 585 586 587 588 589 590 591
        wv_content = (ProgressWebView) findViewById(R.id.wv_content);
        backgroundView = findViewById(R.id.iv_background);
        store_house_ptr_frame = (PtrFrameLayout) findViewById(R.id.store_house_ptr_frame);
        safeTipView = (SafeTipView) findViewById(R.id.safe_tip_view);

        if (h5Params != null && h5Params.isControlBack()) {
            store_house_ptr_frame.setEnabled(false);
        } else {
            store_house_ptr_frame.setEnabled(true);
        }
    }

    //js修改UI的操作需要放在UI线程中更新
    public void hideJavaTitleBar() {
徐健 committed
592 593 594
        runOnUiThread(() -> {
            tb_title.setVisibility(View.GONE);
            if (null != getStatusView()) {
徐健 committed
595 596 597 598 599
                if (selfPageType == TEST_QUESTIONS_PAGE_TYPE) {
                    //测评题隐藏标题的时候,不隐藏状态栏
                } else {
                    getStatusView().setVisibility(View.GONE);
                }
徐健 committed
600 601
            }
        });
602 603
    }

604 605 606 607 608 609
    public void setBottomViewColor(String color) {
        runOnUiThread(() -> {
            setBottomColor(color);
        });
    }

610
    public void showTitleBar() {
徐健 committed
611 612 613 614 615 616
        runOnUiThread(() -> {
            tb_title.setVisibility(VISIBLE);
            if (null != getStatusView()) {
                getStatusView().setVisibility(VISIBLE);
            }
        });
617 618
    }

徐健 committed
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    //js修改UI的操作需要放在UI线程中更新,覆盖标题
    public void coverJavaTitleBar() {
        isTitleBarCover = true;
        runOnUiThread(() -> {
            tb_title_cover_v.setVisibility(VISIBLE);
        });
    }

    public void notCoverTitleBar() {
        isTitleBarCover = false;
        runOnUiThread(() -> {
            tb_title_cover_v.setVisibility(GONE);
        });
    }

634 635 636 637 638 639 640 641 642 643 644
    public void closeWebKit() {
        finish();
    }

    @SuppressLint({"WrongConstant", "AddJavascriptInterface", "SetJavaScriptEnabled"})
    void init() {
        final Intent intent = getIntent();
        purl = intent.getStringExtra("purl");
        //要加"more"按钮
        if (h5Params.isShowMenu()) {
            tb_title.setRightImageListener(v -> popupWindow = PopUtils.showMoreItem(this,
645
                    tb_title.getRootView(), jtoJHandle));
646 647 648 649 650 651 652 653 654 655 656 657 658 659
            tb_title.setRightImageIfShouldSee();
        } else {
            tb_title.setRightImageIfNoSee();
        }
        if (h5Params.getShareData() != null && h5Params.getShareData().getShare_url() != null) {
            shareUrl = h5Params.getShareData().getShare_url();
            shareTitle = h5Params.getShareData().getTitle();
            shareDesc = h5Params.getShareData().getDesc();
            cover = h5Params.getShareData().getCover();
            initShareMenu();
        }
        if (!TextUtils.isEmpty(h5Params.getTitle()) && !h5Params.getShowUrlTitle()) {
            tb_title.setTitle(h5Params.getTitle());
        }
660
        tb_title.setImage(getResources().getDrawable(R.drawable.web_common_back));
661 662

        WebSettings setting = wv_content.getSettings();
663 664 665 666
        //支持js
        setting.setJavaScriptEnabled(true);
        //设置字符编码
        setting.setDefaultTextEncodingName("GBK");
667 668 669 670 671 672
        setting.setDomStorageEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        setting.setAppCachePath(appCachePath);
        setting.setAllowFileAccessFromFileURLs(true);
        setting.setAppCacheEnabled(true);
        setting.setAllowFileAccess(true);
673 674
        // 解决图片不显示
        setting.setBlockNetworkImage(false);
675 676 677 678 679 680 681 682 683 684 685 686 687
        //设置自动缩放 degmi的测试题不能设置 不然界面展示有问题
        if (h5Params.getUrl().contains("l.yidianling.com") || h5Params.getUrl().contains("l.ydl.com")) {
            //l.yidianling.com 这个域名 只有云凤蝶使用 这个平台需要设置自适应 不然显示有问题
            setting.setUseWideViewPort(true);
            setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            setting.setLoadWithOverviewMode(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.setMixedContentMode(WebSettings.LOAD_NORMAL);
        }
        wv_content.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//滚动条风格,为0指滚动条不占用空间,直接覆盖在网页上
        tb_title.setImageListener(v -> {
            if (h5Params.isSplash()) {
688
                WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
689 690
                finish();

691
            } else {
徐健 committed
692 693 694
                if (ActivityManager.Companion.getInstance().getActivitys().size() == 1) {
                    WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
                }
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
                finish();
            }
        });
        if (startType != 1) {
            tb_title.setImageVis(1);
        }
        wv_content.addJavascriptInterface(jtoJHandle, "javascriptHandler");
        //noinspection unused
        wv_content.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                return super.onJsAlert(webView, s, s1, jsResult);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    wv_content.getProgressbar().setVisibility(GONE);
                } else {
715
                    if (wv_content.getProgressbar().getVisibility() == GONE) {
716
                        wv_content.getProgressbar().setVisibility(VISIBLE);
717
                    }
718 719 720 721 722 723 724 725
                    wv_content.getProgressbar().setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
YKai committed
726 727 728
                if (TextUtils.isEmpty(h5Params.getTitle())){
                    tb_title.setTitle(title);
                }
729 730 731 732 733 734
                wv_content.setTitle(title);
                if ("我的订单".equals(title)) {
                    safeTipView.setVisibility(View.VISIBLE);
                    safeTipView.updateVisibility();
                    safeTipView.setLocation("orderList");
                }
735
                if (title.contains("404") || title.contains("500") || title.contains("Error")) {
736 737
                    AliYunRichLogsHelper.Companion.getInstance()
                            .sendRichLog(AliYunLogConfig.WEB, "页面错误 : url:" + view.getUrl() + "title:" + title);
738
                }
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
754
            @Override
755 756 757 758 759 760
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
761
            @Override
762 763 764 765 766 767 768 769 770 771 772 773 774 775
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });


        if (h5Params.getShowUrlTitle()) {
            wv_content.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Boolean overridePayUrl = shouldOverridePayUrl(view, url);
776
                    if (overridePayUrl != null) {
777 778
                        return overridePayUrl;
                    }
779

780
                    if (!TextUtils.isEmpty(url) && url.endsWith(".apk")) {
781 782
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
783 784 785
                    } else if (url.startsWith("tel://")){
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
786
                    } else if (!TextUtils.isEmpty(url) && url.startsWith("http")) {
787
                        loadUrl(setUrlHeightParams(url));
788
                    } else {
789
                        if (!YDLRouterManager.Companion.router(url)) {
790 791 792
                            loadUrl(setUrlHeightParams(url));
                        }
                    }
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
                    return true;
                }


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

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (!hasLoad) {
                        hasLoad = true;
                        loadDuration = System.currentTimeMillis() - loadStartTime;
                        LogUtil.e("initDuration:" + initDuration + ",loadDuration:" + loadDuration);
//                        UploadWebViewTimeUtils.Companion.uploadWebViewTime(h5Params.getUrl(), initDuration + "", loadDuration + "", workSpeedUtils.getNetSpeed());
                    }

                    if (shouldClearHistory) {
                        wv_content.clearHistory();
                        shouldClearHistory = false;
                    }
                    back("top");

                    if (!loadFailed) {
                        v_loading.setVisibility(View.GONE);
                    }

                    cancelSendNetLossMessage();
                }

                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                    onReceivedSslErrorHandle(handler);
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    super.onReceivedError(view, errorCode, description, failingUrl);
832 833
                    AliYunRichLogsHelper.Companion.getInstance()
                            .sendRichLog(AliYunLogConfig.WEB, "onReceivedError---- errorCode: " + errorCode + "----failingUrl:" + failingUrl);
834
                    LogUtil.e("webviewErrorCode:" + errorCode + "description:" + description);
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
                    loadFailed = true;
                    tb_title.setTitle("加载中");
                    if (wv_content != null) {
                        wv_content.loadDataWithBaseURL(null, "<!doctype html>\n" +
                                "<html>\n" +
                                "<head>\n" +
                                "<meta charset=\"utf-8\">\n" +
                                "<title></title>\n" +
                                "</head>\n" +
                                "\n" +
                                "<body>\n" +
                                "\t<p></p>\n" +
                                "</body>\n" +
                                "<ml>", "text/html", "utf-8", null);
                    }

                    llWebView.setVisibility(View.GONE);
                    v_loading.setVisibility(View.VISIBLE);
                    v_loading.setViewType(LogoLoadingView.TYPE_NET_LOSS, "哎呦,网络开小差了");
                }
            });
        } else {
            wv_content.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Boolean overridePayUrl = shouldOverridePayUrl(view, url);
862
                    if (overridePayUrl != null) {
863 864 865
                        return overridePayUrl;
                    }

866
                    if (!TextUtils.isEmpty(url) && url.endsWith(".apk")) {
867 868
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
869 870 871 872 873
                    }else if (url.startsWith("tel://")){
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    }
                    else if (!TextUtils.isEmpty(url) && url.startsWith("http")) {
874
                        loadUrl(setUrlHeightParams(url));
875
                    } else {
876
                        if (!YDLRouterManager.Companion.router(url)) {
877 878
                            loadUrl(setUrlHeightParams(url));
                        }
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
                    }
                    return true;
                }

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

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (!hasLoad) {
                        hasLoad = true;
                        loadDuration = System.currentTimeMillis() - loadStartTime;
                        LogUtil.e("initDuration:" + initDuration + ",loadDuration:" + loadDuration);
                        //UploadWebViewTimeUtils.Companion.uploadWebViewTime(h5Params.getUrl(), initDuration + "", loadDuration + "", workSpeedUtils.getNetSpeed());
                    }

                    if (shouldClearHistory) {
                        wv_content.clearHistory();
                        shouldClearHistory = false;
                    }
                    if (wv_content.canGoBack()) {
                        setTitle(wv_content.getTitle());
                        tb_title.setmLeftText("关闭");
                        tb_title.setImageListener(v -> {
                            if (wv_content.canGoBack()) {
                                wv_content.goBack();
907
                            } else {
908 909 910 911 912 913 914
                                finish();
                            }
                        });
                        if (startType != 1) {
                            tb_title.setImageVis(1);
                        }
                    } else {
915
                        tb_title.setImage(getResources().getDrawable(R.drawable.web_common_back));
916 917 918
                        tb_title.setmLeftText("");
                        tb_title.setImageListener(v -> {
                            if (h5Params.getShowUrlTitle()) {
919
                                WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
920
                                finish();
921
                            } else {
徐健 committed
922 923 924
                                if (ActivityManager.Companion.getInstance().getActivitys().size() == 1) {
                                    WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
                                }
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
                                finish();
                            }
                        });
                        if (startType != 1) {
                            tb_title.setImageVis(1);
                        }
                    }

                    if (!loadFailed) {
                        v_loading.setVisibility(View.GONE);
                    }

                    cancelSendNetLossMessage();
                }

                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                    onReceivedSslErrorHandle(handler);
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    super.onReceivedError(view, errorCode, description, failingUrl);
948 949
                    AliYunRichLogsHelper.Companion.getInstance()
                            .sendRichLog(AliYunLogConfig.WEB, "onReceivedError---- errorCode: " + errorCode + "----failingUrl:" + failingUrl);
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
                    tb_title.setTitle("加载中");
                    loadFailed = true;
                    if (wv_content != null) {
                        wv_content.loadDataWithBaseURL(null, "<!doctype html>\n" +
                                "<html>\n" +
                                "<head>\n" +
                                "<meta charset=\"utf-8\">\n" +
                                "<title></title>\n" +
                                "</head>\n" +
                                "\n" +
                                "<body>\n" +
                                "\t<p></p>\n" +
                                "</body>\n" +
                                "<ml>", "text/html", "utf-8", null);
                    }
                    llWebView.setVisibility(View.GONE);
                    v_loading.setVisibility(View.VISIBLE);
                    v_loading.setViewType(LogoLoadingView.TYPE_NET_LOSS, "哎呦,网络开小差了");
                }
            });
        }
        wv_content.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
972
            if (url != null && url.startsWith("http://")) {
973
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
974
            }
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
        });
        initDuration = System.currentTimeMillis() - initStartTime;
        workSpeedUtils = new NetWorkSpeedUtils(this);
        workSpeedUtils.startNetSpeed();
        loadStartTime = System.currentTimeMillis();
        loadUrl(h5Params.getUrl());
        LogUtil.d(h5Params.getUrl());
        initHead();

    }

    private Boolean shouldOverridePayUrl(WebView view, String url) {
        if (url.startsWith("weixin://")) {
            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } catch (Exception e) {
                // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                ToastUtil.toastShort("该手机没有安装微信");
                return true;
            }
        } else if (url.startsWith("alipays://") || url.startsWith("alipay")) {
997
            try {
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } catch (Exception e) {
                // 防止手机没有安装处理某个 scheme 开头的 url 的 APP 导致 crash
                // 启动支付宝 App 失败,会自行跳转支付宝网页支付
                return true;
            }
        }

        // 处理普通 http 请求跳转
//        if (!(url.startsWith("http") || url.startsWith("https"))) {
//            return true;
//        }

        // 处理微信 H5 支付跳转时验证请求头 referer 失效
        // 验证不通过会出现“商家参数格式有误,请联系商家解决”
1014
        if (url.contains("wx.tenpay.com")) {
1015 1016 1017 1018 1019 1020 1021 1022

            // 申请微信 H5 支付时填写的域名
            // 比如经常用来测试网络连通性的 http://www.baidu.com
            Uri parse = Uri.parse(url);
            //从url 中获取 域名信息
            String redirectUrlStr = parse.getQueryParameter("redirect_url");
            Uri redirectUrl = Uri.parse(redirectUrlStr);
            // 申请微信 H5 支付时填写的域名
1023
            String referer = redirectUrl.getScheme() + "://" + redirectUrl.getHost();
1024 1025 1026 1027

            // 兼容 Android 4.4.3 和 4.4.4 两个系统版本设置 referer 无效的问题
            if (("4.4.3".equals(Build.VERSION.RELEASE))
                    || ("4.4.4".equals(Build.VERSION.RELEASE))) {
1028
                if (firstVisitWXH5PayUrl) {
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                    view.loadDataWithBaseURL(referer, "<script>window.location.href=\"" + url + "\";</script>",
                            "text/html", "utf-8", null);
                    // 修改标记位状态,避免循环调用
                    // 再次进入微信H5支付流程时记得重置状态 firstVisitWXH5PayUrl = true
                    firstVisitWXH5PayUrl = false;
                }
                // 返回 false 由系统 WebView 自己处理该 url
                return false;
            } else {
                // HashMap 指定容量初始化,避免不必要的内存消耗
                HashMap<String, String> map = new HashMap<>(1);
                map.put("Referer", referer);
                view.loadUrl(url, map);
                return true;
            }
1044
        } else if (url.contains("alipay")) {
1045 1046 1047 1048 1049 1050 1051
            return false;
        }

        return null;
    }

    private void onReceivedSslErrorHandle(SslErrorHandler handler) {
1052
        if (BaseApp.instance.getGlobalConfig().getAppDebug()) {
1053 1054 1055
            handler.proceed();
            return;
        }
1056 1057
        ToastUtil.toastShort("SSL 证书验证错误");
        handler.cancel();
1058 1059 1060
    }

    private void initShareMenu() {
1061 1062
        tb_title.setRightIcon(getResources().getDrawable(R.drawable.web_common_share));
        tb_title.setOnRightTextClick((view, isActive) -> {
范玉宾 committed
1063
            ShareData shareData = paramsForCommentList.getShare();
范玉宾 committed
1064
            if (shareData != null && "commentList".equals(shareData.getType())) {
1065
                isShareCommentList = true;
范玉宾 committed
1066 1067 1068
                ActionCountUtils.Companion.record("experts_comment_list_page", "comment_share_click");
                share(shareData.getImageBase64(), paramsForCommentList);
            } else {
范玉宾 committed
1069 1070
                share(null, null);
            }
1071
        });
1072 1073 1074 1075
        LogUtil.d("setSeccessful");
    }

    public void onEvent(RefreshWebEvent event) {
1076
        if (event.isClearHistory) {
1077 1078 1079
            wv_content.clearCache(true);
            wv_content.clearHistory();
            loadUrl(h5Params.getUrl());
1080
        } else {
1081 1082 1083 1084 1085 1086
            //刷新页面
            loadUrl(h5Params.getUrl());
            shouldClearHistory = true;
        }
    }

konghaorui committed
1087 1088 1089 1090 1091 1092
    public void onEvent(UserBindPhoneEvent event) {
        //刷新页面
        loadUrl(h5Params.getUrl());
        shouldClearHistory = true;
    }

1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    public void onEvent(UserLoginEvent event) {
        if (!TextUtils.isEmpty(successPage)) {
            if (!TextUtils.isEmpty(event.getUid())) {
                String subText = "uid=" + event.getUid();

                URI uri = URI.create(successPage);
                String query = uri.getQuery();

                if (TextUtils.isEmpty(query)) {
                    successPage = successPage + "?" + subText;
                } else {
                    Map<String, String> queryMap = URLUtils.queryStr2Map(successPage);
                    if (queryMap != null && queryMap.containsKey("uid")) {
                        queryMap.put("uid", event.getUid());
                        successPage = successPage.substring(0, successPage.indexOf("?")) + "?" + URLUtils.map2QueryStr(queryMap);
                    } else {
                        successPage += "&" + subText;
                    }
                }
            }
            h5Params.setUrl(successPage);
        }

        //刷新页面
        loadUrl(h5Params.getUrl());
        shouldClearHistory = true;
        if (isToTrend) {
            isToTrend = false;
            //分享到心事动态
            toTrend(shareToUrl);
        }
    }


    @SuppressWarnings("unused")
    public void callJSFunc(String funcName) {
        final StringBuffer sb = new StringBuffer("javascript:");
        sb.append(funcName);
        wv_content.post(() -> {
            try {
                wv_content.loadUrl(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void loadUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }

1145
        String resultUrl = h5Params.getSuffix() ? WebUrlParamsUtils.getSuffix(url, jtoJHandle.getUriAppendSuffix()) : url;
1146
        Log.e("AAAA", resultUrl);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
        wv_content.loadUrl(resultUrl);
        pointBI(resultUrl);
    }

    /**
     * 埋点
     *
     * @param url
     */
    private void pointBI(String url) {

    }

    private void initHead() {
        // header
        final MaterialHeader header = new MaterialHeader(this);
1163
        int[] colors = new int[]{getResources().getColor(R.color.platform_main_theme)};
1164 1165
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
konghaorui committed
1166
        int padding = (int) getResources().getDimension(R.dimen.platform_default_dis_size);
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
        header.setPadding(0, padding, 0, padding);
        header.setPtrFrameLayout(store_house_ptr_frame);
        store_house_ptr_frame.setHeaderView(header);
        store_house_ptr_frame.setPtrHandler(this);
        store_house_ptr_frame.addPtrUIHandler(header);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wv_content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        frame.postDelayed(() -> {
            store_house_ptr_frame.refreshComplete();
            if (loadFailed) {
                loadFailed = false;
                wv_content.goBack();
            } else {
                wv_content.reload();
            }
        }, 1800);
    }

    public void goBack() {

        finish();
    }

    public void back(String type) {
        if (wv_content.canGoBack()) {
            tb_title.setmLeftText("关闭");
            tb_title.setLeftTextVisible(VISIBLE);
            if ("top".equals(type)) {
                setTitle(wv_content.getTitle());
徐健 committed
1203 1204 1205
                tb_title.setImageListener(v ->
                        wv_content.goBack()
                );
1206 1207 1208 1209 1210 1211 1212
            } else {
                wv_content.goBack();
            }
            if (startType != 1) {
                tb_title.setImageVis(1);
            }
        } else {
1213
            tb_title.setImage(getResources().getDrawable(R.drawable.web_common_back));
1214 1215 1216 1217 1218
            tb_title.setmLeftText("");
            if ("top".equals(type)) {
                setTitle(wv_content.getTitle());
                tb_title.setImageListener(v -> {
                    if (h5Params.isSplash()) {
1219
                        WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
1220
                        finish();
1221
                    } else {
范玉宾 committed
1222 1223 1224 1225
                        if (ActivityManager.Companion.getInstance().getActivitys().size() == 1) {
                            WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
                        }
                        finish();
1226 1227 1228 1229
                    }
                });
            } else {
                if (h5Params.isSplash()) {
1230
                    WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
                    finish();
                } else {
                    if (startType == 1) {
//                        overridePendingTransition(0, R.anim.activity_open_down);
                    }
                    finish();
                }
            }
            if (startType != 1) {
                tb_title.setImageVis(1);
            }
        }

    }

    public void setWebViewTitle(String title) {
        Observable.just(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(next -> {
                    tb_title.setTitle(title);
                });
    }

    private void setTitle(String title) {
        /**
         * 高级题跳转第三方h5页面,需要特殊处理:不能使用页面自带的title
         */
        if (!h5Params.isControlBack()) {
            tb_title.setTitle(title);
        }
    }

    @Override
    public void finish() {
        super.finish();
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().startSync();
徐健 committed
1268
        //CookieManager.getInstance().removeSessionCookie();
1269 1270 1271 1272 1273 1274 1275 1276 1277
    }

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

1278 1279 1280 1281
    /**
     * 最后在OnActivityResult中接受返回的结果
     */
    @Override
1282 1283
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
1284 1285 1286
            if (null == uploadMessage && null == uploadMessageAboveL) {
                return;
            }
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else if (requestCode == 33 && resultCode == RESULT_OK) {
            //专家收款 支付成功 跟新历史收款消息
            if (!TextUtils.isEmpty(successPage)) {
                NewH5Activity.start(this, new H5Params(successPage, ""));
            }
            if (h5Params.isSplash()) {
1300
                WebModularServiceUtils.Companion.startMain(NewH5Activity.this);
1301 1302 1303 1304 1305 1306
                finish();
            } else {
                finish();
            }
        } else if (requestCode == 55 && resultCode == RESULT_OK) {
            //购买课程成功
konghaorui committed
1307
            ToastUtil.toastShort(getString(R.string.platform_attend_course_success));
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
            wv_content.reload();
        } else if (requestCode == 44) {
            //测试题 支付成功
            refresh();
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
1320
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
1321
            return;
1322
        }
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
1335
                if (dataString != null) {
1336
                    results = new Uri[]{Uri.parse(dataString)};
1337
                }
1338 1339 1340 1341 1342 1343 1344 1345
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
徐健 committed
1346 1347 1348 1349

        /**
         * 判断是否是测评题页面,如果是,则走测评题页面的返回逻辑
         */
1350
        if (keyCode == KeyEvent.KEYCODE_BACK) {
徐健 committed
1351 1352 1353 1354 1355 1356 1357 1358
            /**
             * 是否是测评题目页面
             */
            if (selfPageType == TEST_QUESTIONS_PAGE_TYPE) {
                showTestQuestionPageReturnDialog();
                return false;
            }

1359
            /**
1360
             * 新用户侧滑按钮限制
1361
             */
1362
            if (h5Params.getBackLimit() != null && h5Params.getBackLimit() == H5Params.BackLimit.NEW_USER_PAGE) {
徐健 committed
1363
                ModularServiceManager.INSTANCE.provide(IAppService.class).mainIntent(this);
1364
                return true;
1365
            }
徐健 committed
1366

1367 1368 1369 1370 1371 1372 1373
            /**
             * 增加逻辑:在高级题测试页面,按物理返回键直接finish当前页面,不走webview.goback()逻辑
             */
            if (h5Params.isControlBack()) {
                finish();
            }
            back("key");
徐健 committed
1374

1375 1376 1377 1378 1379
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

徐健 committed
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    /**
     * 测评题返回的时候,弹窗提示用户
     */
    public void showTestQuestionPageReturnDialog() {
        if (null == testQuestionsPageReturnDialog) {
            testQuestionsPageReturnDialog = new YDLCommonDialog(this, new YDLCommonDialog.OnYDLCommonDialogListener() {
                @Override
                public void onCancel() {
                    finish();
                }

                @Override
                public void onSure() {
徐健 committed
1393
                    coverJavaTitleBar();
徐健 committed
1394 1395 1396 1397 1398
                    testQuestionsPageReturnDialog.dismiss();
                }
            }).setTitle("你确定要退出测试吗?")
                    .setDesc("98%的人都说结果很有用哦")
                    .setCancelText("退出")
徐健 committed
1399
                    .setSureText("继续测试");
徐健 committed
1400 1401 1402 1403
        }
        testQuestionsPageReturnDialog.show();
    }

1404 1405
    @Override
    protected void onDestroy() {
1406
        super.onDestroy();
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
        cancelSendNetLossMessage();
        EventBus.getDefault().unregister(this);
        if (wv_content != null) {
            wv_content.destroy();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if ("我的订单".equals(tb_title.getTitle())) {
            safeTipView.updateVisibility();
        }
        if (h5Params.isShowMenu()) {
ydl committed
1422 1423 1424 1425 1426 1427
            try {
                if (WebModularServiceUtils.Companion.getImService().isHasUnread()) {
                    tb_title.setImage_right(getResources().getDrawable(R.drawable.web_common_notice_more_en));
                } else {
                    tb_title.setImage_right(getResources().getDrawable(R.drawable.web_common_notice_more_un));
                }
1428 1429 1430
            } catch (Exception e) {
                e.printStackTrace();
            }
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
        }
        if (backgroundView.getVisibility() == View.VISIBLE) {
            backgroundView.setVisibility(View.GONE);
        }
    }

    /**
     * 分享
     */
    private void share(String base64DataStr, H5JsBean.H5JsCmd.Params params) {
        shareToUrl = !TextUtils.isEmpty(purl) ? purl : shareUrl;
        if (TextUtils.isEmpty(shareToUrl)) {
            return;
        }
        if (!TextUtils.isEmpty(base64DataStr) && TextUtils.isEmpty(shareDesc)) {
            shareDesc = "壹点灵,温暖而有力地爱着你";
        }
        String minPath = "";
        String minId = "";
        if (params != null && params.getShare() != null) {
            minPath = params.getShare().getMinProgramPath();
            minId = params.getShare().getMinProgramId();
        }
        YDLShareDialog dialog;
1455

1456 1457 1458
        if (params != null && !TextUtils.isEmpty(params.getCourse_id())) {
            dialog = YDLShareDialog.Companion.style5(this, shareTitle, shareUrl, shareDesc, cover);
        } else {
1459
            if (!H5RouterUtils.INSTANCE.isDependByClz(IDynamicService.class)) {
1460 1461
                //如果未引入动态模块的话,隐藏分享至动态按钮
                dialog = YDLShareDialog.Companion.style4(this, shareTitle, shareUrl, shareDesc, cover);
1462
            } else {
1463 1464 1465 1466 1467
                if (isShareCommentList){
                    dialog = YDLShareDialog.Companion.style7(this, shareTitle, shareUrl, shareDesc, cover, minPath, minId);
                }else {
                    dialog = YDLShareDialog.Companion.style1(this, shareTitle, shareUrl, shareDesc, cover, minPath, minId);
                }
1468
            }
1469 1470
        }

1471

1472 1473
        dialog.setCallBack(type -> {
            if (1 == type) {
1474
                if (!WebModularServiceUtils.Companion.getUserService().loginByOneKeyLogin(NewH5Activity.this, true)) {
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
                    isToTrend = true;
                } else {
                    //分享到心事动态
                    toTrend(shareToUrl);
                }
            }

            if (type == 5) {
                //生成海报
                ARouter.getInstance().build("/course/poster")
                        .withString("course_id", params.getCourse_id())
                        .navigation();

                new Handler(getMainLooper()).postDelayed(() -> {
                    backgroundView.setImageBitmap(RxImageTool.fastBlur(RxDeviceTool.captureWithStatusBar(NewH5Activity.this), 0.5f, 12, true));
                    backgroundView.setVisibility(View.VISIBLE);
                }, 500);
            }
        });
        if (!TextUtils.isEmpty(base64DataStr)) {
            dialog.setPosterPicture(base64DataStr);
        }
        if ("文章详情".equals(tb_title.getTitle())) {
            dialog.setShareCallBack(new YDLShareDialog.IShareCallBack() {
                @Override
                public void onShareSuccessed(@NotNull SHARE_MEDIA share_media) {
                    String params = getIntent().getStringExtra("articalParams");
                    BuryPointUtils.getInstance().createMap()
                            .put("share_where", share_media.toString())
                            .put("share_what", shareTitle + "," + params)
                            .put("share_succeed", true)
                            .burryPoint("Share");
                }

                @Override
                public void onShareFailed(@NotNull SHARE_MEDIA share_media, @NotNull Throwable throwable) {
                    String params = getIntent().getStringExtra("articalParams");
                    BuryPointUtils.getInstance().createMap()
                            .put("share_where", share_media.toString())
                            .put("share_what", shareTitle + "," + params)
                            .put("share_succeed", false)
                            .burryPoint("Share");
                }
            });
        }
        dialog.show(getFragmentManager(), "lose");
    }

    private void toTrend(String url) {
1524
        this.startActivity(WebModularServiceUtils.Companion.getDynamicService().publishArticleToTrend(NewH5Activity.this, url, cover, shareTitle));
1525
    }
konghaorui committed
1526

范玉宾 committed
1527 1528 1529 1530 1531 1532 1533 1534 1535
    public void switchSound(int mediaId, long meditationId, int meditationType, int businessType,
                             String buried, String mediaUrl, String mediaCoverUrl,
                             String title, String desc, int status){
        MeditationEvent event = new MeditationEvent(
                mediaId,meditationId,meditationType,businessType,
                status,buried,mediaUrl,mediaCoverUrl,title,desc);
        EventBus.getDefault().post(event);
    }

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547

    public void setBG(String color,String alpha){
        try {
            store_house_ptr_frame.setBackgroundColor(Color.parseColor(color));
            int a = Integer.valueOf(alpha);
            store_house_ptr_frame.getBackground().setAlpha(a);
        }catch (Exception ex){

        }

    }

范玉宾 committed
1548

1549
    public void showCommentArticleDialog(String title){
范玉宾 committed
1550
        if (commentArticleDialog == null) {
1551 1552
            String titleStr = title==null?wv_content.getTitle():title;
            commentArticleDialog = ArticleDialogFragment.newInstance(titleStr);
范玉宾 committed
1553 1554 1555
            commentArticleDialog.setOnPublishListener(comment -> {
                callJSFunc("sendComment('"+comment+"')");
            });
范玉宾 committed
1556 1557 1558 1559 1560 1561 1562
        }
        if (commentArticleDialog != null && !commentArticleDialog.isAdded()) {
            commentArticleDialog.show(getSupportFragmentManager(), "article_comment");
        }
    }


1563
}