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

Cách hiển thị Toast từ luồng nền (Thread) trong Android

Giới thiệu

Ví dụ này minh họa cách hiển thị Toast từ một luồng nền (background thread) trong Android. Vì Toast chỉ có thể hiển thị từ luồng chính (UI thread), chúng ta cần sử dụng runOnUiThread() hoặc Handler.

Các bước thực hiện

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/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>

Bước 3: Viết code MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Toast toast;
    Thread thread;

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

        toast = Toast.makeText(this, "Đây là Toast từ Thread", Toast.LENGTH_SHORT);

        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    try {
                        Thread.sleep(1000);
                        // Phải chạy trên UI thread
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                toast.show();
                            }
                        });
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }
}

Cải tiến quan trọng: Code gốc gọi toast.show() trực tiếp từ thread nền - điều này sẽ gây crash. Phải dùng runOnUiThread() hoặc Handler(Looper.getMainLooper()).

Bước 4: Cấu hình 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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run và quan sát Toast xuất hiện mỗi 2 giây.

Cách hiển thị Toast từ luồng nền (Thread) trong Android