# 安卓中实现异步任务(3)——使用HandlerThread实现
问题背景
上篇文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于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;
});
}
}
执行结果如下:
关键代码分析
持续更新。。。
标签:异步,currentThread,Thread,handlerThread,HandlerThread,安卓中,import,android From: https://blog.51cto.com/baorant24/5786136