Android中Handler的简单应用(一)

来源:互联网 发布:matlab矩阵运算 编辑:程序博客网 时间:2024/05/19 12:25

Handler在android里负责发送和处理消息。它的主要用途

  1.按计划发送消息或执行某个Runnanble(使用POST方法),类似定时器;

  2.从其他线程中发送来的消息放入消息队列中,避免线程冲突(常见于更新UI线程);

Handler主要用于异步消息的处理:当发出一个消息之后,首先进入一个消息队列,发送消息的函数即刻返回,而另外一个部分逐个的在消息队列中将消息取出,然后对消息进行出来,就是发送消息和接收消息不是同步的处理。这种机制通常用来处理相对耗时比较长的操作。

今天我们来介绍的只是Handler的最基本用法和意义,好了,上代码:

MainActivity.java

package com.whisker.handlertest;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private Button startButton = null;private Button stopButton = null;private TextView text_view = null;private int i = 0;Handler handler = new Handler();Runnable update_thread = new Runnable() {@Overridepublic void run() {i++;text_view.append("\nUpdateThread..." + i);handler.postDelayed(update_thread, 1000);}};    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        text_view = (TextView)findViewById(R.id.text_view);        startButton = (Button)findViewById(R.id.start);        stopButton = (Button)findViewById(R.id.stop);        startButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {handler.post(update_thread);}});        stopButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {handler.removeCallbacks(update_thread);}});    }}


activity_main.xml:

<LinearLayout 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:orientation="vertical"    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="com.whisker.handlertest.MainActivity" >    <TextView        android:id="@+id/text_view"        android:layout_width="match_parent"        android:layout_height="200dip"        android:text="Test!" />        <Button         android:id="@+id/start"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Start"/>        <Button         android:id="@+id/stop"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Stop"/></LinearLayout>


效果图:




0 0
原创粉丝点击