개요
이 예제는 Kotlin을 사용해 Android 앱의 백그라운드 스레드(Thread) 내부에서 토스트(Toast) 메시지를 표시하는 방법을 단계별로 설명합니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 항목을 입력하고 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성
아래 코드를 res/layout/activity_main.xml에 추가합니다. 화면 중앙에 간단한 TextView 하나만 배치하는 기본 레이아웃입니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="100dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
</RelativeLayout>3단계 — MainActivity.kt 작성
아래 코드를 src/MainActivity.kt에 추가합니다. 여기서 핵심은 별도의 스레드를 생성해 1초마다 토스트를 반복해서 띄우는 부분입니다.
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var toast: Toast
lateinit var thread: Thread
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
toast = Toast.makeText(this, "This is a toast from Thread", Toast.LENGTH_SHORT)
thread = Thread(Runnable {
for (i in 0..999) {
try {
Thread.sleep(1000)
toast.show()
Thread.sleep(1000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
})
thread.start()
}
}코드 설명:
Toast.makeText()로 표시할 메시지를 미리 준비합니다.Thread(Runnable { ... })로 백그라운드 스레드를 만들고thread.start()로 실행합니다.- 스레드는 총 1,000번 반복하며, 1초 대기 → 토스트 표시 → 1초 대기 순서로 동작하므로 약 2초 간격으로 토스트가 나타납니다.
참고 팁: 일부 기기나 Android 버전에서는 Looper가 없는 백그라운드 스레드에서 직접 toast.show()를 호출하면 오류가 발생할 수 있습니다. 이 경우 아래처럼 UI 스레드에서 실행하도록 감싸주면 더 안전합니다.
runOnUiThread {
toast.show()
}4단계 — AndroidManifest.xml 설정
아래 코드를 androidManifest.xml에 추가합니다. 특별한 권한은 필요하지 않으며, 기본 액티비티 등록만 포함됩니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 Run(실행) 아이콘
을 클릭합니다. 목록에서 연결된 모바일 기기를 선택하면, 기기 화면에 앱이 실행되고 약 2초마다 "This is a toast from Thread"라는 토스트 메시지가 반복해서 표시되는 것을 확인할 수 있습니다.
