Lock the Android device programmatically

The activity class should be inner class and the outter class should extend DeviceAdminReceiver

public class adminActivity extends DeviceAdminReceiver {

   public static class Controller extends Activity {

                    DevicePolicyManager mDPM;
            ComponentName mDeviceAdminSample;

        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
                mDeviceAdminSample = new ComponentName(Controller.this,
                        adminActivity.class);
      }
   }
}

To lock the device write the code in the event where you use to lock

if (active) {
mDPM.lockNow();
}

If DeviceAdmin is enabled then the phone will be locked.
To enable the device admin, the DevicePolicyManager intent is called and it should be enabled by the user.

Intent intent = new   Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);  
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample);        

Leave a Comment