android在线时长统计升级版。
前期利用多重标记结合list存储activityname的方式实现的。比较繁琐。升级后,就简单多了。主要是activity生命周期切换和context方法的使用
详细讲解可以参考我的另外一篇文章,https://blog.csdn.net/shoneworn/article/details/80265056
public class OnLineStatics {
private static Context context;
public static boolean mIsAppOnForegroundB;// app是否在前台
public static boolean mIsAppRunningB = false;// APP是否正在运行
private static MetaClass helper ;
private static long mStartTime;
private static Handler mHandler=new Handler(Looper.getMainLooper());// Handler对象
public void init(final Context context, MetaClass metaClass) {
Application application = (Application) context.getApplicationContext();
this.context = context;
//上报活跃量
this.helper = metaClass;
application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
setAppOnForeground(true);
System.out.println("onlin:onActivityResumed");
}
@Override
public void onActivityPaused(Activity activity) {
setAppOnForeground(false);
System.out.println("onlin:onActivityPaused");
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
public static boolean mLastAppOnForeground=false;// 缓存上一次app是否在前台
public static Runnable appOnForegroundCheckRunnable=new Runnable() {
@Override
public void run() {
System.out.println("onlin:mIsAppOnForegroundB app是否在前台"+mIsAppOnForegroundB);
System.out.println("onlin:mLastAppOnForeground 上一次app是否在前台"+mLastAppOnForeground);
if(mIsAppOnForegroundB!=mLastAppOnForeground){
if(mIsAppOnForegroundB){
helper.reportActive();
mStartTime = System.currentTimeMillis()/1000;
}else{
helper.reportOnline(""+(System.currentTimeMillis()/1000 - mStartTime));
}
mLastAppOnForeground=mIsAppOnForegroundB;
}
}
};
public static void setAppOnForeground(boolean onForeground){
mIsAppOnForegroundB=onForeground;
if(mHandler!=null){
mHandler.removeCallbacks(appOnForegroundCheckRunnable);
mHandler.postDelayed(appOnForegroundCheckRunnable,1000);
}
}
}