//AsyncActivity.kt
class AsyncActivity : AppCompatActivity() {
private lateinit var binding: ActivityAsyncBinding
var task: BackgroundAsyncTask? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAsyncBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.start.setOnClickListener {
task = BackgroundAsyncTask(binding.progressBar, binding.ment)
task!!.execute()
}
binding.stop.setOnClickListener {
task!!.cancel(true)
// startActivity(Intent(this, RoomActivity::class.java))
}
}
//액티비티가 종료되도 async는 자동종료되지 않으므로, 액티비티가 puase될 때 async를 종료시켜준다.
override fun onPause() {
super.onPause()
task!!.cancel(true)
}
}
class BackgroundAsyncTask(
val progressbar: ProgressBar,
val progressText: TextView
) : AsyncTask<Int, Int, Int>() {
//params -> doInBackground에서 사용 할 타입
//progress -> onProgressUpdate에서 사용할 타입
//result -> onPostExecute에서 사용할 타입
var percent: Int = 0
//실행하기 바로 직전
override fun onPreExecute() {
percent = 0
progressbar.setProgress(0)
}
override fun doInBackground(vararg params: Int?): Int {
while (isCancelled() == false) {
percent++
Log.e("async", percent.toString())
if (percent > 100) {
break
} else {
//메인쓰레드로
publishProgress(percent)
}
try {
Thread.sleep(100)
} catch (e: Exception) {
e.printStackTrace()
}
}
return percent
}
override fun onProgressUpdate(vararg values: Int?) {
progressbar.setProgress(values[0] ?: 0)
progressText.setText(values[0].toString() ?: "")
super.onProgressUpdate(*values)
}
override fun onPostExecute(result: Int?) {
progressText.setText("작업이 완료되었씁니다")
}
override fun onCancelled() {
progressbar.setProgress(0)
progressText.setText("작업이 취소되었습니다")
}
}
//AsyncActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AsyncActivity">
<TextView
android:id="@+id/ment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AsyncTask"
android:textSize="40dp" />
<ProgressBar
android:id="@+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:max="100" />
<Button
android:id="@+id/start"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="40dp"
android:text="start" />
<Button
android:id="@+id/stop"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="40dp"
android:text="stop" />
</LinearLayout>