Android app start and end event

后端 未结 5 962

I have an app which track user activity on app which include time etc, Now if user has opened the app, It will start an session and till user in this app , his session will cont

5条回答
  •  误落风尘
    2021-02-05 22:33

    You can easily do this by the source code below I mention which is also saved from orientation change . (Reference)

    public class ApplicationEventTracker implements Application.ActivityLifecycleCallbacks {
    private int activityReferences = 0;
    private boolean isActivityChangingConfigurations = false;
    
    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {
    }
    
    @Override
    public void onActivityStarted(Activity activity) {
        if (++activityReferences == 1 && !isActivityChangingConfigurations) {
            // App enters foreground
        }
    }
    
    @Override
    public void onActivityResumed(Activity activity) {
    }
    
    @Override
    public void onActivityPaused(Activity activity) {
    }
    
    @Override
    public void onActivityStopped(Activity activity) {
        isActivityChangingConfigurations = activity.isChangingConfigurations();
        if (--activityReferences == 0 && !isActivityChangingConfigurations) {
            // App enters background
        }
    }
    
    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
    }
    
    @Override
    public void onActivityDestroyed(Activity activity) {
    }
    

提交回复
热议问题