Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AnkiDroid/src/main/java/com/ichi2/anki/SharedDecksActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import com.google.android.material.snackbar.BaseTransientBottomBar.LENGTH_INDEFI
import com.ichi2.anki.common.annotations.NeedsTest
import com.ichi2.anki.databinding.ActivitySharedDecksBinding
import com.ichi2.anki.snackbar.showSnackbar
import com.ichi2.anki.workarounds.SafeWebViewLayout
import com.ichi2.utils.FileNameAndExtension
import dev.androidbroadcast.vbpd.viewBinding
import timber.log.Timber
Expand Down Expand Up @@ -265,6 +266,11 @@ class SharedDecksActivity : AnkiActivity(R.layout.activity_shared_decks) {
}
return super.onOptionsItemSelected(item)
}

override fun onDestroy() {
SafeWebViewLayout.destroyWebView(binding.webView)
super.onDestroy()
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,24 +168,7 @@ open class SafeWebViewLayout :
*/
@MainThread
fun safeDestroy() {
Timber.d("Destroying WebView")

runCatchingWithReport("safeDestroy", onlyIfSilent = true) {
webView.stopLoading()
webView.loadUrl("about:blank")

webView.webChromeClient = null

removeView(webView)

// remove listeners this class exposes
webView.setOnScrollChangeListener(null)
}

// attempt to run destroy() even if the above fails
runCatchingWithReport("safeDestroy", onlyIfSilent = true) {
webView.destroy()
}
destroyWebView(webView, this)
}

companion object {
Expand All @@ -194,6 +177,36 @@ open class SafeWebViewLayout :
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
)

/**
* Clean up and destroy the [webView] to prevent memory leaks.
*
* Stops any loading, clears callbacks, and removes the view from its [parent].
*/
fun destroyWebView(
webView: WebView?,
parent: ViewGroup? = webView?.parent as? ViewGroup,
) {
Timber.d("Destroying WebView")

runCatchingWithReport("safeDestroy", onlyIfSilent = true) {
webView?.apply {
stopLoading()
loadUrl("about:blank")
webChromeClient = null
// remove listeners this class exposes
setOnScrollChangeListener(null)
}

// remove WebView from parent view
parent?.removeView(webView) ?: Timber.w("WebView parent is null")
}

// attempt to run destroy() even if the above fails
runCatchingWithReport("safeDestroy", onlyIfSilent = true) {
webView?.destroy()
}
}
}
}

Expand Down