现在的位置: 首页 > 综合 > 正文

Android中Timer和TimerTask使用完整示例

2014年06月06日 ⁄ 综合 ⁄ 共 1061字 ⁄ 字号 评论关闭

MainActivity如下:

package cc.test;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
/**
 * Demo描述:
 * Timer和TimerTask使用完整示例
 */
public class MainActivity extends Activity {
	private Timer mTimer;
	private TimerTask mTimerTask;
	private int count=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

	private void init() {
		mTimer = new Timer();
		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				count++;
				System.out.println("---> count=" + count);
				if (count == 15) {
					mTimer.cancel();
					System.out.println("---> 取消定时任务");
				}
			}
		};
		//开始一个定时任务
		mTimer.schedule(mTimerTask, 2000, 1500);
	}
}

main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Timer和TimerTask使用完整示例"
        android:layout_centerInParent="true"
        android:textColor="#111111"
        />

</RelativeLayout>

抱歉!评论已关闭.