Creating and handling an app timeout in Android

前端 未结 2 1051
醉话见心
醉话见心 2021-02-06 18:30

I was wondering what would be the best way to handle an application timeout, such as PayPal. I want the user to select between 1, 5, or 15 minute timeout period, so when they op

相关标签:
2条回答
  • 2021-02-06 18:49

    I did this in one of my apps:

    You need a base Activity for which all of your activities will extend from. In this base activity, add a variable that keeps track of the 'last user activity' timestamp. In my case, user activity simply means they touch the screen. So override the dispatchTouchEvent(MotionEvent ev) method, and set the 'last user activity' to current timestamp.

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        lastActivity = new Date().getTime();
        return super.dispatchTouchEvent(ev);
    }
    

    Then in onResume() method of this base activity, just compare current timestamp with 'last user activity' timestamp. If it more than either 1, 5 or 15 minutes (configurable by user), then launch another activity to ask the user to login.

    @Override
    public void onResume() {
        long now = new Date().getTime();
        if (now - lastActivity > xxxx) {
           // startActivity and force logon
        }
    } 
    
    0 讨论(0)
  • 2021-02-06 19:15

    I would use a heartbeat timer while the app is running and active and keep track of the current time (or last activity time - either one). When the app goes into the background from the user hitting the home button (or exits - not sure how you handle the back button) - remember the value by saving it to shared preferences. When the app starts or resumes you can compare the current time to the saved time and if the delta is more than "x" then you can direct the user to a login screen. Make sure you are paying attention to onPause, onResume, onStop, onDestroy events in your main activity. I would personally user System.currentTimeMillis for the timestamp and then compare the millis and divide appropriately based on your time (seconds, minutes, etc.).

    0 讨论(0)
提交回复
热议问题