Android 如何检查是否可以在Kotlin中打开url
在斯威夫特有一件奇妙的事情Android 如何检查是否可以在Kotlin中打开url,android,kotlin,Android,Kotlin,在斯威夫特有一件奇妙的事情 if UIApplication.shared.canOpenURL(myUrl) { // url can be opened UIApplication.shared.open(myUrl) { success in if !success { //... } } } else { // and cannot } Kotlin中有类似的功能吗?您可以检查URL是否有效,是否使用
if UIApplication.shared.canOpenURL(myUrl) {
// url can be opened
UIApplication.shared.open(myUrl) { success in
if !success {
//...
}
}
} else {
// and cannot
}
Kotlin中有类似的功能吗?您可以检查URL是否有效,是否使用模式。请参见示例函数:
fun isValidUrl(url: String): Boolean {
val p = Patterns.WEB_URL
val m = p.matcher(url)
return m.matches()
}
验证URL后,您可以使用以下方法验证设备是否能够连接到URL:
fun isAPIAvailable(c: Context, url:String): Boolean {
return try {
val ipAddr: InetAddress = InetAddress.getByName(url)
ipAddr.hostAddress != ""
} catch (e: Exception) {
false
}
}
添加isvalidul()
:
然后检查:
val url = "www.myWebpage.com"
if (!url.isValidUrl()) {
// url can be opened
}else{
// and cannot
}
离开文档,它不会检查URL是否可用,只有当有可用的应用程序可以处理其方案时才检查 在Android上,URL必须包装成能够打开它的意图。然后,您可以使用PackageManager检查应用程序是否可用于此目的
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(url)
}
if (intent.resolveActivity(packageManager) != null) {
// url can be opened with startActivity(intent) or requireContext().startActivity(intent)
} else {
// ...
}
如果此函数位于片段而不是活动中,请使用requireContext()前缀packageManager
。
编辑: 您可以检查是否可以使用以下函数连接到URL(改编自):
由于您正在建立连接,因此必须异步执行,否则可能会导致应用程序没有响应错误。因此,我将其设置为一个挂起函数,您可以从协同程序调用。我认为最好的方法应该是ping url并等待第一次响应。感谢我们的回答。据我所知,它通过url启动一个新的活动,但在我的情况下,我不需要它。我只需要通过这个url建立一个连接,然后得到一个布尔值,不管它是否成功。也就是说,首先我应该只检查连接是否成功,然后我必须连接以接收布尔状态响应。这种方法可行吗?不,不是有意的。但iOS方法也不会这么做。如果需要ping URL,则需要异步执行,以避免“活动未响应”错误。请参阅编辑。我在使用
httpURLConnection.responseCode
时遇到问题。它冻结了执行。我在AsyncTask中运行您的示例
val intent = Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(url)
}
if (intent.resolveActivity(packageManager) != null) {
// url can be opened with startActivity(intent) or requireContext().startActivity(intent)
} else {
// ...
}
suspend fun canConnect(url: String): Boolean = withContext(Dispatchers.IO) {
// We want to check the current URL
HttpURLConnection.setFollowRedirects(false)
val httpURLConnection = (URL(url).openConnection() as HttpURLConnection)
// We don't need to get data
httpURLConnection.requestMethod = "HEAD"
// Some websites don't like programmatic access so pretend to be a browser
httpURLConnection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"
)
// We only accept response code 200
return@withContext try {
httpURLConnection.responseCode == HttpURLConnection.HTTP_OK
} catch (e: IOException) {
false
} catch (e: UnknownHostException){
false
}
}