闲谈
好久没更新了,前两个月就定了标题,现在才开始动手写。其实之前觉得这种获取App累积时长的方法(以下内容会介绍到)不唯一,可能有很多种,所以想收集多点资料,后来看到腾讯和360都是这么实现的,那么现在就开始介绍一下这个需求。
相信做游戏sdk开发的最近经常有这个需求,为什么是游戏sdk开发需要?而且为什么是最近?
首先回答第一个问题,这个需求主要是要限制用户对于app的使用时长,一般较为常见的是限制游戏游玩时长,其次,很少有Android应用有统计使用时长这一个需求。
第二个问题,为什么是最近?
没错,最近可以说国内的防沉迷越来越严重,导致出现几乎所有游戏,都需要提供防沉迷系统来限制未成年人的游戏时长。关于这个举措,我不作讨论,也不是这个blog的内容。。
案例
话不多说,Demo源码+示例图:
(点我,我是源码
实现
- 现在有一些是通过在各个Activity中埋点来实现计时长的操作的,也就是通过跳转Activity触发其生命周期回调来作为监控点,从而去获取累积时长的,这种方法也可以。但是Google官方有提供一个api:
Application.ActivityLifecycleCallbacks(API14以上,现在还有低于14开发的吗?不是吧不是吧)*
这个api最好在Application中调用,作为贯穿整个应用的对象,applicationContext拥有比Activity更长的生命周期,更易维护,回调函数少,也不用申请权限(Android6.0),因为作为sdk开发而言,权限尽量越少越好。
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ActivityLifeCycle lifecycleCallbacks = new ActivityLifeCycle();
registerActivityLifecycleCallbacks(lifecycleCallbacks);
}
}
我们可以实现一个ActivityLifeCycle继承Application.ActivityLifecycleCallbacks
implements Application.ActivityLifecycleCallbacks
下面是实现的代码:
public class ActivityLifeCycle implements Application.ActivityLifecycleCallbacks {
/**
* 上次检查时间,用于在运行时作为基准获取用户时间
*/
public static long lastCheckTime = 0;
/**
* 前台Activity数量
**/
private int foregroundActivityCount = 0;
/**
* Activity是否在修改配置,
*/
private boolean isChangingConfigActivity = false;
/**
* 应用将要切换到前台
*/
private boolean willSwitchToForeground = false;
/**
* 当前是否在前台
*/
private boolean isForegroundNow = false;
/**
* 上次暂停的Activity信息
*/
private String lastPausedActivityName;
private int lastPausedActivityHashCode;
private long lastPausedTime;
private long appUseReduceTime = 0;
/**
* 每次有Activity启动时的开始时间点
*/
private long appStartTime = 0L;
/**
* 本次统计时,运行的时间
*/
private long runTimeThisDay = 0L;
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
Logger.msg("onActivityCreated" + getActivityName(activity));
}
@Override
public void onActivityStarted(Activity activity) {
Logger.msg("onActivityStarted " + activity.getClass().getSimpleName() + " " + foregroundActivityCount);
//前台没有Activity,说明新启动或者将从从后台恢复
if (foregroundActivityCount == 0 || !isForegroundNow) {
willSwitchToForeground = true;
} else {
//应用已经在前台,此时保存今日运行的时间。
runTimeThisDay = System.currentTimeMillis() - appStartTime;
lastCheckTime = System.currentTimeMillis();
saveTodayPlayTime(activity, runTimeThisDay);
}
appStartTime = System.currentTimeMillis();
if (isChangingConfigActivity) {
isChangingConfigActivity = false;
return;
}
foregroundActivityCount += 1;
}
@Override
public void onActivityResumed(Activity activity) {
Logger.msg("onActivityResumed" + getActivityName(activity));
//在这里更新检查时间点,是为了保证从后台恢复到前台,持续计时的准确性。
lastCheckTime = System.currentTimeMillis();
addAppUseReduceTimeIfNeeded(activity);
if (willSwitchToForeground && isInteractive(activity)) {
isForegroundNow = true;
Logger.msg("switch to foreground");
}
if (isForegroundNow) {
willSwitchToForeground = false;
}
}
@Override
public void onActivityPaused(Activity activity) {
Logger.msg("onActivityPaused" + getActivityName(activity));
lastPausedActivityName = getActivityName(activity);
lastPausedActivityHashCode = activity.hashCode();
lastPausedTime = System.currentTimeMillis();
}
@Override
public void onActivityStopped(Activity activity) {
Logger.msg("onActivityStopped" + getActivityName(activity));
addAppUseReduceTimeIfNeeded(activity);
//如果这个Activity实在修改配置,如旋转等,则不保存时间直接返回
if (activity.isChangingConfigurations()) {
isChangingConfigActivity = true;
return;
}
//该Activity要进入后台,前台Activity数量-1。
foregroundActivityCount -= 1;
//当前已经是最后的一个Activity,代表此时应用退出了,保存时间。
// 如果跨天了,则从新一天的0点开始计时
if (foregroundActivityCount == 0) {
isForegroundNow = false;
Logger.msg("switch to background (reduce time[" + appUseReduceTime + "])");
// if (getTodayStartTime() > appStartTime){
// runTimeThisDay = System.currentTimeMillis() - getTodayStartTime();
// }else {
runTimeThisDay = System.currentTimeMillis() - appStartTime;
saveTodayPlayTime(activity, runTimeThisDay);
lastCheckTime = System.currentTimeMillis();
Logger.msg("run time :" + runTimeThisDay);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
Logger.msg("onActivitySaveInstanceState" + getActivityName(activity));
}
@Override
public void onActivityDestroyed(Activity activity) {
runTimeThisDay = System.currentTimeMillis() - appStartTime;
saveTodayPlayTime(activity, runTimeThisDay);
lastCheckTime = System.currentTimeMillis();
Logger.msg("onActivityDestroyed" + getActivityName(activity) + "--runTimeThisDay:" + runTimeThisDay + "--lastCheckTime" + lastCheckTime);
}
private void addAppUseReduceTimeIfNeeded(Activity activity) {
if (getActivityName(activity).equals(lastPausedActivityName) && activity.hashCode() == lastPausedActivityHashCode) {
long now = System.currentTimeMillis();
if (now - lastPausedTime > 1000) {
appUseReduceTime += now - lastPausedTime;
}
}
lastPausedActivityHashCode = -1;
lastPausedActivityName = null;
lastPausedTime = 0;
}
private boolean isInteractive(Context context) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
return pm.isInteractive();
} else {
return pm.isScreenOn();
}
}
private String getActivityName(final Activity activity) {
return activity.getClass().getCanonicalName();
}
/**
* 保存运行时间
*
* @param context
* @param time
*/
private void saveTodayPlayTime(Context context, long time) {
long todayTime = ShareprefUtils.getLong(context, "APP_USE_TIME", 0);
Logger.msg("使用时长Log:" + (todayTime + time));
ShareprefUtils.saveLong(context, "APP_USE_TIME", todayTime + time);
}
}
累积时长会保存在本地sharepreference文件,当然也可以上传服务器。
另外,ActivityLifecycleCallbacks这个api还可以用来管理 Activity 页面栈,判断应用前后台,应用新开进程假重启处理等
- 参考博客:
探究 Android 中的 ActivityLifecycleCallbacks
android开发之app在线时长统计sdk开发
Application - ActivityLifecycleCallbacks