Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know another answer is accepted already, but I came across this working on a similar problem and think I'm going to try an alternate much simpler approach that I figured I may as well document if anyone else wants to try to go down the same path.enter code here</p> <p>The general idea is just to track the system clock time in a SharedPreference whenever any Activity pauses - sounds simple enough, but alas, there's a security hole if that's all you use, since that clock resets on reboot. To work around that:</p> <ul> <li>Have an <code>Application</code> subclass or shared static singleton class with a global unlocked-since-boot state (initially false). This value should live as long as your Application's process.</li> <li>Save the system time (<a href="http://developer.android.com/reference/android/os/SystemClock.html#elapsedRealtime%28%29" rel="noreferrer">realtime</a> since boot) in every relevant <code>Activity</code>'s <code>onPause</code> into a <code>SharedPreference</code> if the current app state is unlocked.</li> <li>If the appwide unlocked-since-boot state is false (clean app start - either the app or the phone restarted), show the lock screen. Otherwise, check the <code>SharedPreference</code>'s value at the lockable activity's onResume; if it's nonexistent or greater than the <code>SharedPreference</code> value + the timeout interval, also show the lock screen.</li> <li>When the app is unlocked, set the appwide unlocked-since-boot state to true.</li> </ul> <p>Besides the timeout, this approach will also automatically lock your app if your app is killed and restarts or if your phone restarts, but I don't think that's an especially bad problem for most apps. It's a little over-safe and may lock unecessarily on users who task switch a lot, but I think it's a worthwhile tradeoff for reduced code and complexity by a total removal of any background process / wakelock concerns (no services, alarms, or receivers necessary). </p> <p>To work around process-killing locking the app regardless of time, instead of sharing an appwide singleton for unlocked-since-boot, you could use a SharedPreference and register a listener for the system boot broadcast intent to set that Preference to false. That re-adds some of the complexity of the initial solution with the benefit being a little more convenience in the case that the app's process is killed while backgrounded within the timeout interval, although for most apps it's probably overkill.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload