Search code examples
androidandroid-activityandroid-progressbaractivity-lifecycle

How to show some content when android app in onStop


I have a simple question: is there a way to show something, like a progress bar, when the app is onStop? Because my app does a lot of computation, and when it is actually doing that goes on onStop and a black screen is showed, finally when the computation is done it return to the normal screen. So, it is all correct in a functional point of view, but aesthetically it is not so good. Have you got any tip?


Solution

  • So you basically want to prevent your device from going to sleep while the computation is running? That is called a WakeLock, and it basically prevents your activity from turning off the screen. Be careful to use it sparingly, to avoid draining your users battery.

    It's very easy to do this programatically:

    class MainActivity : Activity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        }
    }
    

    Or you can add an xml attribute to the view you want to show:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true">
        ...
    </RelativeLayout>
    

    For more information and details have a look at the documentation