I have written several capacitor plugins for my Android Ionic app. One thing I still need to add is a plugin method to call the following Android API:
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
The above “setFlags” API call causes the Android screen to stay awake, even if the user does not interact with the touchscreen. The reason I need this is because this is a barcode scanning application, and the user only views the screen and pulls the trigger to scan a barcode. The user doesn’t really use the screen’s touch screen while running the app. Therefore, the screen goes dark after a while. I want to keep the screen awake while the app is running because the user is viewing the data on the screen.
I’ve tried adding the above “setFlags” call to my plugin’s Android Java code. However, the Android app instantly crashes when the call is executed. None of the methods in the call chain return “null” (I’ve checked). However, if I move the same exact call to MainActivity.java (which is a file that is auto-generated by the capacitor command “npx cap add android”), then the “setFlags” call works and the screen stays awake as expected.
The problem with this solution is that it’s a customization to auto-generated code. And when we re-generate the Android app by running “npx cap add android” again in the future, then any changes that I make to MainActivity.java will be lost.
Can anyone explain why the above Java call to “setFlags” crashes if I invoke it from within my capacitor plugin?
Any suggestions on how to keep the Android screen awake from code that I can invoke from a capacitor plugin?