Handle异步例子

本文通过一个具体的例子详细介绍了在Android中如何使用Handler进行异步操作,讲解了Handler、Looper和Message的关系,以及它们在Android消息机制中的作用。
摘要由CSDN通过智能技术生成
HandleActivity.java
public class HandleActivity extends FragmentActivity {
	private Context context;// 上下文
	private TextView textView;
	private EditText edt;
	private String string;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置吧显示标题栏--需要在创建视图之前设置
		setContentView(R.layout.activity_handle);
		context = this;// 上下文赋值
		Init();
	}
	private void Init() {
		textView = (TextView) this.findViewById(R.id.txt);
		edt = (EditText) this.findViewById(R.id.editText1);
		textView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new Thread(new Runnable() {
					public void run() {
						try {
							Thread.sleep(2000);
							Message msg = new Message();
							string = edt.getText().toString();
							//msg.obj = string;
							msg.what = 1;//标记
							handel.sendMessage(msg);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
		});
	}
	// 更新UI--内部类
	private Handler handel = new Handler() {
		public void handleMessage(Message msg) {
			// super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				Toast.makeText(context, string, 0).show();
				break;
			default:
				break;
			}
		}
	};
}

activity_handle.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"
    tools:context=".HandleActivity" >
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="100dp"
        android:gravity="center"
        android:text="请输入内容后点击" />
</RelativeLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值