android – 检测应用程序何时打开/恢复

前端之家收集整理的这篇文章主要介绍了android – 检测应用程序何时打开/恢复前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
每次打开/关闭应用程序时,无论是从任务抽屉启动还是恢复,我都希望在服务器上签入并签出用户.有没有办法做到这一点,同时避免在每个活动中调用一个函数

谢谢!

解决方法

d60402 here提供的答案以及Hanno Binder使用 Application.registerActivityLifecycleCallbacks()注册活动回调的建议使我得到了这个解决方案.

我将应用程序和已注册的回调扩展到Activity方法onPause和onStart,如下所示.在这些方法中,启动/停止计时器(退出一个活动,其中调用onPause,在调用onStart时输入新的活动).当app确定在后台/前景(真/假)时,标记“wasInBackground”被切换.如果在运行onStart回调时应用程序处于后台,则会调用“appEntered”.如果在onPause和onStart回调之间传递的时间大于指定时间(为活动转换提供足够的时间),则会调用应用程序会话的“appExited”.

public class MyApplication extends Application {

public static final String LOG_TAG = "MyApp";

public boolean wasInBackground = true;

private AppSession appSession;
private Timer mActivityTransitionTimer;
private TimerTask mActivityTransitionTimerTask;
private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000;  // Time allowed for transitions

Application.ActivityLifecycleCallbacks activityCallbacks = new Application.ActivityLifecycleCallbacks() {

    @Override
    public void onActivityResumed(Activity activity) {

        if (wasInBackground) {
            //Do app-wide came-here-from-background code
            appEntered();
        }
        stopActivityTransitionTimer();
    }

    @Override
    public void onActivityPaused(Activity activity) {
        startActivityTransitionTimer();
    }

    ...

};

@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(activityCallbacks);
}

public void startActivityTransitionTimer() {
    this.mActivityTransitionTimer = new Timer();
    this.mActivityTransitionTimerTask = new TimerTask() {
        public void run() {
            // Task is run when app is exited
            wasInBackground = true;
            appExited();
        }
    };

    this.mActivityTransitionTimer.schedule(mActivityTransitionTimerTask,MAX_ACTIVITY_TRANSITION_TIME_MS);
}

public void stopActivityTransitionTimer() {
    if (this.mActivityTransitionTimerTask != null) {
        this.mActivityTransitionTimerTask.cancel();
    }

    if (this.mActivityTransitionTimer != null) {
        this.mActivityTransitionTimer.cancel();
    }

    this.wasInBackground = false;
}

private void appEntered() {
    Log.i(LOG_TAG,"APP ENTERED");

    appSession = new AppSession();
}

private void appExited() {
    Log.i(LOG_TAG,"APP EXITED");

    appSession.finishAppSession();

    // Submit AppSession to server
    submitAppSession(appSession);
    long sessionLength = (appSession.getT_close() - appSession.getT_open())/1000L;
    Log.i(LOG_TAG,"Session Length: " + sessionLength);
}
原文链接:https://www.f2er.com/android/316921.html

猜你在找的Android相关文章