Java (Android): 時計

ClockActivity

Java: ClockActivity.java

package jp.feb19.snippets;

import java.util.Calendar;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ClockActivity extends Activity {
	TextView tv;
	final Handler myHandler = new Handler();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		
		// テキストビュー
		tv = new TextView(this);
		layout.addView(tv);
		
		// タイマー
		final Timer timer = new Timer("timer");
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				update();
			}
		}, 0, 1000);
		setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
	private void update() {
		// GUI の更新 (TextView の更新) は、
		// 別スレッドで行わないようにするために Runnable を Handler に投げる
		myHandler.post(myRunnable);
	}
	final Runnable myRunnable = new Runnable() {
		public void run() {
			Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo"));
			int yy = cal.get(Calendar.YEAR);
			int MM = cal.get(Calendar.MONTH);
			int dd = cal.get(Calendar.DAY_OF_MONTH);
			int hh = cal.get(Calendar.HOUR_OF_DAY);
			int mm = cal.get(Calendar.MINUTE);
			int ss = cal.get(Calendar.SECOND);
			tv.setText(String.valueOf(yy) + "/" + String.valueOf(MM) + "/" + String.valueOf(dd) +
					"\n" + String.valueOf(hh) + ":" + String.valueOf(mm) + ":" + String.valueOf(ss));
		}
	};
}