How to lock/unlock phone programmatically : Android

Sanjay Joshi picture Sanjay Joshi · Jul 29, 2013 · Viewed 29.8k times · Source

In my application, I need to lock and unlock phone. I searched for it, I found many answers, I tried them but no one is working.

I need to unlock phone on onCreate() and lock phone again while I'm finishing my activity.

Do you guys know any method to do the same?

Thanks friends.

EDIT:

Some links, that I have tried are:

How to display Activity when the screen is locked?

Android screen lock/ unlock programmatically

https://groups.google.com/forum/#!topic/android-developers/BOLjJTMO4zE

In my application I'm scheduling a task using AlarmManager and then enabling the phone lock. My activity is getting started on scheduled time but it not unlocking my phone. when I'm unlocking my phone manually running activity is getting appeared

Answer

sharath yadhav picture sharath yadhav · Sep 8, 2014

on BroadcastReceiver set up the wakelock and in the activity

Do This:

Window window = this.getWindow();
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);

import following

import android.view.Window;
import android.view.WindowManager.LayoutParams;