When the screen is turned on, I want to check is power button activated it, if yes, it will auto dismiss the keyguard and run the toast.
When the screen is turned o
Okay so this is not as simple as it would seem Services cannot actually own the currently running activity but you need an activity to get a reference to the window
So you could do that bit a couple of different ways.
Turning off the screen from a service
In the answer given in this question a dummy activity is created
(one that is not inflated) and used to get the window (works but
not sure what if the uninflated activity causes a leak or other issues. Plus it seems kinda like a dirty hack)
Or.....
Once you decide how you want to do (I would recommend #2) The following should work but, note I have not tested it.
//Get the window from the context
WindowManager wm = Context.getSystemService(Context.WINDOW_SERVICE);
//Unlock
//http://developer.android.com/reference/android/app/Activity.html#getWindow()
Window window = getWindow();
window.addFlags(wm.LayoutParams.FLAG_DISMISS_KEYGUARD);
//Lock device
DevicePolicyManager mDPM;
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);