admin
2021-04-14 fa0f31113129ca3222ecabb86f6c63e8e79675b1
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
package com.weikou.beibeivideo.ui.mine;
 
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
 
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
 
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
 
import com.lcjian.library.permission.PermissionHelper;
import com.lcjian.library.permission.PermissionInterface;
import com.lcjian.library.util.ManifestDataUtil;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.weikou.beibeivideo.R;
import com.weikou.beibeivideo.ui.BaseActivity;
import com.weikou.beibeivideo.ui.media.VideoDetailActivity2;
import com.weikou.beibeivideo.util.ConfigUtil;
import com.weikou.beibeivideo.util.browser.BWJavaInterface;
import com.weikou.beibeivideo.util.downutil.DownFiles;
import com.weikou.beibeivideo.util.downutil.DownFiles.IProgress;
import com.weikou.beibeivideo.util.downutil.StringUtils;
import com.weikou.beibeivideo.util.ui.TopStatusSettings;
import com.weikou.beibeivideo.util.x5.X5WebView;
 
import java.io.IOException;
import java.util.Set;
 
public class BrowserActivity extends BaseActivity implements OnClickListener, PermissionInterface {
    private final static String TAG = "BrowserActivity";
 
    private TextView tv_top_bar_left;
    private TextView tv_top_bar_left2;
    private TextView tv_top_bar_middle;
    private X5WebView webview;
    ProgressBar progressBar;
    private PermissionHelper mPermissionsChecker; // 权限检测器 检测是否有储存卡写入读取权限
 
    private Set<String> webSpeedUpHost;
 
    private WebResourceResponse replaceLocalResource(String url) throws IOException {
        if (url == null)
            return null;
        WebResourceResponse response = null;
        if (webSpeedUpHost == null) {
            webSpeedUpHost = ConfigUtil.getWebSpeedUpHost(this);
        }
 
 
        String host = null;
        try {
            Uri uri = Uri.parse(url);
            host = uri.getHost();
        } catch (Exception e) {
 
        }
        webSpeedUpHost.add("192.168.3.122");
        if (webSpeedUpHost != null && webSpeedUpHost.contains(host)) {
            if (url.endsWith("2.1.4/jquery.min.js")) {
                response = new WebResourceResponse("*", "UTF-8", getAssets().open("js/jquery-2.1.4.min.js"));
            } else if (url.endsWith("vue-2.6.12.min.js")) {
                response = new WebResourceResponse("*", "UTF-8", getAssets().open("js/vue-2.6.12.min.js"));
            }
        }
        return response;
    }
 
 
    private void initX5WebView() {
        webview = findViewById(R.id.webview);
        webview.setDownloadListener(new MyWebViewDownLoadListener());
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, url);
                if (url != null && url.startsWith("weixin://")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(BrowserActivity.this)
                                .setMessage("未检测到支付宝客户端,请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {
 
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                } else if (url != null && url.startsWith("buwanprotocol://")) {
                    String murl = url.split("buwanprotocol://")[1];
                    String[] params = murl.split("#");
                    if (params[0].equalsIgnoreCase("playvideo")) {
                        Intent intent = new Intent(BrowserActivity.this, VideoDetailActivity2.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("Id", params[1]);
                        bundle.putString("ResourceId", params[2]);
                        bundle.putString("DetailId", params[3]);
                        bundle.putString("Share", "0");
                        bundle.putString("ThirdType", "0");
                        intent.putExtra("from", "web");
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                    return true;
                } else if (url.startsWith("tenvideo2://") || url.startsWith("iqiyi://")) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
 
                    }
                    return true;
                } else if (url != null && (!url.startsWith("http"))) {
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
 
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }
 
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }
 
            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();
            }
 
 
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, String url) {
                WebResourceResponse response = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    response = super.shouldInterceptRequest(webView, url);
                    try {
                        WebResourceResponse newResponse = replaceLocalResource(url);
                        if (newResponse != null)
                            response = newResponse;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return response;
            }
 
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                WebResourceResponse response = super.shouldInterceptRequest(view, request);
                String url = String.valueOf(request.getUrl());
                try {
                    WebResourceResponse newResponse = replaceLocalResource(url);
                    if (newResponse != null)
                        response = newResponse;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return response;
            }
 
        });
 
        webview.setWebChromeClient(new WebChromeClient() {
 
            @Override
            public void onReceivedTitle(WebView view, String title) {
                tv_top_bar_middle.setText(title);
            }
 
            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (i == 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (View.INVISIBLE == progressBar.getVisibility()) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    progressBar.setProgress(i);
                }
                super.onProgressChanged(webView, i);
            }
 
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.i(TAG, consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }
        });
        WebSettings webSetting = webview.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setTextZoom(100);
        webview.addJavascriptInterface(new BWJavaInterface(this, webview), "yestv");
    }
 
    private boolean needSetResult = false;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.browser_activity);
        TopStatusSettings.setStatusViewAndDeepColor(this);
        tv_top_bar_left = findViewById(R.id.tv_top_bar_left);
        tv_top_bar_left2 = findViewById(R.id.tv_top_bar_left2);
        tv_top_bar_left2.setVisibility(View.VISIBLE);
        tv_top_bar_middle = findViewById(R.id.tv_top_bar_middle);
 
        tv_top_bar_left2.setText("关闭");
        tv_top_bar_left.setOnClickListener(this);
        tv_top_bar_left2.setOnClickListener(this);
 
        progressBar = findViewById(R.id.myProgressBar);
        progressBar.setMax(100);
        progressBar.setProgressDrawable(this.getResources()
                .getDrawable(R.drawable.color_progressbar));
        initX5WebView();
        String url = getIntent().getStringExtra("url");
//        String url="http://192.168.3.122:8848/buwan-web/BuWanWeb/vip/pay_success.html?id=23";
        webview.loadUrl(url);
        needSetResult = getIntent().getBooleanExtra("result", false);
        mPermissionsChecker = new PermissionHelper(this, this);//权限
    }
 
    // 文件下载监听
 
    private class MyWebViewDownLoadListener implements DownloadListener {
 
        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            startDownLoadFile(url);
        }
    }
 
    private NotificationManager manager;
    private Notification notif;
    private Notification.Builder oBuilder;
    private NotificationCompat.Builder builder;
    int j = -1;
 
    String tempUrl = null;
 
    private void startDownLoadFile(String url) {
        tempUrl = url;
        if (mPermissionsChecker.lacksPermissions(getPermissions())) {//检测是否有写入的权限
            mPermissionsChecker.showNormalDialog();
            return;
        }
        tempUrl = null;
 
        new DownFiles(this, new IProgress() {
 
            @Override
            public void getProgress(int p) {
                // stub
                if (p > 99) {
                    handler.sendEmptyMessage(1);
                    Log.i("DownFiles", "getProgress下载进度:" + p);
                } else {
                    if (manager == null) {
                        Toast.makeText(BrowserActivity.this, "文件已经开始下载",
                                Toast.LENGTH_SHORT).show();
                        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        String id = "YSDQ_DOWNLOAD";
                        String description = ManifestDataUtil.getAppMetaData(BrowserActivity.this, id);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            int importance = NotificationManager.IMPORTANCE_HIGH;
                            NotificationChannel mChannel = new NotificationChannel(id, "影视大全下载", importance);
                            mChannel.setDescription(description);
                            mChannel.enableLights(true);
                            mChannel.setLightColor(Color.RED);
                            //关闭震动
                            mChannel.enableVibration(false);
                            mChannel.setVibrationPattern(new long[]{0});
                            manager.createNotificationChannel(mChannel);
                            oBuilder = new Notification.Builder(BrowserActivity.this, id);
                            oBuilder.setContentTitle("影视大全")
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                                    .setContentText("热门应用下载")
                                    .setAutoCancel(true)
                                    .build();
                        } else {
                            builder = new NotificationCompat.Builder(BrowserActivity.this);
                            builder.setContentTitle("影视大全")
                                    .setContentText("热门应用下载")
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setOngoing(true);//无效
                        }
                    }
 
                    Message msg = handler.obtainMessage();
                    if (j != p) {
                        msg.what = 0;
                        msg.arg1 = p;
                        handler.sendMessage(msg);
                    }
                    j = p;
                }
            }
        }).execute(url);
    }
 
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        oBuilder.setContentText(msg.arg1 + "%");
                        notif = oBuilder.build();
                    } else {
                        builder.setContentText(msg.arg1 + "%");
                        notif = builder.build();
                    }
                    manager.notify(0, notif);
                    break;
                case 1:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        oBuilder.setContentText("下载完成");
                        notif = oBuilder.build();
                    } else {
                        builder.setContentText("下载完成");
                        notif = builder.build();
                    }
                    manager.notify(0, notif);
                    j = 100;
                    manager.cancelAll();
                    break;
                default:
                    break;
            }
        }
    };
 
    @Override
    public void onResume() {
        super.onResume();
        if (webview != null) {
            webview.loadUrl("javascript:onResume()");
        }
    }
 
    @Override
    public void onPause() {
        super.onPause();
    }
 
    @Override
    protected void onDestroy() {
        if (webview != null) {
            webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webview.clearHistory();
 
            ((ViewGroup) webview.getParent()).removeView(webview);
            webview.destroy();
            webview = null;
        }
        super.onDestroy();
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_top_bar_left: {
                if (!webview.canGoBack())
                    finishPage();
                else {
                    webview.goBack();
                }
            }
            break;
            case R.id.tv_top_bar_left2: {
                finishPage();
            }
            break;
            default:
                break;
        }
    }
 
    private void finishPage() {
        if (needSetResult)
            setResult(Activity.RESULT_OK);
        finish();
    }
 
    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                finishPage();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
 
 
    /**
     * 权限请求码
     *
     * @return
     */
    @Override
    public int getPermissionsRequestCode() {
        return 1001;
    }
 
    /**
     * 请求权限
     *
     * @return
     */
    @Override
    public String[] getPermissions() {
        return new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    }
 
    /**
     * 权限请求成功
     */
    @Override
    public void requestPermissionsSuccess() {
        if (!StringUtils.isNullOrEmpty(tempUrl)) {
            startDownLoadFile(tempUrl);
        }
    }
 
    /**
     * 权限请求失败
     */
    @Override
    public void requestPermissionsFail() {
//        Toast.makeText(this, "你以拒绝权限", Toast.LENGTH_SHORT).show();
    }
 
    /**
     * 请求权限结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (mPermissionsChecker.requestPermissionsResult(requestCode, permissions, grantResults)) {
            //权限请求结果,并已经处理了该回调
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}