How to lock/unlock phone programmatically : Android
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;
As of API 27, FLAG_SHOW_WHEN_LOCKED
and FLAG_TURN_SCREEN_ON
were deprecated. Instead use this in the Manifest
<activity
android:name=".MyActivity"
android:turnScreenOn="true"
android:showWhenLocked="true"/>
Or, for general usage, in your activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
} else {
Window window = getWindow();
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
}