Question about Vulkan Initialization / Deinitialization and Android App life cycle event

viewmodel android
android livedata
viewmodelproviders
androidviewmodel
android share viewmodel between activities
android share viewmodel between fragments
how to pass context to viewmodel android
android viewmodel + livedata example

I have studied on Vulkan sample applications provided by numbers of platform venders (Qucomm Adreno SDK, PowerVR SDK, ARM Mali SDK and Google's android NDK samples) for quite a while. I noticed that all samples performe Vulkan initialization and de-initialization in the following code pattern:

void android_main(struct android_app* androidApp)
{
    ...
    androidApp->onAppCmd = [](struct android_app* androidApp, int32_t cmd) -> void //Event handle (Lambda)
    {
        VulkanApp* app = (VulkanApp*)androidApp->userData;
        switch (cmd) 
        {
        case APP_CMD_INIT_WINDOW:   
            initVulkan(...);    //Initialize vulkan: layers, extension, instance, surface, device, swapchain, ...
            break;
        case APP_CMD_TERM_WINDOW:
            deinitVulkan(...);    //Deinitialize vulkan: in reversed order...
            break;
        ...
        }
        ...
    }
    ...
}

Basically app initializes Vulkan components in NDK event APP_CMD_INIT_WINDOW and destroy them in event APP_CMD_TERM_WINDOW. This code is quite reasonable when app is launched by use, runs for a while and then is quit by user.


However, when users swap android app into background (by home or menu button) and then bring it back for several times, paired events APP_CMD_TERM_WINDOW and APP_CMD_INIT_WINDOW will be triggered for several times and thus the function initVulkan() and deinitVulkan() will be called for several times.

Under this scenario the code appear to be unreasonable to me though: since the app is just temporarily pushed to background and brought back to foreground, why should we destroy all Vulkan components like layers, extension, instance, device, surface, swapchain, pipeline ... and recreate them all over? At most, perhaps the only components may need to be recreated are swapchain and pipeline. But why all SDK's samples app performe this heavy recreation?

By the way, when I compare with Vulkan sample source code on other platforms, like Windows, Linux, macOS and iOS, none of them performe such heavy recreations.

I have tried to use a "initialize once" solution but android app crashes when it was brought back to foreground from background.

So may question is: Do we have to destroy and recreate all Vulkan components when Android app swapped between background and foreground? If not, how can we do it?

-----

UPDATE: I have received few kind suggestions about my question and I understand during the "swapped-away" period of Android apps, we better limit system resource held by app (particularly when receiving low-memory warning), and meanwhile, a fine-grained pause/resume mechanism on Vulkan components can help to keep good balance between light memory usage and quick app resumption.

I took a review on Google NDK OpenGL ES "teapot" sample and I noticed that this NDK gl sample uses highly find tuned mechanism to pause / resume OpenGL context: At event handling part, the code looks like:

    switch (cmd)
    {
        case APP_CMD_INIT_WINDOW:
            // The window is being shown, get it ready.
            if (app->window != NULL)
                eng->InitDisplay(app);
            break;
        case APP_CMD_TERM_WINDOW:
            // The window is being hidden or closed, clean it up.
            eng->TermDisplay();
            break;
        case APP_CMD_LOW_MEMORY:
            // Free up GL resources
            eng->TrimMemory();
            break;

And this is code of function InitDisplay():

int Engine::InitDisplay(android_app *app)
{
    if (!initialized_resources_)  // THIS IS FIRST TIME THE EVENT IS TRIGGERED WHEN APP IS LAUNCHED
    {
        gl_context_->Init(app_->window);    //Initialize OpenGL
        LoadResources();
        ...
    }
    else  // TRIGGERED WHEN APP IS BROUGHT BACK FROM BACKGROUND TO FOREGROUND
    {
        // On some devices, ANativeWindow is re-created when the app is resumed
        if (app->window != gl_context_->GetANativeWindow())
        {
            // Re-initialize ANativeWindow.
            assert(gl_context_->GetANativeWindow());
            UnloadResources();
            gl_context_->Invalidate();
            gl_context_->Init(app->window); //Initialize OpenGL again
            LoadResources();
            ...
        }
        // Normal case, only need to resume OpenGL
        else
        {
            // initialize OpenGL ES and EGL
            if (EGL_SUCCESS == gl_context_->Resume(app_->window))//Resume OpenGL
            {
                UnloadResources();
                LoadResources();
            }
            ...
        }
    }
    ...    

As we can see from the code, under most of "good cases", only small part of OpenGL resources are unloaded and reloaded; only under "bad cases", OpenGL context is fully destroyed and recreated, this can generate quick app resumption.

So my question can be extended to : Does any one know a good Vulkan/Android template app that use this find-grined Vulkan pause / resume mechanism? Or would like to share your own code to do this? I'm currently working on this but not going very well.


It's possible to keep most of Vulkan around when in the background, but you're right that you'll have to re-create the swapchain (and any dependent objects, like image views for the swapchain images) since you get a new native window/surface when brought back to the foreground. Unfortunately I don't have any sample code to point you at.

Existing samples probably did it this way for simplicity, since on most other platforms there isn't a need to support swapchains that have a different lifetime to the rest of the top-level Vulkan objects.

It's actually recommended to not discard too much memory immediately when going into the background. But if you don't, you should pay attention to the onTrimMemory callback, and release any large data when you get that. That allows you to restore quickly (and without burning power reloading textures etc.) if the user switches away briefly, but still allows the system to reclaim the memory without completely killing your app if needed.

vulkan - When to use VK_IMAGE_LAYOUT_GENERAL, FWIW, I'm writing Vulkan code that will run on desktop GPUs and Android, but I'm mainly concerned about performance on the latter. vulkan. Performance-critical apps should avoid using software-emulated Vulkan implementations and fall back to OpenGL ES instead. Apply Display Rotation During Rendering. When the upward-facing direction of an app doesn’t match the orientation of the device’s display, the compositor rotates the app’s swapchain images so that it does match.


Under this scenario the code appear to be unreasonable to me though: since the app is just temporarily pushed to background and brought back to foreground, why should we destroy all Vulkan components ...

Define "temporary". A typical user may have dozens of applications opened but idle and running in the background, and if they all hold on to all their resources that's a massive consumer of memory.

Applications using a graphics API is nearly always a heavy user of memory, so it is reasonable to expect backgrounded applications to free up resources for the foreground application to use.

By the way, when I compare with Vulkan sample source code on other platforms, like Windows, Linux, macOS and iOS, none of them perform such heavy recreations.

iOS doesn't force it, but it is highly recommended in developer best practice that an application frees memory heavy resources as part of the applicationDidEnterBackground handler.

The rest are desktop platforms where the application usage model is completely different (open -> close, not open -> suspend), so it's not surprising that they have a different programming model.

ViewModel Overview, ViewModel lets you manage your UI's data in a lifecycle-aware fashion. Handling data layer events · Migrating Wear apps to GoogleApi Configuration and Initialization user actions or device events that are completely out of your control. Another problem is that UI controllers frequently need to make  Shows you how to create a Vulkan instance, device and swapchain on Android. The Native Activity. To get a Vulkan surface up and running, we will use native code exclusively, using NativeActivity. NativeActivity is a built-in Java class in Android which lets us implement applications purely in native code.


Samples: Overview | Android NDK, Managing your native app's activity lifecycle. Vulkan samples are located separately from those for the rest of the NDK. To explore these  Some event interrupts app execution, as described in the onResume() section. This is the most common case. In Android 7.0 (API level 24) or higher, multiple apps run in multi-window mode. Because only one of the apps (windows) has focus at any time, the system pauses all of the other apps.


Vuforia Engine Release Notes, New native sample apps have been created for Android, iOS and UWP. will cause black artifacts to be rendered when the Vulkan graphics API is used. Refactored the way how Unity application code can register for Vuforia Engine events. API documentation has been amended for DataSet usage and its life cycle. A common example of a process life-cycle bug is a BroadcastReceiver that starts a thread when it receives an Intent in its BroadcastReceiver.onReceive() method, and then returns from the function. Once it returns, the system considers the BroadcastReceiver to be no longer active, and thus, its hosting process no longer needed (unless other


Vkframebuffer, In Vulkan, when images are used for rendering or sampling, we need to be valid throughout the question's life, and the question+answer should be self contained. Vulkan program, which was mostly initialization/deinitialization sequences. learning about Vulkan validation layers and how they work in an application,  Vulkan is an experimental build in Unity 5.6.0f3. Have you reached out to the vendor for graphic card of your mobile device to see if they support Vulkan 1.0 specification? I tried with 5 years old mobile graphics card on Windows 10 and it worked. Android Device which supports Vulkan should be running Android API level 24 or higher.


Android Interview Questions And Answers, 1.7 Pressing the home button from an application invokes onPause() and onStop​(). android interview questions, android activity lifecycle On-screen rotation the activity restarts and the objects are initialized again. The orientation changes can occur from a number of other events such as changing the default language  The Android platform includes an Android-specific implementation of the Vulkan API specification from the Khronos Group. Vulkan is a low-overhead, cross-platform API for high-performance, 3D graphics. It provides tools for creating high-quality, real-time graphics in applications.