实时改变Toast提示信息,实现功能:运行该软件时,后台自动启动线程,每一秒钟发送一次消息,在手机屏幕上会显示出需要提示的信息,当发到10条时,系统停止发送消息。
该程序主要运用到了Handler接收消息的功能,在这里需要说明的是Handler和Thread不一定是对应的,也就是说在一个线程中可以有多个Handler,每个消息都可以指定不同的Handler,因为每个消息都可以有不同的行为。
下面首先给出布局文件;
<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="com.example.toasttdw.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="通过有消息循环的线程定时显示Toast"
android:layout_centerInParent="true"/>
</RelativeLayout>
布局文件中只有一个TextView控件。只是起到一个背景作用。
接下给出主要功能代码,
package com.example.toasthh;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
public class MainActivity extends Activity {
private int count = 0;
Handler handler = new Handler(){
@Override
public void handleMessage(android.os.Message msg) {
Toast.makeText(MainActivity.this, "计时器值:"+msg.what, Toast.LENGTH_SHORT).show();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(1*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(count == 10){
break;
}
handler.sendEmptyMessage(count++);
}
}
}).start();
}
}
在主线程中启动一个线程,每隔一秒发送发送消息,在handleMessage(android.os.Message msg)接收消息并且Toast显示。