开发者

writing a time out event for android

i have a small issue i can't figure out. for my program, i basically want to execute some code if the user hasn't done anything with the application for 5 minutes (say log out).

how can i go about doing this? i'm lost on detecting that the user has done nothing, and then reset the count once the user has touched the tablet 开发者_如何学JAVAor something. can somebody give me some pointers?

thanks in advance!


So if you are having single Activity in your app then you create a Timer and TimerTask to achieve this. And can track touch and key events.So in your activity you can do something like this.

Timer longTimer;
synchronized void setupLongTimeout(long timeout) {
  if(longTimer != null) {
    longTimer.cancel();
    longTimer = null;
  }
  if(longTimer == null) {
    Timer longTimer = new Timer();
    longTimer.schedule(new TimerTask() {
      public void run() {
        longTimer.cancel();
        longTimer = null;
        //do your stuff, i.e. finishing activity etc.
      }
    }, 300000 /*delay in milliseconds i.e. 5 min = 300000 ms or use timeout argument*/);
  }
}
@override
public boolean onTouchEvent(MotionEvent me) {
  setupLongTimeout(300000);
  return super.onTouchEvent(me);
}
@override
public boolean onKeyUp(int keyCode, KeyEvent ke) {
  setupLongTimeout(300000);
  return super.onKeyUp(keyCode, ke);
}
If you are handling any key/touch events for any of the views then you need to return false so that event comes to the activity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜