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

Cách chạy Thread liên tục (continuous) trong Android

Giới thiệu về Thread trong Android

Thread là đơn vị thực thi song song. Lưu ý quan trọng: Thread không thể cập nhật UI trực tiếp - phải dùng Handler, runOnUiThread, hoặc View.post().

Ví dụ: Thread chạy liên tục in log

Bước 1: Tạo dự án mới

Android Studio → File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Thread liên tục"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Bước 3: Thread liên tục (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = findViewById(R.id.text);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            Log.d("ContinuousThread", "Tutorialspoint.com");
                            try {
                                Thread.sleep(1000); // Nghỉ 1 giây tránh spam log
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                break; // Thoát loop khi bị interrupt
                            }
                        }
                    }
                }).start();
            }
        });
    }
}

Giải thích

  • while(true): Vòng lặp vô hạn
  • Log.d(): Ghi log debug (xem trong Logcat)
  • Thread.sleep(1000): Nghỉ 1 giây mỗi lần lặp (quan trọng để không làm treo CPU)
  • InterruptedException: Bắt khi thread bị interrupt (ví dụ app đóng)
⚠️ Cảnh báo: Thread này chạy mãi mãi cho đến khi process bị kill. Nên có cơ chế dừng:
  • Biến volatile boolean running = true kiểm tra trong while
  • Gọi thread.interrupt() trong onDestroy()
  • Hoặc dùng HandlerThread / ExecutorService quản lý tốt hơn

Chạy ứng dụng

Chạy app → Nhấn TextView → Mở Logcat (filter tag "ContinuousThread") → Xem log in liên tục mỗi giây.