Есть html страница в webView. У меня проблема в том, что shouldOverrideUrlLoading при клике на pdf ссылку вызывается первее, чем downloadListener, что делать? package ru.maxi.mobile.feature.webview.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.DownloadListener
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import by.kirich1409.viewbindingdelegate.viewBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import ru.maxi.mobile.BuildConfig
import ru.maxi.mobile.R
import ru.maxi.mobile.base.ui.MvvmBaseFragment
import ru.maxi.mobile.common.utils.android.screenArgs
import ru.maxi.mobile.common.utils.android.setupDarkMode
import ru.maxi.mobile.core.data.LoadableData
import ru.maxi.mobile.core.network.BuildConfig as NetworkBuildConfig
import ru.maxi.mobile.databinding.FragmentWebviewBinding
import java.net.URL

/**
 * Фрагмент для отображения WebView
 */
@AndroidEntryPoint
class WebViewFragment : MvvmBaseFragment(R.layout.fragment_webview) {

    private val screenArgs by screenArgs(WebViewArgs)

    private val viewBinding by viewBinding(FragmentWebviewBinding::bind)

    private val viewModel by viewModels<WebViewViewModel>()

    override val analyticsName: String = "_WebView"

    @SuppressLint("SetJavaScriptEnabled")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        actionBarManager.setTitle(screenArgs.title)
        actionBarManager.showBackButton()

        with(viewBinding) {
            webView.apply {
                settings.apply {
                    textZoom = 100
                    javaScriptEnabled = true
                }
                webViewClient = CustomWebViewClient()
                setupDarkMode()
                setDownloadListener(CustomDownloadListener())
            }
            noConnectionView.setOnActionButtonClickListener { webView.reload() }
        }

        with(viewLifecycleOwner) {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    launch { viewModel.viewState.collect(::onViewStateChange) }
                }
            }
        }
        Log.d("TESTING", "WebViewCreated uri ${screenArgs.uri}")
        Log.d("TESTING", "WebViewCreated uri path ${screenArgs.uri.path}")
        Log.d("TESTING", "WebViewCreated uri scheme ${screenArgs.uri.scheme}")
        Log.d("TESTING", "WebViewCreated uri host ${screenArgs.uri.host}")
    }

    private fun onViewStateChange(viewState: LoadableData<URL>) {
        when (viewState) {
            is LoadableData.Loading -> with(viewBinding) {
                loaderView.show()
                noConnectionView.isVisible = false
                webView.isInvisible = true
                viewState.value?.let(::loadPage)
            }

            is LoadableData.Error -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = true
                webView.isInvisible = true
            }

            is LoadableData.Success -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = false
                webView.isVisible = true
                loadPage(viewState.value)
            }
        }
    }

    private fun loadPage(url: URL) {
        if (viewBinding.webView.url != url.toString()) {
            viewBinding.webView.loadUrl(url.toString())
        }
    }

    private inner class CustomDownloadListener : DownloadListener {
        override fun onDownloadStart(
            url: String?,
            userAgent: String?,
            contentDisposition: String?,
            mimeType: String?,
            contentLength: Long,
        ) {
            if (url != null) {
                Log.d("TESTING", "$mimeType")
                try {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(Uri.parse(url), mimeType)
                    val packageManager = requireContext().packageManager
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                    } else {
                        val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(browserIntent)
                    }
                } catch (ignored: Exception) {
                }
            }
        }
    }

    private inner class CustomWebViewClient : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            val uri = request.url
            Log.d("TESTING", "uri.host = ${uri.host}")
            Log.d("TESTING", "uri.path = ${uri.path}")
            Log.d("TESTING", "uri.schema = ${uri.scheme}")
            Log.d("TESTING", "uri.fragment = ${uri.fragment}")
            Log.d("TESTING", "request.url (uri) = $uri")
            // return super.shouldOverrideUrlLoading(view, request)
            return when {
                uri.toString().startsWith("https://" + NetworkBuildConfig.REST_API_URL) || uri.toString()
                    .startsWith(BuildConfig.MAXI_RETAIL_HOST) -> {
                        Log.d("TESTING", "ShOULDOVERRIDEURL STARTSWITH")
                        return super.shouldOverrideUrlLoading(
                    view,
                    request,
                )}

                else -> {
                    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri.toString()))
                    startActivity(browserIntent)
                    return super.shouldOverrideUrlLoading(view, request)
                }
            }

        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            viewModel.onPageStarted()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            viewModel.onPageFinished()
        }

        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest,
            error: WebResourceError?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }

        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest,
            errorResponse: WebResourceResponse?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }
    }

    companion object {
        private const val BACKEND_PATH = "api/v1"
    }
}