androidandroid-activityandroid-taskpicture-in-pictureandroid-picture-in-picture

How to force kill Picture and Picture activity on cross icon click?


i am trying to kill activity from tasks after picture and picture mode was activated and so far I tried finish(), finishAffinity(), onBackPressed(), programmatically set excludeFromRecent but activity still lives on in background..

We can see same behavior in Google Maps when we click on that cross icon. App still lives in background, but i need to brutally kill it :)

    <activity
        android:name=".PipActivity"
        android:launchMode="singleInstance"
        android:supportsPictureInPicture="true"
        android:resizeableActivity="true"
        android:taskAffinity=".PipAffinity"
        android:configChanges="orientation|smallestScreenSize|screenLayout|screenSize"
        android:windowSoftInputMode="adjustPan|stateHidden"/>

This is how i fire intent:

        Intent(context, PipActivity::class.java)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))

Important note: when this activity is not going to PiP mode everything works as expected and activity kills itself normally when i need it!

when i click o this cross icon:

enter image description here

onStop in pipActivity gets called:

override fun onStop() {
        cleanView()
        finish()
        finishAffinity()
        setExcludeRecentToKillActivity()
}

private fun setExcludeRecentToKillActivity() {
    val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val tasks = am.appTasks
    if (tasks != null && tasks.size > 0) {
        tasks[0].setExcludeFromRecents(true)
    }
}

At this point UI is cleaned and connection interrupted. But System still holds task in background and when i click on it it restarts itself.

I dont want this. The task on right is that closed PiP activity that should not be alive. I want to kill it. Is it possible?

enter image description here


Solution

  • So actually i found the solution. finish() have to be changed for finishAndRemoveTask() and task will be closed in background correctly. So setExcludeRecentToKillActivity() is not needed anymore.

    override fun onStop() {
       cleanView()
       finishAndRemoveTask()
       finishAffinity()
    }