Android在后台线程实现 定时更新时间

简述:

这是一类定时功能的原型,用来在后台线程中运行一些定时的服务,比如定时修改时间


知识点:

1. Android多线程的消息通信

2. Java中时间的获取,以及String的格式化

3. Android PostDelay 的定期的实现


设计:

开一个新的Thread每隔3秒, 用来定时修改一个TextView的时间


代码:

首先是Acitivity的布局视图

main_activity.xml




    


1. 开始想到的就是通过System.currentTimeMillis()来获取当前时间

MainActivity.java

package com.atp.ui;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.atp.R;

public class MainActivity extends Activity {

	private Button myBtn = null;
	private TextView myTv = null;
	private boolean runFlag = false;

	//use of Handler
	//messge info
	private static final int UPDATE_MY_TV = 1;
	Message message = null;

	//Handler UI modification
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case UPDATE_MY_TV:
				String currentTime = (String)msg.obj;
				myTv.setText("Current Time: " + currentTime);
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		myBtn = (Button) findViewById(R.id.myBtn);
		myTv = (TextView) findViewById(R.id.myTv);
		myBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(!runFlag){
					runFlag = true;
					myBtn.setText("Stop");
					new Thread(){
						@Override
						public void run() {
							//Time Controller
							//Modify Time After 3000 ms
							long startTime = System.currentTimeMillis();
							while(runFlag){
								long endTime = System.currentTimeMillis();
								if(endTime - startTime > 3000){
									startTime = endTime;
									SimpleDateFormat formatter = 
										new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
									Date curDate = new Date(System.currentTimeMillis());
									String currentTime = formatter.format(curDate);
									message = handler.obtainMessage(UPDATE_MY_TV, currentTime);
									handler.sendMessage(message);
								}
							}
						}
					}.start();
				}else{
					runFlag = false;
					myBtn.setText("Start");
				}
			}
		});
	}
}

2.之后发现Handler的post方法也可以定时做这种效果,而且直接用Handler来调整运行的时间间隔,而不用自己去算了

package com.atp.ui;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.atp.R;

public class MainActivity extends Activity {

	private Button myBtn = null;
	private TextView myTv = null;
	private boolean runFlag = false;

	//use of Handler
	//messge info
	private static final int UPDATE_MY_TV = 1;
	Message message = null;

	//Handler UI modification
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case UPDATE_MY_TV:
				String currentTime = (String)msg.obj;
				myTv.setText("Current Time: " + currentTime);
				break;
			}
		}
	};


	private Thread updateCurrentTime = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		myBtn = (Button) findViewById(R.id.myBtn);
		myTv = (TextView) findViewById(R.id.myTv);
		myBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(!runFlag){
					runFlag = true;
					myBtn.setText("Stop");
					updateCurrentTime = new Thread(){
						@Override
						public void run() {
							//Time Controller
							//Modify Time After 3000 ms
							SimpleDateFormat formatter = 
								new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
							Date curDate = new Date(System.currentTimeMillis());
							String currentTime = formatter.format(curDate);
							message = handler.obtainMessage(UPDATE_MY_TV, currentTime);
							handler.sendMessage(message);
							//use Handler to control the time
							handler.postDelayed(this, 3000);
						}
					};
					updateCurrentTime.start();
				}else{
					runFlag = false;
					handler.removeCallbacks(updateCurrentTime);
					myBtn.setText("Start");
				}
			}
		});
	}
}



效果:


你可能感兴趣的:(Android)