Java (Android): タイマーを実行

device-2013-01-03-005839

java: ToastTimerActivity.java

package jp.feb19.snippets;

import java.util.Timer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class ToastTimerActivity extends Activity {

	Timer timer;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);

		// Button を設置
		final Button button = new Button(this);
		button.setText("タイマー開始");
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				timer = new Timer();
				timer.scheduleAtFixedRate(new ToastTimer(ToastTimerActivity.this), 5000, 5000);
			}
		});
		layout.addView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		// Button を設置
		final Button button2 = new Button(this);
		button2.setText("タイマー停止");
		button2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				cancelTimer();
			}
		});
		layout.addView(button2, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

		setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}

	protected void cancelTimer() {
		if (timer != null) {
			timer.cancel();
		}
	}

	protected void onDestroy() {
		super.onDestroy();
		cancelTimer();
	}
}

java: ToastTimer.java

package jp.feb19.snippets;

import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

public class ToastTimer extends TimerTask {

	private Handler handler;
	private Context context;

	public ToastTimer(Context context) {
		this.handler = new Handler();
		this.context = context;
	}
	
	@Override
	public void run() {
		handler.post(new Runnable() {
			@Override
			public void run() {
				Toast myToast = Toast.makeText(context, "update!", Toast.LENGTH_SHORT);
				myToast.show();
			}
		});
	}
}