How to keep screen awake from Android capacitor plugin?

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?

You should only run npx cap add android once and commit the android (and iOS) folders to your github repo. That way, you can modify the MainActivity and not have it regenerated each time. Not sure why it’s crashing, but it may be due to how the Bridging Activity works

Interesting, because I have found that if you create a new capacitor plugin and add it to the project, the ONLY way I could get the android project to see the new plugin was to delete the android folder in the main project, and re-run “npx cap add android”.

In any case, I’d prefer not to check in the whole auto-generated “android” folder into our source repository, because it is all auto-generated code. In my opinion, auto-generated code doesn’t really belong under source control. As it stands now (without the change to MainActivity.java), we can regenerate most things just from the source files that we actually edit and create.

To add an Android plugin to your project, you should run npx cap sync android or npx cap update android. This updates some Gradle files (not the main build.gradle) and calls a gradle sync to download/install those dependencies. If you run npx cap add android, it will also do an update, which updates/installs the native dependencies.

1 Like