天天看點

安卓中實作異步任務(3)——使用HandlerThread實作# 安卓中實作異步任務(3)——使用HandlerThread實作

# 安卓中實作異步任務(3)——使用HandlerThread實作

問題背景

實作demo

(1)建立我們的activity,對應layout布局如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.HandlerThreadActivity">
    <Button
        android:id="@+id/btn1"
        android:text="啟動子線程"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</androidx.constraintlayout.widget.ConstraintLayout>
           

(2)對應我們activity的代碼如下:

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

public class HandlerThreadActivity extends AbstractSubActivity {
    private static final String TAG = "HandlerThreadActivity";
    Button button;

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

        button = findViewById(R.id.btn1);

        Thread.currentThread().setName("主線程");
        Log.d(TAG, "主線程目前線程名為" + Thread.currentThread().getId()
                + " " + Thread.currentThread().getName());

        HandlerThread handlerThread = new HandlerThread("子線程");
        handlerThread.start();
        Handler handler = new Handler(handlerThread.getLooper(), msg -> {
            if (msg.what == 1) {
                Log.d(TAG, "handlerThread目前線程名為:" + Thread.currentThread().getId()
                        + " " + Thread.currentThread().getName());
            }
            return true;
        });
    }
}
           

執行結果如下:

關鍵代碼分析