When we press this button
We see the apps which we didn\'t close, like this
But when we want to close an app from this screen (below image), the method onD
More promising approach than using a bound service would be using activity lifecycle callbacks in the Application. Though the approach shown in the accepted answer would work but the service would be running in the background until the activity is terminated which is expensive. Instead, I would suggest the use of your implementation of Application.
1) Make a class extending Application, then use it by providing its name in the name attribute of Application tag in Manifest file
class MusicPlayerApplication: Application() {
private val TAG = MusicPlayerApplication::class.java.simpleName
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(object: ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) {
}
override fun onActivityResumed(activity: Activity?) {
}
override fun onActivityStarted(activity: Activity?) {
}
override fun onActivityDestroyed(activity: Activity?) {
Log.d(TAG, "onActivityDestroyed: ")
val activityName = activity!!.localClassName
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStopped(activity: Activity?) {
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
}
})
}
}
AndroidManifest.xml
I have tested this approach using logcat, my onDestory
is not getting called but onActivityDestroyed
in the callback is getting called every time I kill the activity from RAM but this doc says that onActivityDestroyed
would be called when onDestory
of an activity is called but that doesn't seem to happen. However, I find this approach better than using services.