How to make the power button lock phone without forcing apps with <stay awake> enabled to sleep ?

I am going insane with this problem.I have lost so many hours of data using a number of apps all because of inadvertent button presses.

When you press the power button the screen locks and the phone sleeps.

This overrides any apps that have <stay awake> enabled.

So even if your app has stay awake enabled, by touching the power button it is forced to sleep.

I have to find away of changing this, even if it means customising my Android, I need to change the press of the power button to lock the phone and power down the screen.

I have tried apps that claim to do this but they interfere with my application which is sensing movement because most of them use movement(shake or tilt) to lock the phone, when their app tries to initialise the sensor it messes up my application which needs the sensor exclusively.

An app that uses the Android lock screen and just allows you to switch it on without sleeping any apps would save my day.

I don't understand; are you creating an app which you want to stay alive (continue monitoring sensor(s)) regardless of power state? Or, are you using a Play Store app which you are having this problem with?

If the former, I suggest you post in a developer's forum. If the latter, maybe you need to contact the app's developer.

I'm a little confused by the question as well..what is "stay awake". At any rate you can exclude app from battery optimization within settings/apps/gear/battery-optimization...then they won't be affected by doze.