这是托马斯写的一个关于封装倒计时的
package test.hatainet.com.firstgradletest;
import android.app.Fragment;
import android.os.Handler;
import android.os.Looper;
/**
* Created by Thomas on 2017/12/5.
*/
public abstract class FragmentWithTimer extends Fragment
{
public static final int TIME_GAP = 100;
public static final int TIME_RANGE = 60000;
private int flag;
private long timeflag;
public void startCountDown()
{
timeflag = System.currentTimeMillis();
flag = (int) Math.random() * Integer.MAX_VALUE;
final int THIS_FLAG = flag;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable()
{
@Override
public void run()
{
coundDown(THIS_FLAG);
}
}, TIME_GAP);
}
private void coundDown(final int THIS_FLAG)
{
if (flag != THIS_FLAG) {return;}
int timepassed = (int) ((System.currentTimeMillis() - timeflag) / 1000);
onTimeTextChange(timepassed);
if (System.currentTimeMillis() - timeflag < TIME_RANGE)
{
new Handler(Looper.getMainLooper()).postDelayed(new Runnable()
{
@Override
public void run()
{
coundDown(THIS_FLAG);
}
}, TIME_GAP);
}
}
public abstract void onTimeTextChange(int timepassed);
public void resetCountDownTime()
{
timeflag = System.currentTimeMillis();
}
}