這是托馬斯寫的一個關於封裝倒計時的 android
package test.hatainet.com.firstgradletest;app
import android.app.Fragment;
import android.os.Handler;
import android.os.Looper;dom
/**
* Created by Thomas on 2017/12/5.
*/ide
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;oop
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);post
}gradle
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);
}
}.net
public abstract void onTimeTextChange(int timepassed);get
public void resetCountDownTime()
{
timeflag = System.currentTimeMillis();
}
}it