Android异步消息处理机制

时间:2022-04-21 11:44:06

安卓子线程无法直接更改UI,所以需要异步消息处理机制来解决

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
> <Button
android:id="@+id/change_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="change text"
/> <TextView
android:id="@+id/text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World"
android:textSize="20sp"/> </LinearLayout>
package com.example.contacttest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class NotificationTest extends Activity implements View.OnClickListener{ private Button changeText;
private TextView textContent; private static final int UPDATE_TEXT = 1; private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE_TEXT:
textContent.setText("Nice to meet you!");
break;
default:
break;
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_test); changeText = (Button)findViewById(R.id.change_text);
textContent = (TextView)findViewById(R.id.text_content); changeText.setOnClickListener(this); } @Override
public void onClick(View v) { switch (v.getId())
{
case R.id.change_text:
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
break;
default:
break;
}
} }