title: Lock screen Programmatically
body: <p>I use this code to get pattern lock but it does not work. I want to lock the screen on button click.</p>
  
  <p>main.xml</p>
  
  <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
      android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"&gt;
  
      &lt;Button
          android:id="@+id/button"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="Lock"
          android:onClick="lock"/&gt;
  
  &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p>MainActivity.java</p>
  
  <pre><code>public class MainActivity extends ActionBarActivity {
  
      DevicePolicyManager mDPM;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
      }
  
      public void lock(View view) {
          mDPM.lockNow();
      }
  }
  </code></pre>
  
  <p>I want to do like this<a href="https://i.stack.imgur.com/UdrOv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UdrOv.png" alt="enter image description here"></a></p>