320x100
이때까지 작성한 글에 맞춰
1. new thread에서 작업 class 호출
2. 1초당 count 1증가
3. count 가 10이 될 시 강제 에러 발생
4. 특정 에러 상황 분기 처리
5. count 증가나 에러 발생 시 text를 ui에 반영
위 기준으로 예제를 만들어보기로 한다
작성한 쓰레드 생성 글은 상속받고 사용하지만
이번에는 상속받지 않고,
class로 처리해서
쓰레드에서 class를 호출하도록 구현했다
ui 변동의 경우
고차 함수를 활용했으며,
runOnUiThread를 통해
변경이 이루어지게 구현했다
코드 1 : MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var bStart: Button
private lateinit var tvMsg: TextView
// 고차 함수를 활용한 새로운 쓰레드에서 msgUpdate 호출
private val threadLogMsg: (msg: String) -> Unit = { msg ->
msgUpdate(msg)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bStart = findViewById(R.id.b_start)
tvMsg = findViewById(R.id.tv_msg)
bStart.setOnClickListener { jobStart(it as Button) }
}
private fun jobStart(button: Button) {
// 버튼 비활성화(중복 터치 막기)
button.isEnabled = false
object: Thread() {
override fun run() {
// 에러 처리
try {
JobThrow().start(threadLogMsg)
} catch(e: Exception) {
when(e) {
is NullPointerException -> {
msgUpdate("NullPointerException\n발생 !!")
}
is NumberFormatException -> {
msgUpdate("NumberFormatException\n발생 !!")
}
else -> {
msgUpdate("$e\n발생 !!")
}
}
} finally {
// 버튼 활성화로 전환
runOnUiThread { button.isEnabled = true }
}
}
}.start()
}
// 텍스트 업데이트
private fun msgUpdate(msg: String) {
runOnUiThread {
tvMsg.text = msg
}
}
}
코드 2 : JobThrow.kt
class JobThrow {
fun start(threadLogMsg: (msg: String) -> Unit) {
threadLogMsg("JobThrow start method !!")
var idx = 0
while(true) {
Thread.sleep(1000)
idx++
threadLogMsg("idx : $idx")
// idx 가 10일 시 강제로 에러를 발생
if(idx == 10) throw NullPointerException()
// if(idx == 10) throw NumberFormatException()
// if(idx == 10) throw RuntimeException()
}
}
}
코드 3 : activity_main.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=".MainActivity" >
<Button
android:id="@+id/b_start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="시작" />
<TextView
android:id="@+id/tv_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="none"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
</LinearLayout>
320x100
'Android > Kotlin' 카테고리의 다른 글
[Android][Kotlin] 캘린더(Calendar)로 오늘 날짜(today), 마지막 일(last day) 가져오기 (0) | 2022.10.24 |
---|---|
[Android][Kotlin] 단말기(device) 가로 세로 실제 해상도 가져오기 (0) | 2022.10.21 |
[Android][Kotlin] 알람매니저(AlarmManager)를 이용한 알림(Notification) 호출하기 (0) | 2022.10.14 |
[Android][Kotlin] 알림(Notification) 생성, 호출하기 (0) | 2022.10.13 |
[Android][Kotlin] 캘린더(CalendarView) 생성, 오늘 날짜, 클릭 이벤트 (0) | 2022.10.12 |