Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách dùng Thread.sleep() trong Android

Giới thiệu

Thread.sleep(millis) tạm dừng thread hiện tại. Lưu ý: không nên sleep trên main thread (UI thread) vì sẽ treo giao diện. Ví dụ này dùng Handler để delay an toàn.

Bước 1-2: Project & Giao diện

EditText, Button, TextView.

Bước 3: MainActivity.java - dùng Handler.postDelayed

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(v -> {
            final String text = edit_query.getText().toString();
            if (text.isEmpty()) return;

            new Handler().postDelayed(() -> {
                // Chạy trên main thread sau 5 giây
                textView.setText(text);
            }, 5000);
        });
    }
}

Lưu ý quan trọng: Không gọi Thread.sleep() trực tiếp trên main thread. Hãy dùng Handler.postDelayed(), CountDownTimer, hoặc Kotlin Coroutines.

Chạy ứng dụng

Nhập text, nhấn nút. Sau 5 giây TextView hiển thị nội dung.

Cách dùng Thread.sleep() trong Android