线程的使用离不开Handler的使用:
boolean post(Runnable r):把一个Runnable入队到消息队列中,UI线程从消息队列中取出这个对象后,立即执行。
boolean postAtTime(Runnable r,long uptimeMillis):把一个Runnable入队到消息队列中,UI线程从消息队列中取出这个对象后,在特定的时间执行。
boolean postDelayed(Runnable r,long delayMillis):把一个Runnable入队到消息队列中,UI线程从消息队列中取出这个对象后,延迟delayMills秒执行
void removeCallbacks(Runnable r):从消息队列中移除一个Runnable对象。
这里我们主要用post和postDelay来进行实现
首先在布局文件中添加两个按钮以及一个文本框
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
接着我们进行MainActivity中的代码设置
package com.game.handler;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button1,button2;
TextView textView;
/*声明handler对象*/
Handler handler=new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
textView = (TextView )findViewById(R.id.textView);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*启动一个子线程*/
new Thread(new Runnable() {
@Override
public void run() {
/*采用直接发送的方式*/
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("post");
Toast.makeText(MainActivity.this, "click post", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
/*采用延时发送*/
handler.postDelayed(new Runnable() {
@Override
public void run() {
textView.setText("delay");
Toast.makeText(MainActivity.this, "click delay", Toast.LENGTH_SHORT).show();
}
},3000);
}
}).start();
}
});
}
}
public void onClick(View view) {
/*启动一个子线程*/
new Thread(new Runnable() {
@Override
public void run() {
/*采用直接发送的方式*/
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("post");
Toast.makeText(MainActivity.this, "click post", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
这里直接在public void run()中对文本框进行操作是不对的,正确的用法就是要在handler的post等方法中再进行调用,必须在UI线程中对它进行调用,不能直接在子线程中进行调用。