解析
在一些应用场景,需要创建一个线程进行修改页面上的内容
上述需求需要在主线程上创建子线程去更改主线程上的UI,但是为了线程安全,不允许子线程更改主线程的UI


要实现上述就需要用到handler


实例
1、需求:点击下一条信息按钮,异步显示信息

2、activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/show"
android:text="hello"
></TextView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/next"
android:text="下一条"
></Button>
</LinearLayout>
3、MainActivity.java
package com.example.content_provider_page;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private String columns = ContactsContract.Contacts.DISPLAY_NAME;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.show);
Button button = findViewById(R.id.next);
// 主线程监听处理信息
Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
// 通过信息标识,响应该标识的信息
if(msg.what == 0x111){
textView.setText("world");
}
}
};
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Thread th = new Thread(new Runnable() {
@Override
public void run() {
// what参数表示信息标识,通过该表示可以进行标识是属于哪样的信息
handler.sendEmptyMessage(0x111);
}
});
th.start();
}
});
}
}










