Skip to content

Instantly share code, notes, and snippets.

@keima
Created May 18, 2017 12:43
Show Gist options
  • Select an option

  • Save keima/00880cf544a16202a3bbc7bab74b5b87 to your computer and use it in GitHub Desktop.

Select an option

Save keima/00880cf544a16202a3bbc7bab74b5b87 to your computer and use it in GitHub Desktop.
Demonstration of LiveData.
package net.pside.android.example.sunaba.livedata;
import android.arch.lifecycle.LiveData;
import android.os.CountDownTimer;
import android.util.Log;
import java.util.concurrent.atomic.AtomicBoolean;
public class CountDownTimerLiveData extends LiveData<Long> {
private static final String TAG = "CountDownTimerLiveData";
private static CountDownTimerLiveData sInstance;
public static CountDownTimerLiveData get() {
if (sInstance == null) {
sInstance = new CountDownTimerLiveData();
}
return sInstance;
}
CountDownTimer timer;
AtomicBoolean timerIsAwaken = new AtomicBoolean(false);
private CountDownTimerLiveData() {
timer = new CountDownTimer(5000, 100) {
@Override
public void onTick(long millisUntilFinished) {
setValue(millisUntilFinished);
}
@Override
public void onFinish() {
setValue(0L);
timerIsAwaken.set(false);
}
};
}
@Override
protected void onActive() {
Log.d(TAG, "onActive");
super.onActive();
if (!timerIsAwaken.get()) {
timer.start();
timerIsAwaken.set(true);
}
}
@Override
protected void onInactive() {
Log.d(TAG, "onInactive");
super.onInactive();
// timer.cancel();
}
}
package net.pside.android.example.sunaba;
import net.pside.android.example.sunaba.databinding.ActivityMyLifecycleBinding;
import net.pside.android.example.sunaba.livedata.CountDownTimerLiveData;
import android.arch.lifecycle.LifecycleActivity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
public class MyLifecycleActivity extends LifecycleActivity {
public static Intent createIntent(Context context) {
Intent intent = new Intent(context, MyLifecycleActivity.class);
return intent;
}
ActivityMyLifecycleBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_my_lifecycle);
CountDownTimerLiveData.get().observe(this, value -> {
binding.textView.setText(String.valueOf(value));
});
}
}
@keima
Copy link
Author

keima commented May 18, 2017

画面回転してもタイマーがリセットされないやつ

@cbeyls
Copy link

cbeyls commented May 19, 2017

You don't need an AtomicBoolean since onActive() and the CountDownTimer callbacks will be called on the main thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment