How to Lock/Unlock screen programmatically?
Asked Answered
S

3

42

I am doing an application which Locks the screen on shake. Now it is locking and from there it going to a broadcast receiver from there if the screen is off its entering into a service which has to turn the screen on.

Below is the broadcast receiver:

  public class ScreenReceiver extends BroadcastReceiver {   
    public static boolean wasScreenOn = true;
    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("Entered Broadcaste Reciever");

        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // DO WHATEVER YOU NEED TO DO HERE
             System.out.println("SCREEN_OFF"+wasScreenOn);
            wasScreenOn = false;

            Intent i = new Intent(context, UpdateService.class);
            i.putExtra("screen_state", wasScreenOn);
            context.startService(i);

            System.out.println("jrkejhr keh");
        }
        else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // AND DO WHATEVER YOU NEED TO DO HERE
            wasScreenOn = true;
            System.out.println("SCREEN_ON"+wasScreenOn);
        }
    }

And its entering to a service where i had written the intent action to go home is...

  ShakeListener mShaker;
    int amountOfTime = 0;
    Context context1;   
    @Override   
         public void onCreate() {

            super.onCreate();

            // REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
            System.out.println("Enterd Service");
            final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

            mShaker = new ShakeListener(this);
            mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
              public void onShake() {
                vibe.vibrate(100);
                Intent goHome = new Intent();
                goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                goHome.setAction("android.intent.action.MAIN");
                goHome.addCategory("android.intent.category.HOME");
                startActivity(goHome);                      
               }
            });
         }
       @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
     }

It is entering into the service. But home screen is not displaying. When the service is invoked the the screen is locked.

Scansion answered 16/1, 2013 at 6:39 Comment(1)
R
38

Edit:

As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.

Original Answer was:

You need to get Admin permission and you can lock phone screen

please check below simple tutorial to achive this one

Lock Phone Screen Programmtically

also here is the code example..

LockScreenActivity.java

public class LockScreenActivity extends Activity implements OnClickListener {  
 private Button lock;  
 private Button disable;  
 private Button enable;  
 static final int RESULT_ENABLE = 1;  

     DevicePolicyManager deviceManger;  
     ActivityManager activityManager;  
     ComponentName compName;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        deviceManger = (DevicePolicyManager)getSystemService(  
          Context.DEVICE_POLICY_SERVICE);  
        activityManager = (ActivityManager)getSystemService(  
          Context.ACTIVITY_SERVICE);  
        compName = new ComponentName(this, MyAdmin.class);  

        setContentView(R.layout.main);  

        lock =(Button)findViewById(R.id.lock);  
        lock.setOnClickListener(this);  

        disable = (Button)findViewById(R.id.btnDisable);  
        enable =(Button)findViewById(R.id.btnEnable);  
        disable.setOnClickListener(this);  
        enable.setOnClickListener(this);  
    }  

 @Override  
 public void onClick(View v) {  

  if(v == lock){  
    boolean active = deviceManger.isAdminActive(compName);  
             if (active) {  
                 deviceManger.lockNow();  
             }  
  }  

  if(v == enable){  
   Intent intent = new Intent(DevicePolicyManager  
     .ACTION_ADD_DEVICE_ADMIN);  
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,  
                    compName);  
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  
                    "Additional text explaining why this needs to be added.");  
            startActivityForResult(intent, RESULT_ENABLE);  
  }  

  if(v == disable){  
     deviceManger.removeActiveAdmin(compName);  
              updateButtonStates();  
  }    
 }  

 private void updateButtonStates() {  

        boolean active = deviceManger.isAdminActive(compName);  
        if (active) {  
            enable.setEnabled(false);  
            disable.setEnabled(true);  

        } else {  
            enable.setEnabled(true);  
            disable.setEnabled(false);  
        }      
 }  

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
         switch (requestCode) {  
             case RESULT_ENABLE:  
                 if (resultCode == Activity.RESULT_OK) {  
                     Log.i("DeviceAdminSample", "Admin enabled!");  
                 } else {  
                     Log.i("DeviceAdminSample", "Admin enable FAILED!");  
                 }  
                 return;  
         }  
         super.onActivityResult(requestCode, resultCode, data);  
     }  
}

MyAdmin.java

public class MyAdmin extends DeviceAdminReceiver{  


    static SharedPreferences getSamplePreferences(Context context) {  
        return context.getSharedPreferences(  
          DeviceAdminReceiver.class.getName(), 0);  
    }  

    static String PREF_PASSWORD_QUALITY = "password_quality";  
    static String PREF_PASSWORD_LENGTH = "password_length";  
    static String PREF_MAX_FAILED_PW = "max_failed_pw";  

    void showToast(Context context, CharSequence msg) {  
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
    }  

    @Override  
    public void onEnabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: enabled");  
    }  

    @Override  
    public CharSequence onDisableRequested(Context context, Intent intent) {  
        return "This is an optional message to warn the user about disabling.";  
    }  

    @Override  
    public void onDisabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: disabled");  
    }  

    @Override  
    public void onPasswordChanged(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw changed");  
    }  

    @Override  
    public void onPasswordFailed(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw failed");  
    }  

    @Override  
    public void onPasswordSucceeded(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw succeeded");  
    }  

}
Romina answered 16/1, 2013 at 6:52 Comment(7)
Is it possible for me to implement this in a serviceScansion
@Scansion how this code unlock the scree?The question was how to unlock screen.And why this is an accepted answer if this does not unlock screen?Bruch
@RDC actually the original question was how to lock AND unlock the device programmatically. The answer you link for unlocking only works for non-secure lock screens (slide unlock).Zindman
@Zindman the OP asked question for two tasks Lock and Unlock, I have done only Locking in my earlier project and shared here, and if you read carefully my answer says the same words, Hope you got me.Romina
@RDC When I push Enable I always got "DeviceAdminSample﹕ Admin enable FAILED!" on "boolean active = deviceManger.isAdminActive(compName);" lineForgo
Have anyone tried to uninstall the app after implementing this code? I can't do so? I can't do so?Iolenta
Deprecated in sdk 30Zingg
E
16

The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.

Thanks all for this helpful question!

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.kns"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LockScreenActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyAdmin"
                android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data android:name="android.app.device_admin"
                       android:resource="@xml/policies" />
            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

policies.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <limit-password />
        <watch-login />
        <reset-password />
        <force-lock />
        <wipe-data />
    </uses-policies>
</device-admin>
Ecuador answered 6/7, 2016 at 23:57 Comment(1)
thank you but what about android 6 not working this lock thingBelda
T
14

Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:

Tegantegmen answered 16/1, 2013 at 6:45 Comment(1)
This works only as long as your app is on the foreground no? What if you wish to really unlock, so that the user could launch other apps? Maybe there is a workaround? Using draw-on-top? Or a foreground service?Slifka

© 2022 - 2024 — McMap. All rights reserved.