Kotlin:实现APP的本地升级与下载更新 发表于 2019-08-20 更新于 2019-08-20
广州
开发 android Kotlin:实现APP的本地升级与下载更新 ❄️2winter 2019-08-20 2019-08-20 这里就不写服务端的东西了。
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 class Utils { companion object { val versionUrl = "http://www.xxx.com" val versionWd = "https://www.sxxx/xx.apk" fun Tos (str:String ) { Toast.makeText(WdTools.getContext(),str,Toast.LENGTH_SHORT).show() } fun requestUpVersion (hand:Handler ) { var versionOld = 0 val client = OkHttpClient.Builder().build() thread { val request = Request.Builder().url(versionUrl).build() client.newCall(request).enqueue(object : Callback { override fun onResponse (call: Call , response: Response ) { val resText = response.body()?.string() val temResText: String? = resText versionOld = temResText!!.replace(" " ,"" ).toInt() Log.d("@@versionWD:" ,versionOld.toString()) val msg = Message() msg.what = 0x21 msg.arg1 = versionOld hand.sendMessage(msg) } override fun onFailure (call: Call , e: IOException ) { val msg = Message() msg.what = 0x22 hand.sendMessage(msg) } }) } } fun DownNew () :Long { val request = DownloadManager.Request(Uri.parse(versionWd)) request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); request.setDestinationInExternalFilesDir(WdTools.getContext(), Environment.DIRECTORY_DOWNLOADS,"wd.apk" ) request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) request.setTitle("正在下载xx更新" ) request.setDescription("下载完成后请点击打开" ) request.setVisibleInDownloadsUi(true ) request.allowScanningByMediaScanner() request.setMimeType("application/vnd.android.package-archive" ) val downloadManager = WdTools.getContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager return downloadManager.enqueue(request) } fun getVersion (activity:Activity ) :Int { var version:String? = null try { val manager = activity.packageManager val info = manager.getPackageInfo(activity.packageName, 0 ) version ="${info.versionCode} " } catch (e:Exception) { } return version!!.toInt() } }
调用检查:如果服务端返回的版本号大于当前的,调用下载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 if (msg.arg1 > Utils.getVersion(this @WDMain )){ Utils.Tos("新版本" ) temDialog = AlertDialog.Builder(this @WDMain ).setCancelable(false ) .setTitle("检测到新版本!" ).setMessage("是否立即更新?" ) .setPositiveButton("确定" ){ _,_ -> Utils.DownNew() Utils.Tos("请稍后查看通知栏进度!" ) }.setNegativeButton("取消" ){ _,_ -> }.create() temDialog!!.show() } else { Utils.Tos("当前是最新版本" ) }
❄️2winter
ReactNative FullStack Developer
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ❄️2winter !