抽象类方法-倒计时显示(二)

本文介绍了一个抽象基类FragmentWithTimer,该类封装了倒计时功能,并使用Handler和Runnable实现定时更新UI的任务。文章提供了完整的源代码示例。

这是托马斯写的一个关于封装倒计时的 

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();
    }
}

转载于:https://my.oschina.net/u/3407708/blog/1585036

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值