Create a lock screen inside Android 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 cases to protect user information, developer can use this way.

    In this post, I will make a lock activity by designing in XML. There is an another solution is using a third-party library, please read my previous post.

Designing layout for lock activity

    User must input number-password to pass this lock screen, so design a keypad for this activity like this:
activity_lock.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_horizontal_margin"
    tools:context="info.devexchanges.lockscreen.LockActivity">

    <LinearLayout
        android:id="@+id/lock_keypad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn1"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="1" />

            <Button
                android:id="@+id/btn2"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="2" />

            <Button
                android:id="@+id/btn3"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="3" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn4"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="4" />

            <Button
                android:id="@+id/btn5"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="5" />

            <Button
                android:id="@+id/btn6"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="6" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn7"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="7" />

            <Button
                android:id="@+id/btn8"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="8" />

            <Button
                android:id="@+id/btn9"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="9" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn_space"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:enabled="false" />

            <Button
                android:id="@+id/btn0"
                style="@style/Borderless_Button"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="0" />

            <ImageView
                android:id="@+id/btn_clear"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:contentDescription="@null"
                android:src="@android:drawable/ic_input_delete"
                android:tint="@color/colorPrimary" />
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/dot_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/lock_keypad"
        android:layout_marginBottom="@dimen/activity_horizontal_margin"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/dot_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@null"
            android:src="@drawable/dot_disable" />

        <ImageView
            android:id="@+id/dot_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@null"
            android:src="@drawable/dot_disable" />

        <ImageView
            android:id="@+id/dot_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@null"
            android:src="@drawable/dot_disable" />

        <ImageView
            android:id="@+id/dot_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@null"
            android:src="@drawable/dot_disable" />

    </LinearLayout>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/dot_layout"
        android:layout_centerInParent="true"
        android:layout_marginBottom="@dimen/activity_horizontal_margin"
        android:src="@drawable/lock" />

</RelativeLayout>
    Expected output:
    Now, you must have a main activity, it's will start when launching app. It's layout depend on your work, in this simple project, it only include a TextView:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="info.devexchanges.lockscreen.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/activity_horizontal_margin"
        android:text="Hello World!" />
</LinearLayout>

Main activity programmatically code

     Because the lock screen always display when app launching, so in onStart() of MainActivity, we'll check if users haven't typed true before, starting LockActivity immediately by Intent! In order to detect users passed the lock screen or not, we'll use SharedPreferences. Source code simple like this:
MainActivity.java
package info.devexchanges.lockscreen;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.text)
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onStart() {
        super.onStart();
        if (!isPass()) {
            Intent intent = new Intent(this, LockActivity.class);
            startActivity(intent);
        } else {
            textView.setText("The code you typed is right!");
        }
    }

    private boolean isPass() {
        SharedPreferences prefs = getSharedPreferences("PASS_CODE", MODE_PRIVATE);
        return prefs.getBoolean("is_pass", false);
    }

    @Override
    protected void onStop() {
        super.onStop();

        SharedPreferences.Editor editor = getSharedPreferences("PASS_CODE", MODE_PRIVATE).edit();
        editor.putBoolean("is_pass", false);
        editor.apply();
    }
}
As you can see, we must remove password when the main activity closed (by override onStop() to guaranteed that the lock activity always shown when app resumed!

Lock activity programmatically code

    In this activity, we must:
  • Handle click event of all buttons in the keypad (to get input code - password)
  • Update dots layout when input code changed
  • Check input code right or wrong. If right, return to the main activity and if wrong, show a Toast to warning.
    And this is it's source code:
LockActivity.java
package info.devexchanges.lockscreen;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.List;

import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LockActivity extends AppCompatActivity {

    @BindViews({R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6,
            R.id.btn7, R.id.btn8, R.id.btn9, R.id.btn_clear})
    List<View> btnNumPads;

    @BindViews({R.id.dot_1, R.id.dot_2, R.id.dot_3, R.id.dot_4})
    List<ImageView> dots;

    private static final String TRUE_CODE = "2869";
    private static final int MAX_LENGHT = 4;
    private String codeString = "";

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

        setContentView(R.layout.activity_lock);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_clear)
    public void onClear() {
        if (codeString.length() > 0) {
            //remove last character of code
            codeString = removeLastChar(codeString);

            //update dots layout
            setDotImagesState();
        }
    }

    @OnClick({R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6,
            R.id.btn7, R.id.btn8, R.id.btn9})
    public void onClick(Button button) {
        getStringCode(button.getId());
        if (codeString.length() == MAX_LENGHT) {
            if (codeString.equals(TRUE_CODE)) {
                Toast.makeText(this, "Code is right", Toast.LENGTH_SHORT).show();
                setIsPass();
                finish();
            } else {
                Toast.makeText(this, "Wrong Pass code", Toast.LENGTH_SHORT).show();
                //vibrate the dots layout
                shakeAnimation();
            }
        } else if (codeString.length() > MAX_LENGHT){
            //reset the input code
            codeString = "";
            getStringCode(button.getId());
        }
        setDotImagesState();
    }

    private void shakeAnimation() {
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.vibrate_anim);
        findViewById(R.id.dot_layout).startAnimation(shake);
        Toast.makeText(this, "Wrong Password", Toast.LENGTH_SHORT).show();
    }

    private void getStringCode(int buttonId) {
        switch (buttonId) {
            case R.id.btn0:
                codeString += "0";
                break;
            case R.id.btn1:
                codeString += "1";
                break;
            case R.id.btn2:
                codeString += "2";
                break;
            case R.id.btn3:
                codeString += "3";
                break;
            case R.id.btn4:
                codeString += "4";
                break;
            case R.id.btn5:
                codeString += "5";
                break;
            case R.id.btn6:
                codeString += "6";
                break;
            case R.id.btn7:
                codeString += "7";
                break;
            case R.id.btn8:
                codeString += "8";
                break;
            case R.id.btn9:
                codeString += "9";
                break;
            default:
                break;
        }
    }

    private void setDotImagesState() {
        for (int i = 0; i < codeString.length(); i++) {
            dots.get(i).setImageResource(R.drawable.dot_enable);
        }
        if (codeString.length()<4) {
            for (int j = codeString.length(); j<4; j++) {
                dots.get(j).setImageResource(R.drawable.dot_disable);
            }
        }
    }

    private String removeLastChar(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        return s.substring(0, s.length() - 1);
    }

    private void setIsPass() {
        SharedPreferences.Editor editor = getSharedPreferences("PASS_CODE", MODE_PRIVATE).edit();
        editor.putBoolean("is_pass", true);
        editor.apply();
    }
}
    This is output when app running:

Shaking animation

    As you see at the output video, when user type a wrong code, the dots layout will be shake. This is xml file to make this animation:
res\anim\shake_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate
        android:duration="70"
        android:fromDegrees="-5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="5"
        android:repeatMode="reverse"
        android:interpolator="@android:anim/linear_interpolator"
        android:toDegrees="5" />
    <translate
        android:fromXDelta="-10"
        android:toXDelta="10"
        android:repeatCount="5"
        android:repeatMode="reverse"
        android:interpolator="@android:anim/linear_interpolator"
        android:duration="70" />
</set>
    And this is output:

    You can make other better animation than this by research more about animation in Android!
     In this project, I use ButterKnife to make finViewbyId work become easier! In order to use this library, please add this dependency to your app-level build.gradle:
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

Conclusions

    Make a lock screen inside your own application is a not hard work, you can design it better and should pay attention to developing animation and further, vibrating device when user type a wrong code! The fact that there are many third-party libraries which can help you make this layout without write XML codes yourself. Please read my previous post to learn about using one of them. Finally, you can get full project code on Github.

Android simple lock screen with an external library

    Sometimes, in a high security application, it has a lock screen. Only when the correct password entered here, we can continue to use the application. Designing a lock screen in Android is not quite hard, but if you are a...lazy developer, you can use an external library to make it, by searching on the Internet, you can find out a lot of libraries to resolved this problem.
    In this post, I will introduce one of them: PinLockView which able to help you build a lock screen quickly.
DEMO VIDEO:

Importing library

    In order to use it, please add this dependency to your app/build.gradle file:
dependencies {
    // other dependencies here

    compile 'com.andrognito.pinlockview:pinlockview:1.0.1'
}
    Syncing gradle and start coding!

Building the lock-activity

    There are 2 objects in this library which we will use:
  •  PinLockView: a subclass of RecyclerView (can be scrolled in small device screen), which represents a numeric lock view which can used to taken numbers as input. 
  •  IndicatorDots: it represents a set of indicator dots which when attached with PinLockView which can be used to indicate the current length of the input.
    Make a simple layout for the lock-activity like this:
activity_lock.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#99b3ff"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/profile_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/activity_horizontal_margin"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/profile_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/profile_image"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="36dp"
        android:fontFamily="sans-serif-thin"
        android:gravity="center"
        android:maxLines="1"
        android:text="Please Unlock first"
        android:textColor="@color/white"
        android:textSize="24sp" />

    <com.andrognito.pinlockview.IndicatorDots
        android:id="@+id/indicator_dots"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/profile_name"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/activity_horizontal_margin" />

    <com.andrognito.pinlockview.PinLockView
        android:id="@+id/pin_lock_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/indicator_dots"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/activity_horizontal_margin"
        app:keypadButtonSize="72dp"
        app:keypadShowDeleteButton="true"
        app:keypadTextColor="@android:color/holo_green_dark"
        app:keypadTextSize="14dp" />

</RelativeLayout>
    For more xml atrributes of the PinLockView, you can view the Theming part of this library on Github.
     In the programmatically code, the PinLockView has a callback listener to handling user input(PinLockListener) with 3 methods:
  •  onComplete(): called when the complete pin is entered, depends on the pin length set by the user. 
  • onEmpty(): called when the pin is empty after manual deletion. 
  • onPinChange(): called when a key press on the PinLockView.
    And the full code for this activity:
LockActivity.java
package info.devexchanges.applockscreen;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.andrognito.pinlockview.IndicatorDots;
import com.andrognito.pinlockview.PinLockListener;
import com.andrognito.pinlockview.PinLockView;

public class LockActivity extends AppCompatActivity {

    private PinLockView mPinLockView;
    private IndicatorDots mIndicatorDots;
    private final static String TAG = LockActivity.class.getSimpleName();
    private final static String TRUE_CODE = "123456";

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

        setContentView(R.layout.activity_lock);

        mPinLockView = (PinLockView) findViewById(R.id.pin_lock_view);
        mIndicatorDots = (IndicatorDots) findViewById(R.id.indicator_dots);

        //attach lock view with dot indicator
        mPinLockView.attachIndicatorDots(mIndicatorDots);

        //set lock code length
        mPinLockView.setPinLength(6);

        //set listener for lock code change
        mPinLockView.setPinLockListener(new PinLockListener() {
            @Override
            public void onComplete(String pin) {
                Log.d(TAG, "lock code: " + pin);

                //User input true code
                if (pin.equals(TRUE_CODE)) {
                    Intent intent = new Intent(LockActivity.this, MainActivity.class);
                    intent.putExtra("code", pin);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LockActivity.this, "Failed code, try again!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onEmpty() {
                Log.d(TAG, "lock code is empty!");
            }

            @Override
            public void onPinChange(int pinLength, String intermediatePin) {
                Log.d(TAG, "Pin changed, new length " + pinLength + " with intermediate pin " + intermediatePin);
            }
        });
    }
}

The main activity of application

    As you can see at the code above, after putting a true lock code, user will be redirect to the main activity:
MainActivity.java
package info.devexchanges.applockscreen;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.text);
        String code = getIntent().getStringExtra("code");
        textView.setText(String.format("The true code is: %s", code));
    }
}
    And main activity layout (for simple, it only contains a TextView which show the code entered in the lock screen):
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
</RelativeLayout>
    In order to make a good looking lock screen, please use a full screen theme for the lock activity, the styles resource and AndroidManifest.xml will be like this:
styles.xml
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.devexchanges.applockscreen">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LockActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"
            android:label="@string/app_name"/>
    </application>

</manifest>
    Running application, we have this output:
    When user input a wrong code:
    And user input the correct code:

Conclusions and Reference

    I also had a post about the lock screen here (which make it myself), you can take a glance. Through this post, I hope you can build a lock screen for your app quickly by a simple external library. More details about it, please go to the library page on @Github!

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!