非UI线程更改UI线程2

更改UI线程的第二种方式,通过传递消息给UI线程,让UI线程更改

主要用到的几个类

Message,Hander.Looper

Message

Message获得的方式Message.obtain()、Hander.obtainMessage()、new Meessage()

  具有getData()和setData()方法

有五个属性

arg1 如果只需在Message中存放少量的整形数据,使用arg1和arg2比使用setData()节省资源

arg2同上

obj 可以存放任意的数据,使用存放简单数据,其效率也比setdata()高

replyTO指定一个Messenger,可以在其中发送该Message的回复信息(没用过)

what 用来匹配Message的标识符


setData和getData()可以用Bundle 对象来封装数据


Hander

用来发送和接收信息,他有许多方法

Looper

每个线程都唯一对应一个Loop,不管是UI 线程还是非UI线程,只要有looper,其他线程都可以想这个线程发送消息,系统再启动主线程时,会主动给她创建个looper,其余线程需调用Looper.prepare()建立本线程的Loop的对象

另一个方法Loop()让Looper开始工作,从消息队列里取消息,处理消息

Class

package com.example.change_ui2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.R.integer;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class Main extends Activity {
	private int count=0;
	private TextView tv;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			super.handleMessage(msg);
			switch (msg.what) {//消息匹配
			case 6:
				tv.setText("count等于"+msg.arg1);
				
				break;

			default:
				break;
			}
		}
		
		
	};


	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv=(TextView) findViewById(R.id.tv_id);
		
		new Thread(new Runnable() {
			
			
			public void run() {
				while (true) {
					count++;
					//将新结果通过Hander对象发送给UI线程
					Message message=Message.obtain();
					message.what =6;//标识符
					message.arg1=count;
					handler.sendMessage(message);//发送
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
				}
				
				
			}
		}).start();
		
		
	}


}

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <TextView
        android:id="@+id/tv_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值