我正在寻求实现一项功能,可以在 X 分钟不活动后注销用户。在经历了类似的答案后,建议的方法似乎是 -
- 在后台运行一个计时器。将其安排在 x 分钟后超时。
- 在用户与应用程序交互的每个函数(基本上所有事件处理程序)中,调用重置计时器的方法。
我自己想不出比这更好的东西了,但即使对于拥有 6-7 个不同屏幕和一大堆 UI 组件的中型应用程序来说,这似乎也是一个巨大的痛苦。有更好的方法来处理这个问题吗?
谢谢,
特贾。
I'm looking to implement a feature that logs out the user after X minutes of inactivity. After going through a similar answer on SO, the suggested method seems to be to -
- Have a timer running in the background. Schedule it to timeout after x minutes.
- In every function where the user interacts with the app (basically all event handlers), call a method that resets the timer.
I can't think of anything better than this myself, but it's seems to be a huge pain even for a medium sized application that has 6-7 different screens and a whole bunch of UI components. Is there a better way to handle this?
Thanks,
Teja.
发布评论
评论(4)
您可以使用
CountDownTimer
并从 Activity() 中的“http://developer.android.com/reference/android/app/Activity.html#onUserInteraction%28%29">onUserInteraction()
You can use a
CountDownTimer
and restart it fromonUserInteraction()
in everyActivity()
不,又是。如果您在
Service
中实现计时器,请使用计时器 或在IntentService
中。否则,不要。该解决方案将很难维持。
您应该有一个
IntentService
(演示文章此处) 在后台运行,可以轻松实现TimerTask
或Handler
和使其中的可运行代码向您的活动发出广播。在您的 Activity 中,您可以轻松添加BroadcastReciever
在这种情况下,如果时间到了,您可以注销用户。当您的应用程序对用户不可见时,您可以启动服务。No and yes. Use a timer if you're implementing it in a
Service
or in anIntentService
. Otherwise, don't.That solution would be hard to maintain.
You should have an
IntentService
(demonstrating article here) running in the background that can easily implement aTimerTask
or aHandler
and make the runnable code inside it fire a broadcast to your activities. In your activities you can easily add aBroadcastReciever
and in that case you can log out the user if time is out. You can start your service when your application isn't visible to the user.我将这样做:
1) 创建一个全局变量来表示时间日志
2) 在每个活动的 onStop 调用期间,用当前时间更新全局变量。
3)在每个activity的onResume调用期间,将当前时间与全局变量time进行比较,看看已经过去了多少时间
This is how I would go about this:
1) Create a global variable to represent a time log
2) During the onStop call for each activity, update the global variable with the current time.
3) During the onResume call for each activity, compare the current time with the global variable time to see how much time has passed
这是我想为自己实现的事情。
这是我制作的一个“库”: https://github.com/zoltanersek/android-timeout-活动
用法:
This is something that I wanted to implement for myself.
Here is a "library" I made: https://github.com/zoltanersek/android-timeout-activity
Usage: