Restart application instead of reload all resources when opengl es context lost on Android

Restart application instead of reload all resources when opengl es context lost on Android


Current status

Currently, when opengl es context lost after back from background, cocos2d-x will try to reload all resources as possible. In order to achieve it, we do some complex work in engine:

  • reload all programs
  • re-create all textures
  • re-set all gl state

Then you can see similar codes spread all over the engine:

    // Listen this event to save render texture before come to background.
    // Then it can be restored after coming to foreground on Android.
    auto toBackgroundListener = EventListenerCustom::create(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(RenderTexture::listenToBackground, this));
    _eventDispatcher->addEventListenerWithSceneGraphPriority(toBackgroundListener, this);

    auto toForegroundListener = EventListenerCustom::create(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(RenderTexture::listenToForeground, this));
    _eventDispatcher->addEventListenerWithSceneGraphPriority(toForegroundListener, this);

And if program or texture is created from raw data, then we should record all the raw data in engine. It will add the memory usage too.

possible solution

Another solution is to re-start application if the opengl es context lost. This method will simplify the codes, we can remove all codes to recover the states. And may be we can use native activity to prevent missing opengl es context, i am not sure if it works.

pros and cons

Pros and cons of recovering opengl es context:

  • pros
    • application can continue from the point before lost opengl es context
  • cons
    • should add complex logic to recover opengl es context
    • increase memory usage
    • may not recover all the things
    • take a long time to return to foreground if opengl es context lost in background

Pros and cons of re-start application:

  • pros
    • simplify the codes
    • reduce memory usage
  • cons
    • will restart application if gl context lost

when opengl es context lost

I don’t find a documentation to mention it. I think it may happen when system resource is limited. And we find it will not happen frequently as we add this line in engine:



I think we can restart application if opengl es context lost, it will simplify and unify the codes. cocos creator use this method now, and not one complain it.

And we will continue to research how to prevent missing opengl es context, native active may be the solution.

Cocos2d 3.17.1 crash on android
pinned globally #2


Can you elaborate more on what does it means “Context” is lost ?
If context is lost the app will crash no? why do you what to reload the application internally ?


First you can check the doc for OpenGL context. When the context is lost, then program, texture, buffer and other OpenGL resource are invalid.

unpinned #5

pinned #6

unpinned #7

pinned globally #8