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
| class CenterFragment : Fragment() { lateinit var mPgb: ProgressBar lateinit var textView: TextView private lateinit var centerViewModel: CenterViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { centerViewModel = ViewModelProvider(this).get(CenterViewModel::class.java) val root = inflater.inflate(R.layout.fragment_center, container, false) textView = root.findViewById(R.id.text_center) centerViewModel.text.observe(viewLifecycleOwner, { textView.text = it }) mPgb = root.findViewById(R.id.mPgb) textView.setOnClickListener { initDownload() } return root }
private fun initDownload() { val okHttpClient: OkHttpClient = OkHttpClient.Builder().build() val request: Request = Request.Builder() .url("https://8629e1d8ab66424c0245ed79d86fed17.dlied1.cdntips.net/dlied1.qq.com/qqweb/QQlite/qqlite_4.0.1.1060_537064365.apk") .get() .build() okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("tag", "onFailure: " + e.message); } override fun onResponse(call: Call, response: Response) { val responseBody = response.body() // 获取到请求体 val inputStream = responseBody?.byteStream() // 转换成字节流 val path: String = "" + Environment.getExternalStorageDirectory() + "/" + "qq.apk" saveFile( inputStream, path, responseBody?.contentLength() ) } }) }
private fun saveFile(inputStream: InputStream?, s: String?, l: Long?) { var count: Long = 0 try { // 获取到输出流,写入到的地址 val outputStream = FileOutputStream(File(s!!)) var length = -1 val bytes = ByteArray(1024 * 10) while (inputStream!!.read(bytes).also { length = it } != -1) { // 写入文件 outputStream.write(bytes, 0, length) count += length.toLong() val finalCount = count activity?.runOnUiThread { // 设置进度条最大值 mPgb.setMax(l!!.toInt()) // 设置进度 mPgb.setProgress(finalCount.toInt()) val num = "" + (100 * finalCount / l) + "%" // 设置进度文本 (100 * 当前进度 / 总进度) textView.text = num } } inputStream.close() // 关闭输入流 outputStream.close() // 关闭输出流 activity?.runOnUiThread { // 如果写入的进度值完毕,Toast Toast.makeText(activity, "下载完成", Toast.LENGTH_SHORT).show() } } catch (e: Exception) { e.printStackTrace() } } }
|