Android - Make A Lock screen In Application

     Like some application which focuses on the protection of user data, if we would like to access content, we must enter password first. This lock screen always show every time we open the app, ensure that strangers cannot access your data. Maybe in some case to protect user information, developer can use this solution. In this post, I provide a my own solution to do this requirement through handling activity lifecycle. See this DEMO VIDEO first for output:

Warning

A better solution about making a lock screen inside your own app now available on my newer post, please read it HERE!

Designing layouts

    Firstly, design layout for lock screen, make it look like System Lock Screen:
    Output:
    Main (launching) activity is based on your aim. In this sample project, it's so simple like this:
    Output:

Programmatically coding

    Now, about the saving data (password) first. SharedPreference is the best choice here. Creating a session class include a SharedPreferences object and we will store and get password key then:
package info.devexchanges.applockscreen;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

public class PasswordSession {

    // Shared Preferences
    private SharedPreferences pref;

    // Editor for Shared preferences
    private SharedPreferences.Editor editor;

    // Context
    private Context context;

    // Shared preferences mode
    int PRIVATE_MODE = 0;

    private static final String PREF_NAME = "password";
    public static final String KEY_PW = "password";
    public static final String KEY_IS_PASS = "isPass";

    @SuppressLint("CommitPrefEdits")
    public PasswordSession(Context context) {
        this.context = context;
        pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public String getKeyPassword() {
        return pref.getString(KEY_PW, "");
    }

    public void setKeyPassword(String s) {
        editor.putString(KEY_PW, s);
        editor.commit();
    }

    public boolean getKeyIsPass() {
        return pref.getBoolean(KEY_IS_PASS, false);
    }

    public void setKeyIsPass (boolean isPass) {
        editor.putBoolean(KEY_IS_PASS, isPass);
        editor.commit();
    }
}
    In Activtity/Fragment, attach SharedPreferences with ApplicationContext, so data will be avaiable in whole project by this line:
PasswordSession session = new PasswordSession(getApplicationContext());
    Back to lock screen code, at the first time, we will create and store a password. Since later, user only need input this password to enter main Activity:
package info.devexchanges.applockscreen;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LockScreenActivity extends AppCompatActivity {

    private EditText txtPass;
    private LinearLayout llRePass;
    private EditText txtRePass;
    private View btn1;
    private View btn2;
    private View btn3;
    private View btn4;
    private View btn5;
    private View btn6;
    private View btn7;
    private View btn8;
    private View btn9;
    private View btn0;
    private View btnGo;

    private PasswordSession session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        session = new PasswordSession(getApplicationContext());

        setContentView(R.layout.activity_lock_screen);
        findViews();

        btn0.setOnClickListener(onClickListener(0));
        btn1.setOnClickListener(onClickListener(1));
        btn2.setOnClickListener(onClickListener(2));
        btn3.setOnClickListener(onClickListener(3));
        btn4.setOnClickListener(onClickListener(4));
        btn5.setOnClickListener(onClickListener(5));
        btn6.setOnClickListener(onClickListener(6));
        btn7.setOnClickListener(onClickListener(7));
        btn8.setOnClickListener(onClickListener(8));
        btn9.setOnClickListener(onClickListener(9));
        btnGo.setOnClickListener(onChangeActivityListener());

        if (!session.getKeyPassword().equals("")) {
            llRePass.setVisibility(View.GONE);
        }
    }

    private View.OnClickListener onChangeActivityListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!session.getKeyPassword().equals("")) {
                    if (!getText(txtPass).equals(session.getKeyPassword())) {
                        Toast.makeText(LockScreenActivity.this, "Incorrect password", Toast.LENGTH_SHORT).show();
                    } else {
                        session.setKeyIsPass(true);
                        Intent intent = new Intent(LockScreenActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                } else {
                    if (textLength(txtPass) < 4) {
                        Toast.makeText(LockScreenActivity.this, "Password is 4 digits", Toast.LENGTH_SHORT).show();
                    } else if (textLength(txtRePass) < 4) {
                        Toast.makeText(LockScreenActivity.this, "Please retype password", Toast.LENGTH_SHORT).show();
                    } else if (!txtRePass.getText().toString().trim().equals(txtPass.getText().toString().trim())) {
                        Toast.makeText(LockScreenActivity.this, "Re-type failed", Toast.LENGTH_SHORT).show();
                    } else {
                        session.setKeyIsPass(true);
                        session.setKeyPassword(txtPass.getText().toString());
                        Intent intent = new Intent(LockScreenActivity.this, MainActivity.class);
                        startActivity(intent);
                        Log.i("Activity", "go gog go");
                        finish();
                    }
                }
            }
        };
    }

    private View.OnClickListener onClickListener(final int value) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txtPass.isFocused() && textLength(txtPass) < 4) {
                    txtPass.setText(txtPass.getText().toString() + String.valueOf(value));
                } else if (txtRePass.isFocused() && textLength(txtRePass) < 4) {
                    txtRePass.setText(txtRePass.getText().toString() + String.valueOf(value));
                } else {
                    Log.i("Activity", "?????????");
                }
            }
        };
    }

    private void findViews() {
        txtPass = (EditText) findViewById(R.id.txt_pass);
        llRePass = (LinearLayout) findViewById(R.id.ll_re_pass);
        txtRePass = (EditText) findViewById(R.id.txt_re_pass);
        btnGo = findViewById(R.id.btn_go);
        btn1 = findViewById(R.id.btn_1);
        btn2 = findViewById(R.id.btn_2);
        btn3 = findViewById(R.id.btn_3);
        btn4 = findViewById(R.id.btn_4);
        btn5 = findViewById(R.id.btn_5);
        btn6 = findViewById(R.id.btn_6);
        btn7 = findViewById(R.id.btn_7);
        btn8 = findViewById(R.id.btn_8);
        btn9 = findViewById(R.id.btn_9);
        btn0 = findViewById(R.id.btn_0);
    }

    private int textLength(TextView textView) {
        return textView.getText().toString().trim().length();
    }

    private String getText(TextView textView) {
        return textView.getText().toString().trim();
    }
}
    In main Activity, in orderto always show lock screen after launching app,  let's overriding onStart() or onResume(), start LockScreenActivity in this method:
    @Override
    protected void onStart() {
        super.onStart();
        if (!session.getKeyIsPass()) {
            Intent intent = new Intent(this, LockScreenActivity.class);
            intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        session.setKeyIsPass(false);
    }
    In this activity, after enter incorect password, I will show to a TextView by get it from SharedPreferences, full code is so light:
package info.devexchanges.applockscreen;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private PasswordSession session;
    private View btnChange;
    private TextView txtPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        btnChange = findViewById(R.id.btn_change);
        txtPassword = (TextView) findViewById(R.id.text);

        session = new PasswordSession(getApplicationContext());
        txtPassword.setText(session.getKeyPassword()); //show password just typed in lock screen to TextView

        btnChange.setOnClickListener(onClickListener());
    }

    private View.OnClickListener onClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                session.setKeyPassword(""); //remove old password
                session.setKeyIsPass(false);
                Intent intent = new Intent(MainActivity.this, LockScreenActivity.class);
                startActivity(intent);
                finish();
            }
        };
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!session.getKeyIsPass()) {
            Intent intent = new Intent(this, LockScreenActivity.class);
            intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        session.setKeyIsPass(false);
    }
}
    Now, we have completed project and our problem is resolved. This is strings resource use for code:

Conclusions

    Over here, I have presented the way to make the lock screen for our own app, maybe it's useful with the data security app. Project now available on Github, you can get it by click below button! Subscribe my blog to get newest tutorials!


Share


Previous post
« Prev Post
Next post
Next Post »