H5Activity.java
38.8 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
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
832
833
834
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
package com.people.webview.ui;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.people.webview.R;
import com.people.webview.constant.AppNotifyEventConstant;
import com.people.webview.constant.CallbackHandlerType;
import com.people.webview.javabridge.BridgeJavascriptInterface;
import com.people.webview.util.JSBridgeUtils;
import com.people.webview.util.LinkUrlUtils;
import com.people.webview.util.WebUtils;
import com.people.webview.vm.ArticleDetailViewModel;
import com.people.webview.vm.IArticleDetailDataListener;
import com.wd.base.log.Logger;
import com.wd.capability.network.constant.EventConstants;
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.common.net.NetStateChangeReceiver;
import com.wd.common.permissions.IPmsCallBack;
import com.wd.common.permissions.PermissionsUtils;
import com.wd.common.utils.H5JsApiPermissionUtil;
import com.wd.common.utils.ProcessUtils;
import com.wd.common.widget.DefaultView;
import com.wd.common.widget.MarqueeNormalTextView;
import com.wd.foundation.bean.JsCallAppBean;
import com.wd.foundation.bean.JsImageBean;
import com.wd.foundation.bean.JsScrollBean;
import com.wd.foundation.bean.JsShareBean;
import com.wd.foundation.bean.custom.content.ContentBean;
import com.wd.foundation.bean.livedate.EventMessage;
import com.wd.foundation.bean.livedate.NetStateMessage;
import com.wd.foundation.bean.response.NewsDetailBean;
import com.wd.foundation.bean.web.AppToH5DataBean;
import com.wd.foundation.bean.web.JSCallbackBean;
import com.wd.foundation.bean.web.JSTitleBean;
import com.wd.foundation.bean.web.JsPageBean;
import com.wd.foundation.wdkitcore.constant.BaseConstants;
import com.wd.foundation.wdkit.constant.DefaultViewConstant;
import com.wd.foundation.wdkit.constant.IntentConstants;
import com.wd.foundation.wdkit.statusbar.StatusBarStyleEnum;
import com.wd.foundation.wdkit.utils.SpUtils;
import com.wd.foundation.wdkitcore.livedata.LiveDataBus;
import com.wd.foundation.wdkitcore.tools.AppContext;
import com.wd.foundation.wdkitcore.tools.JsonUtils;
import com.wd.foundation.wdkitcore.tools.StringUtils;
import org.json.JSONException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* H5页面
*
* @author libo
* @version [V1.0.0, 2022/12/27]
* @since V1.0.0
*/
@Route(path = RouterConstants.PATH_H5_PAGE)
public class H5Activity extends BaseActivity implements View.OnClickListener {
private final static int FILECHOOSER_RESULTCODE = 1;
private final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;
private final static String TAG = "H5Activity";
// 展示返回栏
private final int TOOL_BAR_SHOW = 0;
// 隐藏返回栏
private final int TOOL_BAR_HIDE = 1;
public ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> mUploadMessageForAndroid5;
private LinearLayout titleLayout;
/**
* webview
*/
private NativeWebView mWebView;
/**
* 标题
*/
private MarqueeNormalTextView titleTv;
/**
* 标题底线
*/
private View titleLine;
/**
* 更多
*/
private ImageView shareImg;
/**
* 缺省页
*/
private DefaultView defaultView;
private JSONObject jsonObject;
/**
* webView加载状态 false为加载异常
*/
private boolean webViewLoad;
/**
* 上下文环境
*/
private Context mContext;
/**
* 上下文环境
*/
private Activity mActivity;
/**
* webUrl
*/
private String webUrl = "";
/**
* 标题
*/
private String titleStr = "";
private NetStateChangeReceiver mReceiver;
/**
* 用来保存WebView访问的链接
**/
private ArrayList<String> loadHistoryOldUrls = new ArrayList<>();
/**
* viewmoel
*/
private ArticleDetailViewModel articleDetailViewModel;
/**
* 当dataSource为7时 数据对象为数组,该数组元素为,:
* http://192.168.1.3:3300/project/3802/interface/api/189235
* 接口的 data下面的operDataList 列表元素对象 json object
*/
private String shareDataJson = "";
/**
* 解决刚进入,网络变化回调会执行一次
*/
private boolean networkFirst = true;
/**
* 分享数据
*/
private JsShareBean jsShareBean = null;
/**
* h5通知APP是否可以直接使用goBack
*/
private boolean useGoBack = false;
/**
* 关闭加载动效标记
*/
private boolean stopLoadingTag = false;
private boolean isFullScreen = false;
/**
* 回调
*/
public Handler callBackHandler = new Handler(Looper.getMainLooper()){
@SuppressLint("HandlerLeak")
@Override
public void handleMessage(@NonNull Message msg) {
JSCallbackBean jsCallbackBean = null;
if(msg != null && msg.obj != null){
jsCallbackBean = (JSCallbackBean) msg.obj;
}
if(CallbackHandlerType.jsCall_openAppShare == msg.arg1){
//H5调用此方法,启动客户端分享弹窗
try {
if(jsCallbackBean != null) {
JsShareBean jsShareBean = (JsShareBean) jsCallbackBean.getCallbackData();
if (StringUtils.isBlank(jsShareBean.getWebpageUrl())) {
jsShareBean.setWebpageUrl(BaseConstants.appDownLoadUrl);
}
WebUtils.onSingleShare(mActivity,jsShareBean,null,null);
}
} catch (Exception e) {
e.printStackTrace();
}
}if(CallbackHandlerType.jsCall_appShare == msg.arg1){
//H5调用此方法,展示右上角分享
try {
if(jsCallbackBean != null) {
JsShareBean jsShareBean = (JsShareBean) jsCallbackBean.getCallbackData();
setAppShare(jsShareBean);
}
} catch (Exception e) {
e.printStackTrace();
}
}else if(CallbackHandlerType.jsCall_savePhoto == msg.arg1){
if(jsCallbackBean != null) {
//保存图片到相册
JsImageBean jsImageBean = (JsImageBean) jsCallbackBean.getCallbackData();
WebUtils.getPermission(mActivity, jsImageBean);
}
}else if(CallbackHandlerType.jsCall_receiveH5Data == msg.arg1){
if(jsCallbackBean != null) {
//由App预埋,H5加载完成后 主动传递数据用
JsPageBean jsPageBean = (JsPageBean) jsCallbackBean.getCallbackData();
setJSPageData(jsPageBean);
}
}else if(CallbackHandlerType.jsCall_h5ScrollEvent == msg.arg1){
if(jsCallbackBean != null) {
//滚动事件
JsScrollBean jsScrollBean = (JsScrollBean) jsCallbackBean.getCallbackData();
WebUtils.updateVoiceEasyFloatUi(jsScrollBean);
}
}else if(CallbackHandlerType.jsCall_callAppService == msg.arg1){
//H5调用App接口
try {
if(jsCallbackBean != null) {
JsCallAppBean jsCallAppBean = (JsCallAppBean) jsCallbackBean.getCallbackData();
//处理数据
setJsCallAppData(jsCallAppBean);
}
} catch (Exception e) {
e.printStackTrace();
}
}else if (CallbackHandlerType.jsCall_receiveSubjectData == msg.arg1){
//这里是普通H5详情页面里的,应该不需要,先保留着
try {
if(jsCallbackBean != null) {
JsCallAppBean jsCallAppBean = (JsCallAppBean) jsCallbackBean.getCallbackData();
//处理数据
WebUtils.sendH5TopicPageInfo(mWebView,jsCallAppBean);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if(CallbackHandlerType.jsCall_currentPageOperate_12 == msg.arg1){
Logger.t(TAG).i("jsCall_currentPageOperate_12");
//关闭 App原生默认顶部导航,并通顶显示Webview
try {
if(jsCallbackBean != null) {
int statusBarType = (int) jsCallbackBean.getCallbackData();
//处理数据
setStatusBarType(statusBarType);
}
} catch (Exception e) {
e.printStackTrace();
}
}else if(CallbackHandlerType.jsCall_currentPageOperate_13 == msg.arg1){
Logger.t(TAG).i("jsCall_currentPageOperate_13");
//关闭 App原生默认顶部导航,并通顶显示Webview
try {
//处理数据,显示导航栏
setStatusBarType(0);
} catch (Exception e) {
e.printStackTrace();
}
}else if(CallbackHandlerType.jsCall_currentPageOperate_18 == msg.arg1){
//页面相关操作-18 设置标题使用
try {
if(jsCallbackBean != null) {
JSTitleBean jsTitleBean = (JSTitleBean) jsCallbackBean.getCallbackData();
String title = jsTitleBean.getTitle();
setTitle(title);
String bottomLineHidden = jsTitleBean.getBottomLineHidden();
if (StringUtils.isNotBlank(bottomLineHidden)) {
setTitleBottomLineHidden(bottomLineHidden);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else if(CallbackHandlerType.jsCall_currentPageOperate_19 == msg.arg1){
//页面相关操作-19 设置状态栏颜色
try {
if(jsCallbackBean != null) {
String statusBarMode = (String) jsCallbackBean.getCallbackData();
setStatusBarMode(statusBarMode);
}
} catch (Exception e) {
e.printStackTrace();
}
}else if(CallbackHandlerType.jsCall_currentPageOperate_45 == msg.arg1){
//页面相关操作-45 打开APP直接使用goBack
useGoBack = true;
}else if(CallbackHandlerType.jsCall_currentPageOperate_46 == msg.arg1){
//页面相关操作-46 关闭APP直接使用goBack
useGoBack = false;
} else if (CallbackHandlerType.jsCall_currentPageOperate_47 == msg.arg1) {
//页面相关操作-47 显示客户端通用loading动效
startLoading(false);
} else if (CallbackHandlerType.jsCall_currentPageOperate_48 == msg.arg1) {
//页面相关操作-48 关闭客户端通用loading动效
stopLoading();
stopLoadingTag = true;
}
}
};
@Override
protected int getLayoutId() {
return R.layout.activity_webview_h5;
}
@Override
protected String getTag() {
return "H5Activity";
}
@Override
protected void initView() {
mContext = this;
mActivity = this;
titleLayout = findViewById(R.id.layout_title);
defaultView = findViewById(R.id.default_view);
mWebView = findViewById(R.id.webView);
ImageView back = findViewById(R.id.iv_back);
shareImg = findViewById(R.id.iv_share);
titleTv = findViewById(R.id.tv_title);
titleLine = findViewById(R.id.line_title);
back.setOnClickListener(this);
shareImg.setOnClickListener(this);
shareImg.setVisibility(View.INVISIBLE);
//设置背景为透明
mWebView.setBackgroundColor(0);
Drawable bgDrawable = mWebView.getBackground();
if(bgDrawable != null){
bgDrawable.mutate().setAlpha(0);
}
WebUtils.getInstance().initWebSetting( mWebView);
// 初始化发布视频进度浮窗
// PublishFloatViewManager.getInstance().addWhiteList(H5Activity.class);
}
@Override
protected void initData() {
Object actionBeanObject = getExtrasSerializableObject();
if (actionBeanObject == null) {
return;
}
jsonObject = JsonUtils.convertJsonToObject(((ActionBean) actionBeanObject).paramBean.params, JSONObject.class);
Logger.t(TAG).i("jsonObject:"+jsonObject);
webUrl = jsonObject.getString(IntentConstants.WEBSITES_SEARCHURL);
if(TextUtils.isEmpty(webUrl)){
finish();
return;
}
// 从链接地址中参数 hiddenNavigator=1 表示展示导航栏 否则隐藏
String hiddenTopNavigation = LinkUrlUtils.getParamsValue(webUrl, "hiddenNavigator");
if ("1".equalsIgnoreCase(hiddenTopNavigation)){
Logger.t(TAG).d("hiddenNavigator==1");
setStatusBarType(TOOL_BAR_HIDE);
}else {
setStatusBarType(TOOL_BAR_SHOW);
}
initWeb();
//监听
receiveLiveDataMsg();
// 需要网络监听
setNetStateObserver();
}
/**
* 初始化webview
*/
private void initWeb(){
// 这段代码会影响对 js 的注入,需注意
mWebView.setGson(new Gson());
mWebView.setWebChromeClient(new WebChromeClient() {
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
this.openFileChooser(uploadMsg,acceptType);
}
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(acceptType);
startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android 5.0+
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
PermissionsUtils.getSDPermission(H5Activity.this, new IPmsCallBack() {
@Override
public void granted() {
onenFileChooseImpleForAndroid(filePathCallback,fileChooserParams);
}
@Override
public void notGranted() {
// ToastNightUtil.showShort("请先授权存储权限");
}
});
return true;
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
/*if (TextUtils.isEmpty(titleStr)&&!TextUtils.isEmpty(title)) {
titleTv.setText(title);
}*/
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
// NBSWebChromeClient.initJSMonitor(view, newProgress);
super.onProgressChanged(view, newProgress);
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webViewLoad = true;
}
@Override
public void onPageFinished(WebView view, String url) {
Logger.t(TAG).i("onPageFinished");
if(view.getProgress() == 100) {
stopLoading();
stopLoadingTag = true;
if (webViewLoad) {
if (mWebView != null && mWebView.getVisibility() == View.GONE) {
mWebView.setVisibility(View.VISIBLE);
}
}
if (loadHistoryOldUrls != null) {
if (!loadHistoryOldUrls.contains(url)) {
loadHistoryOldUrls.add(url);
}
}
}
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!url.startsWith("http")) {
try {
//处理唤端
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
// 新版本调用,只会在Android6及以上调用
@Override
public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
super.onReceivedError(view, webResourceRequest, webResourceError);
String url = webResourceRequest.getUrl().toString();
if (url.endsWith(".apk") || url.endsWith(".pdf")) {
return;
}
if (webResourceRequest.isForMainFrame()) {
/**
* webview加载异常时 webViewLoad设置为false,隐藏webview 避免显示x5系统默认网络错误页面,显示自定义断网/网络不给力页面
*/
webViewLoad = false;
mWebView.setVisibility(View.GONE);
stopLoading();
//展示缺省页
int type = DefaultViewConstant.TYPE_GET_CONTENT_FAILED;
if (!NetworkUtil.isNetAvailable()) {
type = DefaultViewConstant.TYPE_NO_NETWORK;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(webResourceError != null && webResourceError.getErrorCode() == ERROR_TIMEOUT){
type = DefaultViewConstant.TYPE_NO_NETWORK;
}
}
showDefaultView(defaultView, type);
// 展示返回工具类
titleLayout.setVisibility(View.VISIBLE);
}
}
// 旧版本调用,会在新版本中也可能被调用,所以加上一个版本判断,防止重复显示
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return;
}
if (failingUrl.endsWith(".apk") || failingUrl.endsWith(".pdf")) {
return;
}
/**
* webview加载异常时 webViewLoad设置为false,隐藏webview 避免显示系统默认网络错误页面,显示自定义断网/网络不给力页面
*/
webViewLoad = false;
mWebView.setVisibility(View.GONE);
stopLoading();
//展示缺省页
int type = DefaultViewConstant.TYPE_GET_CONTENT_FAILED;
if (!NetworkUtil.isNetAvailable()) {
type = DefaultViewConstant.TYPE_NO_NETWORK;
}
if(errorCode == ERROR_TIMEOUT){
type = DefaultViewConstant.TYPE_NO_NETWORK;
}
showDefaultView(defaultView, type);
// 展示返回工具类
titleLayout.setVisibility(View.VISIBLE);
}
});
//设置下载监听
mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//进行下载处理,跳转浏览器或者调用系统下载方法
try {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//H5白名单控制JS交互
if (H5JsApiPermissionUtil.getInstance().isAppWhiteHostForJs(webUrl)){
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.addJavascriptInterface(new BridgeJavascriptInterface(mWebView.getCallbacks(), mWebView, callBackHandler), "WebViewJavascriptBridge");
}else {
mWebView.getSettings().setJavaScriptEnabled(false);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
}
mWebView.loadUrl(webUrl);
mWebView.postDelayed(new Runnable() {
@Override
public void run() {
//延迟200ms,且没有关闭,展示loading
if(!stopLoadingTag){
startLoading(false);
}
}
},200);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) {
return;
}
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
if (null == mUploadMessageForAndroid5) {
return;
}
onActivityResultAboveL(requestCode, resultCode, data);
}
}
// 4. 选择内容回调到Html页面
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
if (requestCode != FILECHOOSER_RESULTCODE_FOR_ANDROID_5 || mUploadMessageForAndroid5 == null) {
return;
}
//正确的方法,需要存储权限,声明下
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
if (result != null) {
mUploadMessageForAndroid5.onReceiveValue(new Uri[] { result });
} else {
mUploadMessageForAndroid5.onReceiveValue(null);
}
mUploadMessageForAndroid5 = null;
}
private void onenFileChooseImpleForAndroid(ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMessageForAndroid5 = filePathCallback;
Intent fileChooseIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileChooseIntent.addCategory(Intent.CATEGORY_OPENABLE);
//需要的选择类型
String[] acceptTypes = fileChooserParams.getAcceptTypes();
if (acceptTypes!=null){
if ("image/*".equals(acceptTypes[0])){
fileChooseIntent.setType(acceptTypes[0]);
}else {
fileChooseIntent.setType("*/*");
}
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, fileChooseIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_MIME_TYPES,acceptTypes);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
}
/**
* livedata监听
*/
private void receiveLiveDataMsg() {
//登录成功
LiveDataBus.getInstance().with(EventConstants.USER_ALREADY_LOGIN, Boolean.class).observe(this, aBoolean -> {
if (aBoolean) {
JSBridgeUtils.jsCall_appNotifyEvent(mWebView, AppNotifyEventConstant.EVENT_ONE);
}
});
//接收关注事件
LiveDataBus.getInstance().with(EventConstants.FRESH_FOLLOW_CREATOR_EVENT,
EventMessage.class).observe(this, mEventMessage -> {
if (mEventMessage == null) {
return;
}
if (null != mWebView) {
// 同步关注信息
JSONObject jsonObject = new JSONObject();
jsonObject.put("event", AppNotifyEventConstant.EVENT_ELEVEN);
String createId = mEventMessage.getStringExtra(IntentConstants.PARAM_CREATOR_ID);
boolean followStatus = mEventMessage.getBooleanExtra(IntentConstants.IS_FOLLOW, false);
//当 event==11时,被关注的号主id
jsonObject.put("creatorId", createId);
//当 event==11时,1 已关注,0 未关注
jsonObject.put("followStatus", followStatus ? "1" : "0");
JSBridgeUtils.jsCall_appNotifyEvent(mWebView,jsonObject);
}
});
//接收点赞事件
LiveDataBus.getInstance().with(EventConstants.FRESH_ZAN_CREATOR_EVENT,
EventMessage.class).observe(this, mEventMessage -> {
if (mEventMessage == null) {
return;
}
if (null != mWebView ) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("event", AppNotifyEventConstant.EVENT_TWELVE);
String contentId = mEventMessage.getStringExtra(IntentConstants.CONTENT_ID);
String relId = mEventMessage.getStringExtra(IntentConstants.REL_ID);
boolean isZan = mEventMessage.getBooleanExtra(IntentConstants.IS_ZAN, false);
//当 event==12时,被点赞内容id
jsonObject.put("contentId", contentId);
//当 event==12时,1 已点赞,0 未点赞
jsonObject.put("likeStatus", isZan ? "1" : "0");
JSBridgeUtils.jsCall_appNotifyEvent(mWebView,jsonObject);
}
});
}
/**
* 监听网络
*/
protected void setNetStateObserver() {
// Create the broadcast receiver instance
mReceiver = new NetStateChangeReceiver();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, intentFilter);
LiveDataBus.getInstance()
.with(EventConstants.NETWORK_STATE_CHANGE, NetStateMessage.class)
.observe(this, new Observer<NetStateMessage>() {
@Override
public void onChanged(@Nullable NetStateMessage msg) {
Logger.t(TAG).d("Network status" + msg.type);
if(networkFirst){
networkFirst = false;
return;
}
if (msg == null) {
return;
}
JSBridgeUtils.jsCall_appNetworkStatusChangedEvent(mWebView);
}
});
}
/**
* 设置h5返回的page数据
*/
private void setJSPageData(JsPageBean jsPageBean){
if (jsPageBean == null) {
return;
}
String dataSource = jsPageBean.getDataSource();
Logger.t(TAG).d("dataSource=========>"+dataSource);
Logger.t(TAG).d("dataJson=========>"+jsPageBean.getDataJson());
if (StringUtils.isEqual("2", dataSource)) {
//2.跳转推荐内容数据
WebUtils.jumpToNewArticle(jsPageBean);
}else if (StringUtils.isEqual("3", dataSource)) {
//3.显示图片预览
ProcessUtils.goToImageSlidePage(jsPageBean.getImgListData());
}else if (StringUtils.isEqual("5", dataSource)) {
//5、专题comp运营位点击跳转(并记录浏览历史)
WebUtils.setOperDataJump(jsPageBean);
}else if (StringUtils.isEqual("6", dataSource)) {
//6.图文稿件引用内容
WebUtils.jumpNewLink(jsPageBean);
}else if (StringUtils.isEqual("7", dataSource)) {
//7、专题分享海报图上的数据列表(H5可选第一页前5条运营位数据)
shareDataJson = jsPageBean.getDataJson();
}else if (StringUtils.isEqual("8", dataSource) ||
StringUtils.isEqual("9", dataSource) ||
StringUtils.isEqual("10", dataSource) ||
StringUtils.isEqual("11", dataSource)) {
//8、活动投稿 文章跳转;9、活动投稿 视频跳转;10、活动投稿 动态跳转;11、活动投稿 图集跳转
WebUtils.jumpToPubLish(H5Activity.this, jsPageBean);
}
}
/**
* 处理js传递给APP的数据
* @param jsCallAppBean
*/
private void setJsCallAppData(JsCallAppBean jsCallAppBean){
if(jsCallAppBean == null){
return;
}
org.json.JSONObject dataObject = jsCallAppBean.getJsonObject();
try {
String method = dataObject.getString("method");
String url = dataObject.getString("url");
org.json.JSONObject parameters = dataObject.getJSONObject("parameters");
articleDetailViewModel.requestPageData(method, url, parameters, jsCallAppBean.getCallbackId());
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* 设置标题
* @param title
*/
private void setTitle(String title){
if(titleTv != null && !StringUtils.isEmpty(title)){
titleTv.setVisibility(View.VISIBLE);
titleTv.setText(title);
}
}
/**
* 设置标题底线是否隐藏
* @param bottomLineHidden
*/
private void setTitleBottomLineHidden(String bottomLineHidden){
if(titleLine != null && !StringUtils.isEmpty(bottomLineHidden)){
titleLine.setVisibility(StringUtils.isEqual("1",bottomLineHidden)?View.GONE:View.VISIBLE);
}
}
/**
* 设置状态栏颜色
* @param statusBarMode 1深色 (黑) 2、浅色 (白色)
*/
private void setStatusBarMode(String statusBarMode){
if(isFullScreen){
setStatusBarStyle(StringUtils.isEqual("2",statusBarMode) ? StatusBarStyleEnum.FULLSCREEN_LIGHT_ENUM :
StatusBarStyleEnum.FULLSCREEN_DARK_ENUM);
}else {
setStatusBarStyle(StringUtils.isEqual("2",statusBarMode) ? StatusBarStyleEnum.NORMAL_161827_LIGHT_ENUM :
StatusBarStyleEnum.NORMAL_WHITE_DARK_ENUM);
}
}
/**
* 设置状态栏类型
*
* @param type 展示返回栏 TOOL_BAR_SHOW 隐藏返回栏 TOOL_BAR_HIDE
*/
private void setStatusBarType(int type){
if(type == TOOL_BAR_HIDE){
isFullScreen = true;
titleLayout.setVisibility(View.GONE);
//沉浸式,全屏,透明,黑字
setStatusBarStyle(SpUtils.isNightMode()? StatusBarStyleEnum.FULLSCREEN_LIGHT_ENUM :
StatusBarStyleEnum.FULLSCREEN_DARK_ENUM);
}else {
isFullScreen = false;
titleLayout.setVisibility(View.VISIBLE);
//正常状态栏,白色背景,黑字
setStatusBarStyle(SpUtils.isNightMode()? StatusBarStyleEnum.NORMAL_161827_LIGHT_ENUM :
StatusBarStyleEnum.NORMAL_WHITE_DARK_ENUM);
}
}
/**
* 透传接口数据给h5
* @param netError
* @param dataList
* @param callbackId
*/
private void sendPageDataToH5(String netError, String dataList, String callbackId) {
AppToH5DataBean.DataJson dataJson = new AppToH5DataBean.DataJson();
dataJson.netError = netError;
dataJson.responseMap = dataList;
String data = new Gson().toJson(dataJson);
mWebView.sendResponse(data, callbackId);
}
/**
* 设置app分享
* @param jsShareBean
*/
private void setAppShare(JsShareBean jsShareBean){
if(jsShareBean == null){
return;
}
this.jsShareBean = jsShareBean;
//是否显示分享:1 显示分享按钮 0 不显示
int isShowShare = jsShareBean.getIsShowShare();
if(isShowShare == 1){
shareImg.setVisibility(View.VISIBLE);
}else {
shareImg.setVisibility(View.GONE);
}
}
@Override
protected void initViewModel() {
articleDetailViewModel = new ArticleDetailViewModel();
articleDetailViewModel.observerDataListener(this, new IArticleDetailDataListener() {
@Override
public void onDetailDataSuccess(String dataList) {
}
@Override
public void onDetailDataError(String errorMsg) {
}
@Override
public void onPageDataSuccess(String url, String dataList, String callbackId) {
sendPageDataToH5("0", dataList, callbackId);
}
@Override
public void onPageDataError(String errorMsg, String callbackId) {
sendPageDataToH5("1", "", callbackId);
}
@Override
public void onGetNewsDetailSuccess(List<NewsDetailBean> newsDetailBeanList) {
}
@Override
public void onGetNewsDetailFailed(String error) {
}
@Override
public void onGetRecListSuccess(List<ContentBean> operDataList) {
}
@Override
public void onGetRecListFailed(String error) {
}
});
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.iv_back) {
goBack();
} else if (id == R.id.iv_share) {
//分享
if(jsShareBean == null){
return;
}
if (StringUtils.isBlank(jsShareBean.getWebpageUrl())){
jsShareBean.setWebpageUrl(BaseConstants.appDownLoadUrl);
}
jsShareBean.setSharePlatform("7");
WebUtils.onSingleShare(mActivity,jsShareBean,null,null);
}
}
@Override
public void retryBtnClickListener() {
super.retryBtnClickListener();
refresh();
}
/**
* web view refresh
*/
public void refresh() {
//重新加载刷新时隐藏缺省页
hideDefaultView();
if (mWebView != null) {
mWebView.reload();
startLoading();
}
}
@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()) {
String backUrl = null;
if (loadHistoryOldUrls.size() > 1) {
backUrl = loadHistoryOldUrls.get(loadHistoryOldUrls.size() - 2);
}
//判断打开页面大于1个
if (backUrl != null) {
if (loadHistoryOldUrls.get(loadHistoryOldUrls.size() - 1).contains(loadHistoryOldUrls.get(loadHistoryOldUrls.size() - 2))) {
loadHistoryOldUrls.remove(loadHistoryOldUrls.size() - 1);
}
loadHistoryOldUrls.remove(loadHistoryOldUrls.size() - 1);
mWebView.goBack();
}else if(useGoBack){
//h5设置APP可以直接使用goBack,默认false
mWebView.goBack();
}else{
finish();
}
}else{
finish();
}
}
@Override
protected void onPause() {
super.onPause();
JSBridgeUtils.jsCall_appNotifyEvent(mWebView,AppNotifyEventConstant.EVENT_TWO);
}
@Override
protected void onDestroy() {
if(callBackHandler != null){
callBackHandler.removeCallbacksAndMessages(null);
callBackHandler = null;
}
if(mReceiver != null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
if(mWebView != null){
mWebView.destroy();
}
// 根据时间顺序删除缓存文件
File cacheDir = new File (AppContext.getContext().getFilesDir().getAbsolutePath()+"/cache/web/");
long currentTimeMillis = System.currentTimeMillis();
if(cacheDir.exists()){
for (File file : cacheDir.listFiles()) {
long lastModified = file.lastModified();
if ((currentTimeMillis - lastModified) >= TimeUnit.DAYS.toMillis(3)) {
file.delete();
}
}
}
}
@Override
protected void onResume() {
super.onResume();
JSBridgeUtils.jsCall_appNotifyEvent(mWebView,AppNotifyEventConstant.EVENT_ONE);
}
}