I know this question is asked many times but I found that none of the solution is working. I tried the code given below...
protected void onPause() {
The sure way of providing a flawless, non-root lockscreen functionality is by combining your "locker" app idea with a launcher app.
A simple change in the manifest will allow your app to register as a homescreen/launcher, which will give your .apk full control of the home button:
Pulled from this tutorial
You will then have two activities, one for your home-screen, one for your lock screen.
You'll have to detect when the screen is turned off/turned on, to show your lock screen activity:
public class MainActivity extends Activity {
//Create a receiver for screen-on/screen-off
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//Show lock-screen
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//Also show lock-screen, to remove flicker/delay when screen on?
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}
Pulled from this answer
FYI: since your "lock screen" will still be considered part of your launcher at this point, apps will be able to launch on top of your lock-screen, which is bad if: the user has access to the notification drawer to click on messages/Tweets etc, but can also be good for: being able to answer incoming calls without unlocking the phone.
Either way, your lock screen activity should override onPause, check whether the user is "authenticated", if he is not, assume that the user opened something and should go back to the lock screen:
@Override
public void onPause() {
super.onPause();
if(password!=storedPassword) {
//Lockscreen activity shouldn't ever be escaped without the right password!
//Return to launcher without root!
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
}
For better user experience, you should give your user the option to allow a few apps to bypass the lockscreen (such as Spotify), you can include that in the if statement above (ex. if(password!=storedPassword||isForegroundAppSpotify)).
As far as loading apps on your homescreen, you can refer to tutorials on Google for creating your own launcher activity.
Combining launcher+lock-screen is the easiest way to avoid root access. You may find it easier to use root, but you'll limit your customer base.
Hope this helps!