Friday, March 2, 2012

Lock Phone Screen Programmtically

How to lock Mobile Phone Screen ...
first of all we need to get permission from Admin
create app with default activity

Project Name : LockScreen
Package Name: com.kns
Android SDK: 2.2 API 8

the project structure is look like this


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
  


    
    
        
    
        
    
        
    
        


policies.xml
  


    
        
        
        
        
        
    


AndroidManifest.xml
  


    

    
        
            
                
                
            
        
        
        
            
            
                
            
        

    


Before Lock the screen you need to Enable Admin Permission

Then you will get this..
 After Enable you will lock screen..like this

we have done it!!

I'd love to hear your thoughts!!

21 comments:

  1. First thank you then I will try and give you feedback

    ReplyDelete
  2. Thank you so much. Its working cool....

    ReplyDelete
  3. Thank you so much. Its working cool...

    ReplyDelete
  4. Very nice tutorial...
    I was searching for this but could not find anything in detail like this... KEEP YOUR GOOD WORK!

    ReplyDelete
  5. Very nice tutorial...
    I was searching for this bt couldnt find anything in detail like this...
    KEEP YOUR GOOD WORK!!

    ReplyDelete
  6. really nice tutorial.
    Can you please put the complete source code here i know it is there but i am facing some problems it is not showing any thing after running this appication in my emulator that's why i am asking the source.

    ReplyDelete
  7. really nice tutorial.
    Can you please put the complete source code here i know it is there but i am facing some problems it is not showing any thing after running this appication in my emulator that's why i am asking the source.

    ReplyDelete
    Replies
    1. okay!! may i know where you getting stuck or any error message, btw coz I'm sorry but now-days I'm home for diwali, Still I'll try to post code asap!!

      Delete
  8. Sir Can you tell me that how you show your code in blog live Code
    Editor. I m also a blog writer and android developer. Please help that how i can show code like you post.

    ReplyDelete
  9. Thanks it working :-)

    ReplyDelete
  10. Thanks it working for me, but how can i unlock the phone?

    ReplyDelete
  11. Hi It is working fine in emulator but it is not working in mobile.
    Please tell the changes if required.

    ReplyDelete
  12. Thank you very much , it worked well .
    but I would like to know how to unlock the screen.
    thanks in advance.

    ReplyDelete
    Replies
    1. hey..did u get the code of hoe to unlock the screen?

      Delete
  13. is there any tutorial for privacy locks???

    ReplyDelete
  14. i have problem with enabling device as admin. im suspecting it might be on the component name. may i know what the value of your compName when you run this statement:
    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
    compName);

    or is there other reasons why i can't enable device as admin?
    thanks

    ReplyDelete
  15. Thank you very match, it is an excellent code.
    I want to show only "Lock screen" instead of ("Erase all data", "set password roles", ........ , "Lock screen") when my app ask for administration.
    If you or anyone know how, please tell me.
    Thanks in advance.

    ReplyDelete
  16. can we do the same using proximity sensors? if yes, please tell how?

    ReplyDelete
  17. Not working on samsung galaxy s3...

    ReplyDelete