如何在不抛出异常的情况下将字符串转换为 URI

How to convert a string to a URI without throwing exceptions

我必须将 Uri 转换为字符串,以便序列化该 Uri。

Intent openFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
openFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
openFileIntent.setType("audio/mpeg");
startActivityForResult(openFileIntent, PICK_MP3_FILE);

...然后 activity 结果...

public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_MP3_FILE)
        {
            if (resultCode == RESULT_OK)
            {
                try
                {
                    if (data != null)
                    {
                        Uri mp3AudioFile;
                        if ((mp3AudioFile = data.getData()) != null)
                        {
                            myObject.setMp3Path(mp3AudioFile.getPath());
                            myObject.Save();

                        }
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

我关闭了应用程序并再次打开。当我尝试使用以下命令打开该 Uri 时:

Uri uri = Uri.parse(myObject.getMp3Path();

我收到一个错误:

java.lang.SecurityException: Permission Denial: reading com.android.providers.downloads.DownloadStorageProvider uri content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Faudio.mp3 from pid=601, uid=10107 requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

我的清单具有以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

我们需要提供持久的 Uri 权限。


JAVA

 Intent openFileIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
 openFileIntent.addCategory(Intent.CATEGORY_OPENABLE);
 openFileIntent.setType("audio/mpeg");
 startActivityForResult(openFileIntent, PICK_MP3_FILE);

还有一个值得一提的注意事项,持久权限仅适用于 Intent.ACTION_OPEN_DOCUMENTNOT Intent.ACTION_GET_DOCUMENT 而后者就像是一次性的事情。

To do that I used getPath().

您应该改用 toString()。

 String scheme = uri.toString();

 Uri uri = Uri.parse(scheme);

权限拒绝问题需要在您第一次收到 URI 时处理。

    private val pickImage = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            //  you will get result here in result.data
            val uri = result.data?.data!!
            requireActivity().contentResolver.takePersistableUriPermission(
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
            // Do something else with the URI. E.g, save the URI as a string in the database
        }
    }