Skip to content

Instantly share code, notes, and snippets.

@noxi515
Last active August 29, 2015 14:01
Show Gist options
  • Save noxi515/edea22698b444b344885 to your computer and use it in GitHub Desktop.
Save noxi515/edea22698b444b344885 to your computer and use it in GitHub Desktop.
ViewをTimerで更新するサンプル
package jp.noxi.sample.android.timer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class MyActivity extends Activity {
private Handler handler;
private Timer timer;
private TextView text1;
private TextView text2;
private int count1;
private int count2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler = new Handler();
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
timer = new Timer();
// Handler経由で更新
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
text1.setText(String.valueOf(++count1));
}
});
}
}, 0, TimeUnit.SECONDS.toMillis(1L));
// Handlerを経由せずに更新
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
text2.post(new Runnable() {
@Override
public void run() {
text2.setText(String.valueOf(++count2));
}
});
}
}, 0, TimeUnit.SECONDS.toMillis(2L));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment