判断是否已过时--时间戳比较

文章介绍了如何在Android应用中使用AlarmManager和SharedPreferences实现一个功能,判断应用程序是否已经超过设定的时间(如1天),如果超过则触发定时操作。核心是isAlarmTimeFlag方法,它检查应用启动时间和当前时间差来确定是否需要提醒。
摘要由CSDN通过智能技术生成

直接撸代码:


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.jaydenxiao.common.commonutils.SPUtils;

/**
 * Description: [相关定时警告等]
 * </p>
 *
 */
public class AlarmTimeUtil {
    /**
     * 一天一夜  24H
     */
    public static final long ONE_DAY_MS = 24 * 60 * 60 * 1000; // 1天的毫秒数


    /**

     */
    /**
     * <p>
     * Description: [判断是否已过时]
     * 在应用程序的入口处(通常是MainActivity的onCreate()方法),使用SharedPreferences存储上次启动的时间戳。
     * 通过获取存储的时间戳与当前时间戳的差值,判断是否超过1天。
     * 如果超过1天,返回true。
     * 如果未超过1天,返回false。
     *  <p>
     *
     * @param context
     * @param during     限制时间---毫秒单位(如24h=24 * 60 * 60 * 1000)
     * @return boolean
     *
     */
    public static boolean isAlarmTimeFlag(Context context, long during) {
        boolean result = true;
        // 获取上次启动的时间戳
        long lastStartTime = SPUtils.getLongValue(context, "lastStartAppTime", 0);

        // 获取当前时间戳
        long currentTime = System.currentTimeMillis();

        // 判断是否超过1天
        if (currentTime - lastStartTime > during) {
            // 超过1天,设置定时器
            result = true;
        } else {
            // 未超过1天,继续执行以前的流程
            result = false;
        }

        // 存储当前启动的时间戳
        SPUtils.putLongValue(context, "lastStartAppTime",  currentTime);
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值