利用消息传递机制实现子线程与主线程通信,完成自动变化界面背景颜色的功能。掌握Handler类的使用方法,重点学习handmessage() 和sendEmptyMessage()方法在程序中的应用。
消息传递机制handler
实现代码:
MainActivity:
package com.example.xiaoxicd;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private RelativeLayout root;
private int[] colors={Color.RED,Color.GREEN,Color.YELLOW,Color.GRAY,Color.MAGENTA};
private int currentIndex=0;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root=(RelativeLayout)findViewById(R.id.root);
mHandler=new Handler(){
public void handleMessage(Message mgs){
if (mgs.what==0x11){
currentIndex=(currentIndex+1)%colors.length;
root.setBackgroundColor(colors[currentIndex]);
}
}
};
start();
}
private void start() {
new Thread(){
public void run(){
while (true){
try
{
Thread.sleep(5000);
mHandler.sendEmptyMessage(0x11);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}.start();
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="@+id/root">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="hello World!" />
</RelativeLayout>
运行结果: