Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีแสดงข้อความ Toast จาก Thread ใน Android ด้วย Kotlin

ภาพรวม

ตัวอย่างนี้สาธิตวิธีแสดงข้อความ Toast จาก Thread พื้นหลังในแอปพลิเคชัน Android โดยใช้ภาษา Kotlin เนื่องจาก Toast ต้องทำงานบน UI Thread หลัก จึงต้องใช้กลไกการสื่อสารระหว่าง Thread อย่างเหมาะสม

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio เลือก File → New Project กรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (activity_main.xml)

<?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)

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var toast: Toast
    private lateinit var backgroundThread: Thread

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        // สร้าง Toast object ล่วงหน้า
        toast = Toast.makeText(this, "This is a toast from Thread", Toast.LENGTH_SHORT)

        // สร้าง Thread พื้นหลัง
        backgroundThread = Thread(Runnable {
            for (i in 0..999) {
                try {
                    Thread.sleep(1000)
                    // ต้องรันบน UI Thread
                    runOnUiThread { toast.show() }
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        })
        backgroundThread.start()
    }
}

ขั้นตอนที่ 4: กำหนดค่า Manifest (AndroidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.toastfromthread">

    <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 เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นเป้าหมาย จากนั้นตรวจสอบหน้าจออุปกรณ์ จะเห็นข้อความ Toast ปรากฏขึ้นทุก 2 วินาที

หมายเหตุสำคัญ

  • ใช้ runOnUiThread เพื่อแสดง Toast จาก Thread พื้นหลัง
  • ควรยกเลิก Thread เมื่อ Activity ถูกทำลาย เพื่อป้องกัน Memory Leak
  • ในการพัฒนาจริง ควรพิจารณาใช้ Coroutines หรือ Handler แทน Thread ตรงๆ