在 WebView 中加载网站之前,我想检查 URL 并确保它已加载。如果是,则显示 WebView;如果没有,则显示另一个带有消息的 View 。
想法是检查网站是否可以加载,并根据响应显示“网站无法加载”屏幕或显示加载了 URL 的 WebView。
我已经检查过连接是否可用,所以不用担心。
需要支持 API 25+。
最佳答案
我下面的解决方案试图做两件事:
使用
AsyncTask
“ping”一个网站,然后通过从
MainActivity
传递上下文,调用一个函数来显示 WebView(这里使用WeakReference
来实现)
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 的新手,所以我愿意接受任何改进建议。
我找不到适用于 API 25+ 的最新代码。
关于android - 在 Android Kotlin 的 WebView 中加载网站 URL 之前先 Ping 网站 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53402128/