Follow-up steps to password protect Android app launch

Following this StackOverflow question , what is the best way to show the password screen?

My first attempt was to start SubActivity using LockActivity:

public void onResume() {

    ApplicationState state = ((ApplicationState) getApplication());
    if ((new Date().getTime() - state.mLastPause) > 5000) {

        // Prompt for password if more than 5 seconds since last pause
        Intent intent = new Intent(this, LockActivity.class);
        startActivityForResult(intent, UNLOCKED);


However, this causes the MainActivity to pause again after unlocking if the LockActivity is displayed for more than 5 seconds.

So, I have some things:

  • Use Fragments

    to display the main screen or lock screen inside MainActivity.
  • Show Dialog

    as lock screen (not recommended).
  • Using multiple branches if ... else

    to check if the password has been set and the MainActivity has been suspended for longer than five seconds.

To give you an example, I would like to achieve the same behavior as in the Dropbox app (using the "Password Lock" option).

What is the correct way to handle this?

PS I'm not sure if I should post this as a question to the original question, digging up an old thread. I felt that posting a new question was a cleaner solution.


source to share

1 answer

Since I was asking a different question, I could tell you how I solved it. I use a dialog box to ask for a password (which I know you don't like, but might help someone else) and make sure the only way to decline it is to enter the correct password.

MyApplication app = ((MyApplication)getApplication());
if (new Date().getTime() - app.mLastPause > 5000) {
  // If more than 5 seconds since last pause, check if password is set and prompt if necessary
  SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
  String password = pref.getString("password", "");
  if (password.length() > 0) {
     // Prompt for password
     MyPasswordDialog dlg = new MyPasswordDialog(this, password);


And in the OnCreate()

MyPasswordDialog method I make sure it is not overridden

protected void onCreate(Bundle savedInstanceState) {
   // ...and some other initializations




All Articles