您的位置:首页 > 移动开发 > Android开发

Android异步消息处理机制

2016-03-16 15:13 302 查看
安卓子线程无法直接更改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;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: