/**
* Created by zxy on 2019/10/8-9:59
* Class functions
* ******************************************
* * 多线程
* ******************************************
*/
class ExecutorActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_executor)
MyAsyncTask(this).execute("1", "2")
}
/**
* String: MyAsyncTask(this).execute("1", "2")
* String:onProgressUpdate()参数类型
* String:doInBackground()参数类型
* @property activityReference WeakReference<Activity> 弱引用 内存泄漏
*/
class MyAsyncTask : AsyncTask<String, String, String> {
private var activityReference: WeakReference<Activity>
constructor(context: Activity) {
activityReference = WeakReference<Activity>(context)
}
/**
* 异步执行开始之前的准备工作,比如弹出Dialog
*/
override fun onPreExecute() {
super.onPreExecute()
}
/**
* 做耗时操作
* @param p0 Array<out String?>
* @return String?
*/
override fun doInBackground(vararg p0: String?): String? {
publishProgress(*p0) //子线程中的值发送到onProgressUpdate中做更新
return null
}
/**
* 更新UI进度
* @param values Array<out String?>
*/
override fun onProgressUpdate(vararg values: String?) {
super.onProgressUpdate(*values)
val ExecutorActivity = activityReference.get()
val textView = ExecutorActivity!!.findViewById<TextView>(R.id.tv)
textView.setText(values[0].toString())
Log.e("msg", values[0].toString())
}
/**
* 完成
* @param result String
*/
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
Log.e("msg", "${result}result")
}
}
}