Prevent screen dimming

Does anyone know how to prevent the screen on the mobile phone from dimming (to save energy)?

I am using cocos2d-x-3.0 and building for Android.

Does cocos2d-x have any functionality to regulate this? I have looked everywhere in the sourcecode of the engine but I have found nothing so far.

I don’t think cocos2d-x have this feature.

Here is how I did it (with the ability to toggle it on or off, for example if only one scene need this feature) :
public static void preventIdleTimerSleep(boolean prevent)
{
//Those operations must be executed on the main thread, otherwise there is an exception
getMainActivity().runOnUiThread(prevent ? new Runnable()
{
@Override
public void run()
{
Log.i(TAG, “Preventing app from sleep”);
getMainActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
: new Runnable()
{
@Override
public void run()
{
Log.i(TAG, “Stop preventing app from sleep”);
getMainActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
}

You need to create a JNI wrapper to call it from C++. It is fairly easy to do.

You’ll need the WAKE_LOCK permission in your manifest.

Thanks for the answer. JNI wrapper. Sounds advanced.
:slight_smile:

I googled like a maniac and I found that one can add the line:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

in one of the cocos2d-x 3.0 source files.

\cocos2d-x-3.0\cocos\2d\platform\android\java\src\org\cocos2dx\lib\Cocos2dxActivity.java

On line 66 inside the function:
protected void onCreate(final Bundle savedInstanceState) {
}

I also needed to import the package android.view.WindowManager;

Code:
import android.view.WindowManager;

It works when I am building the debug version. Havn’t tried the release yet.
I am gonna consider your more advanced solution though. Thanks again!

My solution for now:
File:
\cocos2d-x-3.0\cocos\2d\platform\android\java\src\org\cocos2dx\lib\Cocos2dxActivity.java

Added code on line 38:
import android.view.WindowManager;

Added code on line 66:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

2 Likes

It’s not really advanced (a bit complicated at first, but it’s required as soon as you need an Android feature not already in cocos2d-x). There are some JNI wrappers in cocos2d-x project you can take example on.

But yes, changing directly Cocos2dxActivity is the easy solution.

1 Like