How can i set up screen lock with a password programmatically?
Asked Answered
L

5

14

Is there any one that can help me with a code to set a password to lock the screen ? thx

Lingulate answered 15/3, 2012 at 16:54 Comment(0)
B
23

Use this code in your App, it works for me:

DevicePolicyManager devicePolicyManager =   
             (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName demoDeviceAdmin = new ComponentName(this, name of activity);

devicePolicyManager.setPasswordQuality(
             demoDeviceAdmin,DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
devicePolicyManager.setPasswordMinimumLength(demoDeviceAdmin, 5);

boolean result = devicePolicyManager.resetPassword("123456",
             DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);

Toast.makeText(this, "button_lock_password_device..."+result, Toast.LENGTH_LONG).show();
Bacillus answered 11/12, 2012 at 16:14 Comment(3)
what is tha "name of activity"? which activity?Actaeon
what is the name of the activity?Those
"name of activity" is the name of the class inherited from the DeviceAdminReceiver.Silvester
C
4

Check this . This worked for me.

enter image description here

LockScreenActivity.java

   package com.kns;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

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

    package com.kns;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;

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");
    } 

} 

main.xml

    <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="To Lock Screen First Enable it.." android:textsize="15sp"></textview>

    <button android:id="@+id/lock" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Lock The Phone"></button>

    <button android:id="@+id/btnEnable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enable"></button>

    <button android:id="@+id/btnDisable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Disable"></button></linearlayout>

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>
    </wipe-data></force-lock></reset-password></watch-login></limit-password></uses-policies>
</device-admin>

You can have this policies.xml either in layout or in xml folder. Only thing you need to take care is metadata tag in Androidmanifest file.

 <?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">
                </category></action></intent-filter>
            </activity>
 <receiver android:name=".MyAdmin" android:permission="android.permission.BIND_DEVICE_ADMIN">
     <meta-data android:name="android.app.device_admin" android:resource="@layout/policies">
                    <intent-filter>
         <action android:name="android.app.action.DEVICE_ADMIN_ENABLED">
                        </action></intent-filter>
                    </meta-data></receiver>
 </application>
        </uses-sdk></manifest>

Before Lock the screen you need to Enable Admin Permission

enter image description here

Then you will get this..

enter image description here

After Enable you will lock screen..like this

enter image description here

Centreboard answered 25/8, 2015 at 9:19 Comment(2)
A link to a potential solution is always welcome, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. Take into account that being barely more than a link to an external site is a possible reason as to Why and how are some answers deleted?.Reek
It´s works in the emulador. But it is not locked properly. the screen turns black and can return to the application by pressing the option back.Thermocouple
K
0

http://developer.android.com/guide/topics/admin/device-admin.html

private static DevicePolicyManager dpm =
        (DevicePolicyManager)context
            .getSystemService(Context.DEVICE_POLICY_SERVICE);

private static ComponentName admin = 
        new ComponentName(context, DeviceAdminManager.class);
// add password policies you want
dpm.setPasswordQuality(admin, DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
dpm.setPasswordMinimumLength(admin, 5);

**boolean result = dpm.resetPassword("newPassword", RESET_PASSWORD_WITHOUT_ENTRY);**
Kramlich answered 12/7, 2012 at 20:29 Comment(0)
F
0

check out this website http://blog.stef.be/patternlock. In this website, the implementation of screen lock pattern using javascript, html and css was defined very clearly...Entire code is available since its open source..Hope it wil help you

Farra answered 23/7, 2012 at 12:17 Comment(0)
A
0

Android N is not working , See Here

Note: This API has been limited as of N for device admins that are not device owner and not profile owner. The password can now only be changed if there is currently no password set. Device owner and profile owner can still do this when user is unlocked and does not have a managed profile.

Anarchism answered 8/12, 2017 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.