You can use following code to detect power button press.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
  int keyPressed = event.getKeyCode();
  if(keyPressed==KeyEvent.KEYCODE_POWER){
    Log.d("###","Power button long click");
    Toast.makeText(MainActivity.this, "Clicked: "+keyPressed, Toast.LENGTH_SHORT).show();
    return true;}
  else
    return super.dispatchKeyEvent(event);
}
credits https://stackoverflow.com/a/39197768/9640177
Now to prevent system from showing dialog, you can broadcast to close all system dialogs.
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
Complete solution
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
  int keyPressed = event.getKeyCode();
  if(keyPressed==KeyEvent.KEYCODE_POWER){
    Log.d("###","Power button long click");
    Toast.makeText(MainActivity.this, "Clicked: "+keyPressed, Toast.LENGTH_SHORT).show();
 //send broadcast to close all dialogs
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    return true;}
  else
    return super.dispatchKeyEvent(event);
}
If you want to perform a small action just before shutdown, You can do follow this.
 you can listen for following intent using intent filters.
in your manifest
<uses-permission android:name="android.permission.DEVICE_POWER" />
  ....
  ....//other stuff goes here.
<receiver android:name=".ShutdownReceiver">
  <intent-filter>
    <action android:name="android.intent.action.ACTION_SHUTDOWN" />
    <action android:name="android.intent.action.QUICKBOOT_POWEROFF" />
  </intent-filter>
</receiver>
credit https://stackoverflow.com/a/39213344/9640177
Once you receive this intent you know that the po