One Tap Lock Screen for Android Java

This tutorial is suitable for both beginners and intermediate Android developers. Whether you're looking to improve your Java programming skills or want to create a useful lock screen app, this blog is for you.

📌 Key Topics Covered:

  1. Setting up your Android Studio environment
  2. Creating a user-friendly lock screen UI
  3. Implementing lock and unlock functionality
  4. Enhancing security with various authentication methods
  5. Customizing the lock screen to match your style

1. res > xml > admin.xml


Code :
 <?xml version="1.0" encoding="utf-8"?>  
 <device-admin xmlns:android="http://schemas.android.com/apk/res/android">  
   <uses-policies>  
     <force-lock/>  
   </uses-policies>  
 </device-admin>  

2. manifests > AndroidManifest.xml inside the application tag


Code:

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

3. Create a Java class MyDeviceAdminReceiver.java


Code:
 public class MyDeviceAdminReceiver extends DeviceAdminReceiver {  
   
 }  

4. Add a button in activity_main.xml


Code:
   <Button  
     android:id="@+id/button"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Lock Screen"  
     />  

5. MainActivity.java 


Code: 
 public class MainActivity extends AppCompatActivity {  
   
   private ComponentName cn;  
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     DevicePolicyManager dpm=(DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);  
     cn = new ComponentName(this, MyDeviceAdminReceiver.class);  
   
     findViewById(R.id.button).setOnClickListener(v -> {  
       toLock();  
       finish();  
       if (dpm.isAdminActive(cn)) {  
         dpm.lockNow();  
         finish();  
         return;  
       }  
   
     });  
   
   } // onCreate method end here ======  
   
   private void toLock() {  
     Intent i=new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);  
     i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, cn);  
     i.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Now");  
     startActivity(i);  
   }  
     
 } // public class end here =============  

Thank You ðŸ¥°


Next Post Previous Post
No Comment
Add Comment
comment url