August 13, 2021

Lock own app functionality for android

By lj007

The simple demo to create lock screen activity for your android app:

  1. Create one activity which ask for password or pin. It is may be like
  2. Create MyApplication class which  extends Application class.
  3. Set application name in Manifest.xml
    android:name=”.MyApplication” ………>

Now you need two static variable in MyApplication file.

public static boolean locked;
private static long time = 0;

Now define two methods to track app state

public static void activityPaused() {
    time = Calendar.getInstance().getTimeInMillis();}

public static void activityResumed() {
    if (Calendar.getInstance().getTimeInMillis() - time > 60000) {
        locked = true;    } else {
        locked = false;    }
}

And finally override OnResume and OnPause of every activity

@Overridepublic void onResume() {
    super.onResume(); 
    CustomApplication.activityResumed(); 
    if (CustomApplication.locked) {
        startActivity(new Intent(this, LockScreenActivity.class));     
    }
}

@Overrideprotected void onPause() {
    super.onPause(); 
    if(!CustomApplication.locked) 
        CustomApplication.activityPaused(); 
}

Now run app and enjoy security of your app.