从android中的另一个应用程序共享时如何检索链接?

问题描述

您好,我正在尝试检索从另一个应用程序共享的 url,并将其敬酒并在 WebViewTab 中打开它。 但是应用程序的 id 显示在吐司中。 这是我的代码

  val extras = intent.extras
        if (extras != null) {
            for (key in activity.intent.extras!!.keySet()) {
                copyKey = key

                val value: String? = activity.intent.extras!!.getString(copyKey)
                Toast.makeText(applicationContext,value,Toast.LENGTH_LONG).show()
                    TabInfo.addTab(value.toString())
                
            }
            val url = intent.extras!!.getString("query")
            if (url.toString().startsWith("http")) {
                TabInfo.addTab(url.toString())
                intent.removeExtra("query")
            }
        }

提前致谢

解决方法

这解决了我的问题:

val extras = intent.extras
        if (extras != null) {
            val externalUrl: Uri? = intent?.data //retrieves the shared text from another app.
            val url = intent.extras!!.getString("query")
            if (url.toString().startsWith("http")) {
                TabInfo.addTab(url.toString())
                intent.removeExtra("query")
            }
            else {
                TabInfo.addTab(externalUrl.toString())
            }
        }
,

检查以下代码片段的详细信息

注意:

  1. 错误处理和数据空检查可以分开处理。
  2. 假设成功案例。
    val URL_FINDER_REGEX = "((http:\\/\\/|https:\\/\\/|ftp:\\/\\/|file:\\/\\/)?(www.)?(([a-zA-Z0-9-]){2,2083}\\.){1,4}([a-zA-Z]){2,6}(\\/(([a-zA-Z-_\\/\\.0-9#:?=&;,]){0,2083})?){0,2083}?[^ \\n]*)"
    
    fun test(intent: Intent?) {

        intent?.let {
            it.extras?.let { extras ->
                val urlQuery = extras.getString("query")
                urlQuery?.let {
                    val links = getUrlsFromText(urlQuery)
                    println(links)
                    // TODO("Your Business logic")
                }
            }
        }
    }

    fun getUrlsFromText(text: String): ArrayList<URI> {

        val availableLinks = ArrayList<URI>()
        val matcher: Matcher = Pattern.compile(URL_FINDER_REGEX,Pattern.CASE_INSENSITIVE).matcher(text)
        while (matcher.find()) {
            try {
                val url = URI(matcher.group())
                availableLinks.add(url)
            } catch (e: Exception) {
                println(e)
            }
        }
        return availableLinks
    }

这类似于一些旧的查询。

参考

  1. Regular expression to find URLs within a string
  2. Detect and extract url from a string?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...