在将网站网址加载到Android Kotlin的WebView中之前对其进行Ping网站URL [英] Ping website URL before loading it in WebView in Android Kotlin

查看:357
本文介绍了在将网站网址加载到Android Kotlin的WebView中之前对其进行Ping网站URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用WebView加载网站之前,我要检查URL并确保已加载.如果是这样,请显示WebView;如果没有,请显示另一个带有消息的视图.

Before loading a website in WebView, I want to check the URL and make sure that it loads. If it does, show the WebView; if not, show another View with a message.

想法是检查网站是否可以加载,并根据响应显示网站无法加载"屏幕或显示已加载URL的WebView.

The idea is to check if the website can be loaded and depending on the response show either the "Website cannot be loaded" screen or show the WebView with URL loaded.

我已经检查了连接是否可用,因此无需担心.

I have already checked if the connection is available, so no need to worry about that.

需要支持API 25 +.

Need to support API 25+.

推荐答案

我下面的解决方案试图做两件事:

My solution below is trying to do two things:

  1. 使用AsyncTask"ping"网站,然后

  1. Using AsyncTask "ping" a website and then

通过从MainActivity传递上下文,调用一个函数以显示WebView(此处使用WeakReference来实现)

By passing context from MainActivity, call a function to show WebView (using WeakReference here to achieve that)

class MainActivity : AppCompatActivity() {
private var websiteURL = "https://www.google.com"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // ...
    webView.webViewClient = WebViewClient()
}

// I called this function after checking that there is Internet connection
private fun connectionResponseFunction(): String {
    return if (isConnected) {
        // *** is connected
        // pass in "this" context from MainActivity
        val downloadData = CheckLink(this)
        downloadData.execute(websiteURL)
    } else {
      // *** not connected
    }
}

private fun showWebView() {
    webView.loadUrl(websiteURL)
}

companion object {
    class CheckLink internal constructor(context: MainActivity) : AsyncTask<String, Void, String>() {
      // Needed if you want to use webView or anything else from MainActivity
        private val activityReference: WeakReference<MainActivity> = WeakReference(context)

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing) return

            if (result == "success") {
                // URL loaded, show webView
                activity.showWebView()
            } else {
                // URL didn't load
            }
        }

        override fun doInBackground(vararg url: String?): String {
            val linkLoaded = loadLink(url[0])
            if (!linkLoaded) {
                return "failure"
            }
            return "success"
        }

        private fun loadLink(urlPath: String?): Boolean {
            try {
                val url = URL(urlPath)
                val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
                connection.setRequestProperty("Connection", "close")
                connection.connectTimeout = 3000
                connection.connect()

                val response = connection.responseCode

                // 200 for success
                return if (response == 200) {
                    true
                } else {
                    false
                }
            } catch (e: Exception) {
              // Handle exceptions
                when (e) {
                    is MalformedURLException -> "loadLink: Invalid URL ${e.message}"
                    is IOException -> "loadLink: IO Exception reading data: ${e.message}"
                    is SecurityException -> { e.printStackTrace()
                        "loadLink: Security Exception. Needs permission? ${e.message}"
                    }
                    else -> "Unknown error: ${e.message}"
                }
            }
            return false  // Error
        }
    }
}
}

我对Android和Kotlin还是很陌生,因此我乐于接受任何建议以使其变得更好.

I'm quite new to Android and Kotlin, so I'm open to any suggestions to make it better.

我找不到适用于API 25+的任何最新代码.

I could not find any recent code that works for API 25+.

这篇关于在将网站网址加载到Android Kotlin的WebView中之前对其进行Ping网站URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆