package com.yzx.webebook.activity import android.annotation.SuppressLint import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.Intent import android.net.http.SslError import android.os.Build import android.text.TextUtils import android.util.Log import android.view.View import android.view.ViewGroup import android.webkit.* import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import androidx.annotation.RequiresApi import androidx.core.widget.ContentLoadingProgressBar import com.allenliu.versionchecklib.callback.APKDownloadListener import com.allenliu.versionchecklib.v2.AllenVersionChecker import com.allenliu.versionchecklib.v2.builder.UIData import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener import com.blankj.utilcode.util.AppUtils import com.blankj.utilcode.util.SPUtils import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.lzy.okgo.OkGo import com.lzy.okgo.callback.StringCallback import com.lzy.okgo.model.Response import com.yzx.webebook.MainActivity import com.yzx.webebook.R import com.yzx.webebook.activity.base.BaseActivity import com.yzx.webebook.model.BaseBean import com.yzx.webebook.model.Version import com.yzx.webebook.presenter.base.BasePresenter import com.yzx.webebook.widget.BaseDialog import kotlinx.android.synthetic.main.activity_web.* import org.jetbrains.anko.ctx import org.jetbrains.anko.find import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast import org.json.JSONObject import java.io.File import java.util.* /** * 类名:WebActivity * 作者:Yun.Lei * 功能: * 创建日期:2020年5月6日14:42:16 * 修改人: * 修改时间: * 修改备注: */ class WebActivity : BaseActivity>() { companion object { fun active(act: Activity, link: String) { act.startActivity("link" to link) } } private val webView: WebView by lazy { WebView(this) } private var url: String = "" private var count = 0 private val run = Runnable { count = 0 } override val inflateId: Int get() = R.layout.activity_web override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) url = intent?.getStringExtra("link") ?: "https://m.qbjjyyun.net/" this.initData() } fun checkVersion(userCheck: Boolean = false): Unit { val test = "192.168.69.112:9009" val online = "https://oa.qbjjyyun.net/api" val BASE_URL = online OkGo.post("$BASE_URL/parent/common/getInkBottleMaxVersion") .tag(this) .execute(object : StringCallback() { override fun onSuccess(response: Response) { val json = response.body() Log.d("checkVersion", "onSuccess: ${json}") val resultType = object : TypeToken>() {}.type val gson = Gson() val res = gson.fromJson>(json, resultType) if (res.code == 0) { val appVersion = AppUtils.getAppVersionName() val appVersionCode = AppUtils.getAppVersionCode() val versionCode = res?.data?.version_code ?: 0 val curr = Date().time val lastTipTime = SPUtils.getInstance() .getLong("last_tip_time${res.data.version_code}", 0) if (versionCode > appVersionCode) { //有新版本 when { res.data.type == 1 -> { //强制升级 updateApp(res.data) } curr - lastTipTime > 24 * 60 * 60 * 1000 -> { //非强制一天以内提示一次 updateApp(res.data) } userCheck -> { // updateApp(res.data) } } } else { if (userCheck) { toast("已经是最新版本了!") } } } } }) } private fun updateApp(version: Version) { AllenVersionChecker .getInstance() .downloadOnly( UIData.create() .setTitle("检测到新版本") .setContent(version.explain) // .setDownloadUrl("https://oa-edu-1259243469.cos.ap-chengdu.myqcloud.com/public/Yzx_2.0.0.apk") // .setDownloadUrl("https://filea.oa.qbjjyyun.net/edufile/202102/5986/27a58c0b85cb42aee37ce85fe956b743.apk") .setDownloadUrl(version.app_src) ) .setCustomVersionDialogListener { context, versionBundle -> val dialog = BaseDialog(context, R.style.BaseDialog, R.layout.version_dialog) val title = dialog.find(R.id.tv_title) title.text = "检测到新版本" val content = dialog.find(R.id.tv_msg) content.text = version.explain dialog.window?.setDimAmount(0.5f) val cancelBtn = dialog.find(R.id.cancel_btn) if (version.type == 1) { cancelBtn.visibility = View.GONE } return@setCustomVersionDialogListener dialog } .setOnCancelListener { SPUtils.getInstance().put("last_tip_time${version.version_code}", Date().time) } .setCustomDownloadingDialogListener(object : CustomDownloadingDialogListener { @SuppressLint("SetTextI18n") override fun updateUI(dialog: Dialog?, progress: Int, versionBundle: UIData?) { val tvProgress: TextView = dialog!!.findViewById(R.id.tv_progress) val progressBar: ContentLoadingProgressBar = dialog.findViewById(R.id.pb) progressBar.progress = progress tvProgress.text = "$progress%" Log.d("checkVersion", "onSuccess: ${progress}") } override fun getCustomDownloadingDialog( context: Context?, progress: Int, versionBundle: UIData? ): Dialog { return BaseDialog( context!!, R.style.BaseDialog, R.layout.download_dialog ) } }) .executeMission(this) } @SuppressLint("SetJavaScriptEnabled") override fun initView() { url = intent?.getStringExtra("link") ?: "https://m.qbjjyyun.net/" titleTv.setOnClickListener { count++ titleTv.removeCallbacks(run) titleTv.postDelayed(run, 1000) if (count >= 5) { startActivity() } } btnBack.setOnClickListener { onBackPressed() } btnClose.setOnClickListener { webView.loadUrl(url) } btnRefresh.setOnClickListener { webView.reload() } webView.layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) webLayout.addView(webView) webView.addJavascriptInterface(YzxJavascriptInterface(this), "YZX") val userAgent = webView.settings.userAgentString webView.settings.apply { allowFileAccess = true javaScriptEnabled = true loadWithOverviewMode = true useWideViewPort = true defaultTextEncodingName = "gb2312" setAppCacheEnabled(true) mediaPlaybackRequiresUserGesture = false javaScriptCanOpenWindowsAutomatically = true cacheMode = WebSettings.LOAD_DEFAULT databaseEnabled = true setRenderPriority(WebSettings.RenderPriority.HIGH) blockNetworkImage = false domStorageEnabled = true setAppCacheMaxSize(1024 * 1024 * 8) setAppCachePath(ctx.cacheDir.absolutePath) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW } userAgentString = "$userAgent app/ebook" } webView.webViewClient = object : WebViewClient() { @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { view?.loadUrl(request?.url.toString()) return super.shouldOverrideUrlLoading(view, request) } // 即使加载失败后,webview执行完onReceivedError()方法也会执行这个方法 override fun onPageFinished(view: WebView, url: String) { super.onPageFinished(view, url) webView.settings.blockNetworkImage = false if (!TextUtils.isEmpty(view.title)) { titleTv.text = view.title//webView获取到网页title } } override fun onReceivedSslError( view: WebView, handler: SslErrorHandler, error: SslError ) { handler.proceed() } } webView.webChromeClient = object : WebChromeClient() { override fun onProgressChanged(view: WebView?, newProgress: Int) { super.onProgressChanged(view, newProgress) progressbar.progress = newProgress if (newProgress >= 100) { view?.post { progressbar.visibility = View.GONE if (view.canGoBack()) { btnBack.visibility = View.VISIBLE // btnClose.visibility = View.VISIBLE } else { btnBack.visibility = View.GONE // btnClose.visibility = View.GONE } } } else { if (progressbar.visibility == View.GONE) { view?.post { progressbar.visibility = View.VISIBLE } } } } override fun onJsAlert( view: WebView?, url: String?, message: String?, result: JsResult? ): Boolean { val b = AlertDialog.Builder(this@WebActivity) b.setTitle(message) b.setPositiveButton("确定") { _, _ -> result?.confirm() } return true } } WebView.setWebContentsDebuggingEnabled(true) //将 WebViews 配置为可调试状态 webView.setLayerType(View.LAYER_TYPE_HARDWARE, null) } override fun initData() { webView.loadUrl(url) } override fun initPresenter(): BasePresenter<*>? { return null } override fun onResume() { super.onResume() webView.onResume() checkVersion() } override fun onPause() { super.onPause() webView.onPause() } override fun onBackPressed() { if (webView.canGoBack()) { webView.goBack() } else { super.onBackPressed() } } override fun onDestroy() { super.onDestroy() webView.apply { // webViewClient = null webChromeClient = null (parent as ViewGroup).removeView(webView) removeAllViews() destroy() } AllenVersionChecker.getInstance().cancelAllMission() } /** * 调用js方法 */ private fun evaluateJavascript(funName: String, data: String) { webView.post { webView.evaluateJavascript("javascript:$funName('$data')") { Log.d("javascriptCallBack:", it) //toast(it) } } } @SuppressLint("SetTextI18n") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == BookActivity.REQ_CODE && resultCode == Activity.RESULT_OK) { val mKey = data?.getStringExtra("key") ?: "" val mIdentity = data?.getStringExtra("identity") ?: "" val obj = JSONObject() obj.put("key", mKey) obj.put("identity", mIdentity) obj.put("name", data?.getStringExtra("name") ?: "") obj.put("index", data?.getIntExtra("index", 0)) obj.put("type", data?.getIntExtra("type", 1)) evaluateJavascript("onImageUploadSuccess", obj.toString()) } if (requestCode == NoteActivity.REQ_CODE && resultCode == Activity.RESULT_OK) { val json = data?.getStringExtra("note_info") ?: "" evaluateJavascript("onImageUploadSuccess", json) } } } class YzxJavascriptInterface(var ctx: Activity) { /** * 获取电子书的clientId */ @JavascriptInterface fun getClientId(): Int = 601 /** * 跳转到电子书页面 */ @JavascriptInterface fun bookPage( title: String, identity: String, key: String, name: String, index: Int, type: Int ) { BookActivity.active(ctx, title, key, identity, name, index, type) } /** * 跳转到笔记页面 * @param title 展示的title * @param note_info 笔记得json,新的笔记 传"" ,老的笔记 传 [{"BGid":0,"identity":"fileb","key":"a92511a457cdc444bb274e5dee29c487"}] * @param can_add_page 是否可以新加纸,1可以,0不可以 */ @JavascriptInterface fun notePage( title: String, note_info: String, can_add_page: Int = 1 ) { NoteActivity.active(ctx, title, note_info, can_add_page) } /** * 跳转到笔记页面 * @param title 展示的title * @param note_info 笔记得json,新的笔记 传"" ,老的笔记 传 [{"BGid":0,"identity":"fileb","key":"a92511a457cdc444bb274e5dee29c487"}] */ @JavascriptInterface fun notePage( title: String, note_info: String ) { NoteActivity.active(ctx, title, note_info, 1) } /** * 提示 */ @JavascriptInterface fun toast(msg: String) { ctx.toast("android:$msg") } /** * 检查版本升级 */ @JavascriptInterface fun mCheckVersion() { Log.d("mCheckVersion", "mCheckVersion: -------------------->") val act = ctx as WebActivity act.checkVersion(true) } }