Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect the closing of the app and take acction ? ( kotlin )

I want to disable the WiFi when the app is closed. i know the code to disable WiFi using this line :

wifiManager!!.isWifiEnabled = false

but i don't know how to detect the closing of the app.

like image 483
Anis KONIG Avatar asked Feb 03 '26 10:02

Anis KONIG


2 Answers

This exactly what lifecycles are used for. Any clean up work that needs to done should be done in onDestroy(). This is the final call you receive before your activity is destroyed. So in the activity where you want to disable wifi you can just do:

override func onDestroy() {

   super.onDestroy();
   wifiManager!!.isWifiEnabled = false;

}
like image 199
AvidRP Avatar answered Feb 04 '26 23:02

AvidRP


You might check out this blog post. It described how to do it more detail than I could.

EDIT:

Important parts of blog post are:

1 - Create our interface that will be implemented by a custom Application class:

interface LifecycleDelegate {
    fun onAppBackgrounded()
    fun onAppForegrounded()
}

2 - Now we a class that is going to implement the ActivityLifecycleCallbacks and ComponentCallbacks2:

class AppLifecycleHandler(
    private val lifeCycleDelegate: LifeCycleDelegate
) : Application.ActivityLifecycleCallbacks, ComponentCallbacks2
{
    private var appInForeground = false

    override fun onActivityResumed(activity: Activity?) {
        if (!appInForeground) {
            appInForeground = true
            lifeCycleDelegate.onAppForegrounded()
        }
    }

    override fun onTrimMemory(level: Int) {
        if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
            appInForeground = false
            lifeCycleDelegate.onAppBackgrounded()
        }
    }

    // stub other methods
}

3 - We need to use that handler in our application class:

class App : Application(), LifeCycleDelegate {

    override fun onCreate() {
        super.onCreate()
        val lifeCycleHandler = AppLifecycleHandler(this)
        registerLifecycleHandler(lifeCycleHandler)
    }

    override fun onAppBackgrounded() {
        Log.d("App", "App in background")
    }

    override fun onAppForegrounded() {
        Log.d("App", "App in foreground")
    }

    private fun registerLifecycleHandler(lifeCycleHandler: AppLifecycleHandler) {
        registerActivityLifecycleCallbacks(lifeCycleHandler)
        registerComponentCallbacks(lifeCycleHandler)
    }
}
like image 38
TheKarlo95 Avatar answered Feb 05 '26 00:02

TheKarlo95