Search code examples
androidscreen-lock

Android screen lock when just click on app icon


i want to create app in that when i click on my app icon , screen autmatically locked, please any one help me to how to do this ?

I much googling but not find like this, so please help me to do it.

In this i click on app_launcher icon and directly mobile screen locked.


Solution

  • Try this code (lock screen and screen off):

    public DevicePolicyManager deviceAdminPolicyManager = (DevicePolicyManager)getSystemService( Context.DEVICE_POLICY_SERVICE);
    public ComponentName deviceAdminComponentName = new ComponentName( this, DeviceAdmin.class);
    
    deviceAdminPolicyManager.lockNow();
    PowerManager powerManager = (PowerManager) getSystemService( Context.POWER_SERVICE);
    if( powerManager.isScreenOn()) powerManager.goToSleep( System.currentTimeMillis() + 1000L);
    

    Your app must be added as device administrator by Settings - Security - Device administartors.

    Also add in Manifest:

    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.DEVICE_POWER"/> <!-- for screen off and on -->
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    
     <receiver android:label="@string/label" android:name="com.package$DeviceAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
      <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin" />
      <intent-filter>
       <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
      </intent-filter>
     </receiver>
    

    And:

    public  static class DeviceAdmin extends DeviceAdminReceiver
     {
       public CharSequence onDisableRequested( Context paramContext, Intent paramIntent) { return ""; }
       public void onDisabled( Context paramContext, Intent paramIntent) {}
       public void onEnabled( Context paramContext, Intent paramIntent) {}
       public void onPasswordChanged( Context paramContext, Intent paramIntent) {}
     }
    

    DeviceAdmin.xml

    <?xml version="1.0" encoding="utf-8"?>
    <device-admin xmlns:android="http://schemas.android.com/apk/res/android">
     <uses-policies>
      <force-lock />
     </uses-policies>
    </device-admin>