Prevent mobile device auto lock screen on iOS / Android

Well I guess I just helped myself, here’s the Android solution if anyone’s interested:

  1. Keep the same Autolock.h file as in the post above and just add a JUCE_ANDROID flag on top, so the AutoLock struct is available for Android as well.

  2. Add an Autolock.cpp file

  3. In the Autolock.cpp file

    #include "AutoLock.h"
    
    #if JUCE_ANDROID
    #include <juce_core/native/juce_android_JNIHelpers.h>
    
    #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK)\
         METHOD (addFlags, "addFlags", "(I)V") \
         METHOD (clearFlags, "clearFlags", "(I)V") \
    
    DECLARE_JNI_CLASS (Window, "android/view/Window")
    #undef JNI_CLASS_MEMBERS
    
    void AutoLock::setAutolockEnabled (bool state)
    {
          auto activity = getMainActivity();
          auto env = getEnv();
          auto window = env->CallObjectMethod(activity.get(), AndroidActivity.getWindow);
    
             //https://developer.android.com/reference/android/view/WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON
          const auto keepScreenOnFlag { 0x00000080 };
    
          if (state)
               env->CallVoidMethod(window.get(), Window.clearFlags, keepScreenOnFlag);
          else
               env->CallVoidMethod(window.get(), Window.addFlags, keepScreenOnFlag);
    
          DBG("Android Auto Lock " << String(state? "enabled" : "disabled"));
    }
    #endif
    

Hope this will help somebody :slight_smile:

5 Likes