首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动注销用户,当应用程序在后台5分钟,什么时候用户恢复应用程序?

自动注销用户,当应用程序在后台5分钟,什么时候用户恢复应用程序?
EN

Stack Overflow用户
提问于 2017-02-14 13:30:52
回答 4查看 1.4K关注 0票数 0

如果屏幕被锁定(在应用程序还在的时候),或者应用程序移动到后台超过5分钟,我想注销我的应用程序。我有一个扩展BaseActivity的AppCompatActivity。所有其他活动都扩展了BaseActvity。

我在BaseActivity中使用了下面的代码,但是5分钟后,应用程序在LoginActivity中自动打开。你能帮帮我吗?

Java代码如下:

代码语言:javascript
复制
   @Override
    protected void onPause() {
        super.onPause();
        Log.v(TAG, "on pause called");
        timer = new Timer();
        Log.i(TAG, "Invoking logout timer");
        LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
        timer.schedule(logoutTimeTask, 300000); //auto logout in 5 minutes
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.v(TAG, "on resume called");
        if (timer != null) {
            timer.cancel();
            Log.i(TAG, "cancel timer");
            timer = null;
        }
    }

    private class LogOutTimerTask extends TimerTask {

        @Override
        public void run() {

            //redirect user to login screen
            Constants.SESSION_ID = "";
            Intent i = new Intent(getApplicationContext(), LoginActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            finish();
        }
    }

编辑

我增加了所有可能的建议,但计时器是工作的,即使当我启动应用程序。一个代码片段将是有用的。

EN

回答 4

Stack Overflow用户

发布于 2017-02-14 13:41:20

代码语言:javascript
复制
@Override
protected void onPause() {
   super.onPause();
   long LastTime= System.currentTimeMillis(); //save this time
} 



@Override
protected void onResume() {
   super.onResume();
   long CurrentTime= System.currentTimeMillis(); //this is your current time
   //get LastTime and compare
   long difference = CurrentTime - LastTime;
   // now convert difference into minutes and start login activity
}

这可能对你有帮助。

票数 0
EN

Stack Overflow用户

发布于 2017-02-14 13:42:04

您可以使用:

代码语言:javascript
复制
import java.util.Calendar

Calendar c = Calendar.getInstance(); 
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTES);

这将给你用户的时间。

您可以将它们保存在onStop()中,并在onRestart()/onResume中查看它们(如果您销毁了它)。在那里你可以运用你的逻辑。做一些计算,这样你就可以知道有多少时间已经过去和离开那里。您可以用SharedPreferences或其他任何您喜欢的方式保存它。

票数 0
EN

Stack Overflow用户

发布于 2017-02-14 13:43:36

这里的问题在于包含自动移动到登录屏幕的代码的LogoutTimerTask类。不要在这个LogoutTimerTask类中启动一个活动。相反,将全局定义的变量值设置为在运行()方法中注销5分钟后,当用户重新进入应用程序时,我建议您在onCreate中使用该变量来检查是否手动注销了用户,并从那里调用适当的活动类。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42227478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档