package org.ntlab.radishforandroidstudio.framework.gameMain; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.ntlab.radishforandroidstudio.R; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; public abstract class RealTimeFragment extends Fragment implements Runnable{ //インターバル確認用変数 private long interval = 15L; private long prevTime = 0L; private ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(1); private boolean fixedInterval; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_real_time, container, false); } protected void start(long interval){ this.interval = interval; this.fixedInterval = false; schedule.scheduleWithFixedDelay(this, interval, interval, TimeUnit.MILLISECONDS); } protected void start(long delay, long interval){ this.interval = interval; this.fixedInterval = false; schedule.scheduleWithFixedDelay(this, delay, interval, TimeUnit.MILLISECONDS); } protected void start(long delay, long interval, boolean fixedInterval){ this.interval = interval; this.fixedInterval = fixedInterval; schedule.scheduleWithFixedDelay(this, delay, interval, TimeUnit.MILLISECONDS); } protected void stop() { schedule.shutdown(); } //繰り返し実行される部分 public void run(){ long interval; if (prevTime == 0L || fixedInterval) { interval = this.interval; prevTime = System.currentTimeMillis(); } else { long curTime = System.currentTimeMillis(); interval = curTime - prevTime; prevTime = curTime; } update(interval); } //intervalミリ秒のインターバルをおいて定期実行 protected abstract void update(long interval); }