handler发消息到消息队列,循环器取消息给handler处理
DownloadActivity
class DownloadActivity : AppCompatActivity() {
private val DOWNLOAD_MESSAGE_CODE = 100001
private val DOWNLOAD_MESSAGE_FAIL_CODE = 100002
val APP_URL =
"http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk"
private val mHandler = MyHandler(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_download)
/**
* 主线程 -- > start
* 点击按键 |
* 发起下载 |
* 开启子线程做下载 |
* 下载过程中通知主线程 | -- > 主线程更新进度条
*/
button2.setOnClickListener {
thread {
download(APP_URL)
}
}
}
private fun download(appUrl: String) {
try {
val url = URL(appUrl)
val urlConnection = url.openConnection()
val inputStream = urlConnection.getInputStream()
//获取文件的总长度
val contentLength = urlConnection.contentLength
val downloadFolderName =
Environment.getExternalStorageDirectory()
.toString() + File.separator + "imooc" + File.separator
val file = File(downloadFolderName)
if (!file.exists()) {
file.mkdir()
}
val fileName = downloadFolderName + "imooc.apk"
val apkFile = File(fileName)
if (apkFile.exists()) {
apkFile.delete()
}
var downloadSize = 0
val bytes = ByteArray(1024)
var length: Int
val outputStream: OutputStream = FileOutputStream(fileName)
while (inputStream.read(bytes).also { length = it } != -1) {
outputStream.write(bytes, 0, length)
downloadSize += length
//update UI
val message = Message.obtain()
message.obj = downloadSize * 100 / contentLength
message.what = DOWNLOAD_MESSAGE_CODE
mHandler.sendMessage(message)
}
inputStream.close()
outputStream.close()
} catch (e: MalformedURLException) {
notifyDownloadFaild()
e.printStackTrace()
} catch (e: IOException) {
notifyDownloadFaild()
e.printStackTrace()
}
}
private fun notifyDownloadFaild() {
val message = Message.obtain()
message.what = DOWNLOAD_MESSAGE_FAIL_CODE
mHandler.sendMessage(message)
}
class MyHandler(activity: DownloadActivity) : Handler() {
private val weakReference = WeakReference(activity)
@SuppressLint("SetTextI18n")
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val activity = weakReference.get()
when (msg.what) {
activity?.DOWNLOAD_MESSAGE_CODE -> {
activity.progressBar.progress = (msg.obj as Int)
activity.text666.text = ((msg.obj as Int).toString())+"%"
}
activity?.DOWNLOAD_MESSAGE_FAIL_CODE -> {
}
}
}
}
}