将字符串转换为Uri

Tec*_*boy 160 java string android uri

如何在Java(Android)中将String转换为Uri?即:

String myUrl = "http://stackoverflow.com";
Run Code Online (Sandbox Code Playgroud)

myUri = ???;

cch*_*son 365

您可以使用parse静态方法Uri

Uri myUri = Uri.parse("http://stackoverflow.com")
Run Code Online (Sandbox Code Playgroud)

  • 我试过这个解决方案,但我遇到了问题.首先需要将Uri更改为URI(如果它来自java.net包).其次,它没有"解析"构造函数.你知道我做错了什么吗? (4认同)
  • 有一个`Uri`类,带有`parse`方法http://developer.android.com/reference/android/net/Uri.html.还有一个`URI`类http://developer.android.com/reference/java/net/URI.html没有`parse`方法.所以使用的正确类是"Uri".确保您输入正确 (2认同)
  • @ccheneson 为什么 Uri 应该比 URI 更正确?有了 URI,你就可以使用 `create` 方法。使用起来和 Uri 一样简单。那么你从 Uri 中得到什么好处呢? (2认同)

Jür*_* K. 28

我只是在用这个java.net .您可以在此处执行以下操作:

String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
Run Code Online (Sandbox Code Playgroud)


JSO*_*C11 7

您可以使用Uri.parse()将字符串解析为 Uri,如下所示:

Uri myUri = Uri.parse("http://stackoverflow.com");
Run Code Online (Sandbox Code Playgroud)

以下是如何在隐式意图中使用新创建的 Uri 的示例。在用户手机上的浏览器中查看。

// Creates a new Implicit Intent, passing in our Uri as the second paramater.
Intent webIntent = new Intent(Intent.ACTION_VIEW, myUri);

// Checks to see if there is an Activity capable of handling the intent
if (webIntent.resolveActivity(getPackageManager()) != null){
    startActivity(webIntent);
}
Run Code Online (Sandbox Code Playgroud)

注意: Androids URIUri之间存在差异。


Shu*_*ain 6

import java.net.URI;
Run Code Online (Sandbox Code Playgroud)

以下也适用于我:

URI uri = URI.create("http://stackoverflow.com");
Run Code Online (Sandbox Code Playgroud)

或者

URI uri = new URI("http://stackoverflow.com");
Run Code Online (Sandbox Code Playgroud)


Mid*_*mar 5

如果您使用的是Kotlin和Kotlin android扩展,那么有一种不错的方法。

val uri = myUriString.toUri()
Run Code Online (Sandbox Code Playgroud)

要将Kotlin扩展(KTX)添加到您的项目中,请将以下内容添加到应用模块的build.gradle中

  repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-rc01'
}
Run Code Online (Sandbox Code Playgroud)