我需要使用空闲侦听器来监听用户正在使用应用程序或在活动处于活动状态时闲置。 当用户不使用应用程序超过十秒钟时,我需要做一些事情。 我怎样才能成为可能?
答案 0 :(得分:7)
以下是您如何完成此任务的想法:
首先你需要一个Runnable(),它会在你的超时(例如10秒)发生时运行。下面是Runnable():
private Runnable DoOnTimeOut = new Runnable()
{
public void run()
{
// Do something Here
}
}
现在,在您的活动中,您可以为DoOnTimeOut调用postDelayed:
Handler hl_timeout = new Handler();
@Override
public void onCreate(Bundle b)
{
hl_timeout.postDelayed(DoOnTimeOut, 10000); // The DoOnTimOut will be triggered after 10sec
}
现在,最重要的部分是,当您看到用户交互时,您想要取消对DoOnTimeOut的调用,然后再次设置下一个10秒的调用。以下是您的用户交互活动的覆盖方法:
@Override
public void onUserInteraction()
{
super.onUserInteraction();
//Remove any previous callback
hl_timeout.removeCallbacks(DoOnTimeOut);
hl_timeout.postDelayed(DoOnTimeOut, 10000);
}
我希望它会对你有所帮助。