人気ブログランキング | 話題のタグを見る
ブログトップ

智信の部屋

tomonobu.exblog.jp

プログラムに関する雑談なんかを書いていこうと思います。(android記事のまとめサイトはこちらです→http://tomonobu.rocketserver.jp/android_blog_index.php)

Android:Timerの実装

一定時間経過後に起動する処理を実装しよう!
っということで TImer の実装です。

参考資料
 「Timerを使って定期実行する

 ・遅延を発生させて処理を発生させるために
  TImerクラス を使用する。
  処理の登録には schedule を使用する。
  【登録例】
   schedule(TimerTask task, long delay)
    1回限りの実行の登録
   schedule(TimerTask task, long delay, long period)
    繰り返し実行の登録
 ・schedule において登録を行う処理は TimerTask により定義を行う。
  実際の処理は run に記載する。
 ・TImer で実行される TimerTask ではUIの制御が実施できない。
  よって Handler を使用して、
  実行中の Activity に戻して実行を行う。
  データの受け渡しは HandlerhandleMessage を使用して実施する。
  実際の内容は Message に登録して受け渡しを行う。
  Message のデータ設定は Bundle を使用して設定を行う。

サンプルコード
package com.tomonobu.application.test_3;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

public class Test_program_3Activity extends Activity {
private final static String MESSAGE = "message";

private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String message = msg.getData().get(MESSAGE).toString();
Toast.makeText(Test_program_3Activity.this, message, Toast.LENGTH_LONG).show();
}
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TextView tv = new TextView(this);
tv.setText("Timer Test");
setContentView(tv);

Timer timer = new Timer(false);
timer.schedule(new TimerTask() {
@Override
public void run() {
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putString(MESSAGE, "Timer Test");
message.setData(bundle);
handler.sendMessage(message);
}
}, 2000);
}
}


by Tomonobu1979 | 2011-08-17 20:23 | android

by Tomonobu1979