writing a time out event for android

前端 未结 1 724
一生所求
一生所求 2021-01-03 18:39

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

相关标签:
1条回答
  • 2021-01-03 19:36

    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 讨论(0)
提交回复
热议问题