Мне необходимо, чтобы ссылки открывались через браузер, а pdf обрабатывались методом onDowndloadStart, как это сделать? 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 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.databinding.FragmentWebviewBinding
import java.net.URL
import ru.maxi.mobile.core.network.BuildConfig as NetworkBuildConfig

/**
 * Фрагмент для отображения 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)
        Log.d("TESTING", "onViewCreated screenargs.uri = ${screenArgs.uri}")
        Log.d("TESTING", "onViewCreated screenargs.uri.host = ${screenArgs.uri.host}")
        Log.d("TESTING", "onViewCreated screenargs.uri.path = ${screenArgs.uri.path}")
        Log.d("TESTING", "onViewCreated screenargs.uri.scheme = ${screenArgs.uri.scheme}")

        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) }
                }
            }
        }
    }

    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,
        ) {
            Log.d("TESTING", "onDoswnloadStart")
            if (url != null) {
                Log.d("TESTING", "onDoswnloadStart mimeType = $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", "shouldOverrideUrlLoading uri $uri")
            Log.d("TESTING", "shouldOverrideUrlLoading uri.host ${uri.host}")
            Log.d("TESTING", "shouldOverrideUrlLoading uri.path ${uri.path}")
            Log.d("TESTING", "shouldOverrideUrlLoading uri.scheme ${uri.scheme}")
            Log.d("TESTING", Uri.parse(screenArgs.uri.toString()).host.toString())
            return when {
                screenArgs.uri.host == uri.host -> super.shouldOverrideUrlLoading(view, request)
                else -> {
                    false
                    // val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri.toString()))
                    // startActivity(browserIntent)
                    // true
                }
            }
        }

        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()
            }
        }
    }
}