ก่อนจะเริ่มตัวอย่าง เราควรเข้าใจก่อนว่า Thread คืออะไร Thread เป็นกระบวนการย่อยที่มีน้ำหนักเบา ทำงานเบื้องหลังโดยไม่รบกวน UI ตัวอย่างนี้สาธิตวิธีการใช้ thread.sleep() ใน Android
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2: ออกแบบหน้าจอ (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="100dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter string" />
<Button
android:id="@+id/click"
android:layout_marginTop="50dp"
style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:background="#c1c1c1"
android:textColor="#FFF"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
ในโค้ดด้านบน เรามี EditText และ TextView เมื่อผู้ใช้ป้อนข้อความใน EditText จะรอ 5000ms แล้วอัปเดต TextView
ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText edit_query;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_query = findViewById(R.id.edit_query);
textView = findViewById(R.id.text);
findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runThread();
}
});
}
private void runThread() {
final String text = edit_query.getText().toString();
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(text);
try {
// หยุดการทำงาน 5000 มิลลิวินาที (5 วินาที)
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
});
}
}
การทดสอบแอปพลิเคชัน
เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอเริ่มต้น

ผลลัพธ์: ป้อนข้อความใน EditText แล้วกดปุ่ม หลังจาก 5000ms (5 วินาที) จะอัปเดต TextView
หมายเหตุ: การใช้ Thread.sleep() บน UI Thread จะทำให้แอปพลิเคชันหยุดตอบสนอง (ANR) ในทางปฏิบัติควรใช้ Handler.postDelayed() หรือ Kotlin Coroutines แทน