ภาพรวม
ตัวอย่างนี้สาธิตวิธีการแสดง Toast จากเธรดพื้นหลัง (Background Thread) ใน Android เนื่องจาก Toast ต้องถูกเรียกใช้บนเธรดหลัก (Main/UI Thread) เท่านั้น จึงต้องใช้กลไกการสื่อสารระหว่างเธรด
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio → File → New Project → เลือก Empty Activity → กรอกรายละเอียดให้ครบถ้วน
ขั้นตอนที่ 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">
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Toast toast;
private Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// สร้าง Toast object บน UI Thread
toast = Toast.makeText(this, "This is a toast from Thread", Toast.LENGTH_SHORT);
// สร้างและเริ่ม Background Thread
thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
try {
Thread.sleep(1000);
// ต้องใช้ runOnUiThread เพื่อแสดง Toast บน UI Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
toast.show();
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
}
}
⚠️ หมายเหตุสำคัญ
โค้ดต้นฉบับมีปัญหา: เรียก toast.show() โดยตรงจาก Background Thread ซึ่งจะทำให้เกิด Crash จริงๆ ต้องใช้ runOnUiThread() หรือ Handler แทน (โค้ดข้างบนได้แก้ไขแล้ว)
ขั้นตอนที่ 4: กำหนดค่าใน AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<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>
การทดสอบ
รันแอปบนอุปกรณ์จริง → จะเห็น Toast แสดงทุก 2 วินาที (1 วินาที Sleep + 1 วินาที Sleep)
วิธีอื่นที่แนะนำ
- Handler + Looper.getMainLooper(): เหมาะสำหรับงานที่ซับซ้อนกว่า
- LiveData / Flow (Kotlin): แนวทางสมัยใหม่สำหรับการสื่อสารข้ามเธรด
- Coroutines (Kotlin): ใช้
withContext(Dispatchers.Main)สลับไป UI Thread ได้ง่าย