okhttp3下载工具类kotlin及apk安装

2020-07-27  本文已影响0人  吃饱了就送

object DownloadUtil {
    private val okHttpClient: OkHttpClient = OkHttpClient()
    private var context: Context? = null
    private val TAG = javaClass.simpleName

    /**
     * @param url 下载连接
     * @param listener 下载监听
     */
    fun download(context: Context?, url: String?, listener: OnDownloadListener) {
        this.context = context
        // 需要token的时候可以这样做
        // Request request = new Request.Builder().header("token",token).url(url).build();
        val request: Request = Request.Builder().url(url).build()
        okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                e?.printStackTrace()
                listener.onDownloadFailed()
            }

            override fun onResponse(call: Call?, response: Response) {
                var inputStream: InputStream? = null
                val buf = ByteArray(2048)
                var len = 0
                var fos: FileOutputStream? = null
                try {
                    inputStream = response.body()?.byteStream()
                    val total: Long = response.body()?.contentLength()!!
                    var downloadPath = File(AppConfig.DEFAULT_SAVE_APK_PATH,"apk/")
                    if (!downloadPath.mkdirs()) {
                        downloadPath.createNewFile()
                    }
                    val file = File(downloadPath.absoluteFile,AppConfig.DEFAULT_APK_NAME)
                    Log.w(TAG, "最终路径:$file")
                    fos = FileOutputStream(file)
                    var sum: Long = 0
                    while (inputStream?.read(buf).also { len = it!! } != -1) {
                        fos.write(buf, 0, len)
                        sum += len.toLong()
                        val progress = (sum * 1.0f / total * 100).toInt()
                        listener.onDownloading(progress)
                    }
                    fos.flush()
                    listener.onDownloadSuccess(file)
                } catch (e: Exception) {
                    listener.onDownloadFailed()
                } finally {
                    try {
                        inputStream?.close()
                        fos?.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        })
    }


    interface OnDownloadListener {
        /**
         * 下载成功
         */
        fun onDownloadSuccess(file: File)

        /**
         * @param progress
         * 下载进度
         */
        fun onDownloading(progress: Int)

        /**
         * 下载失败
         */
        fun onDownloadFailed()
    }
}
class AppConfig {
 var DEFAULT_SAVE_APK_PATH = (Environment
                .getExternalStorageDirectory().toString()
                + File.separator
                + "xxx.xxx.xxx"
                + File.separator)
var DEFAULT_APK_NAME = "app.apk"
}

使用

DownloadUtil.download(mContext, downUrl,object : DownloadUtil.OnDownloadListener {
            override fun onDownloadSuccess(file: File) {
                installApk(file);
            }

            override fun onDownloading(progress: Int) {
                 Log.e(TAG,"onDownloading" + progress)
            }

            override fun onDownloadFailed() {
                Log.e(TAG,"onDownloadFailed")
            }
        })
private fun installApk(apkFile: File) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            val contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName().toString() + ".FileProvider", apkFile)
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
        }
        startActivity(intent)
    }

最后加上权限

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
上一篇 下一篇

猜你喜欢

热点阅读