在以Android 10/11为目标并使用范围存储的情况下,在文件系统上的任何位置向文件添加应用内快捷方式是否可以!

问题描述

我想让用户在其文件系统(理想的任何类型)上选择一个文件,无论是内部存储器,外部sd卡还是云服务(使用filechooser)

我知道,有了范围存储,应用程序将无法再从非特定于应用程序的目录中读写。我以为我会做的是让用户选择文件,读取文件,然后将其复制到我的应用程序作用域存储(context.filesDir()?)。

我已经尝试了几个小时,以从用户选择的文件获取创建的File对象的绝对路径,但是它从未起作用。这是我的一些代码

val chooserIntent = Intent.createChooser(Intent().setType("*/*").setAction(Intent.ACTION_GET_CONTENT),getString(R.string.select_files_or_documents_you_wish_to_pin))
    try {
        startActivityForResult(chooserIntent,REQUEST_CODE_DESTINATION_PIN_FILE_CHOOSER)
    } catch (e: ActivityNotFoundException) {
        Toast.makeText(activity,activity?.getString(R.string.no_file_chooser_client_installed),Toast.LENGTH_SHORT).show()
    }

override fun onActivityResult(requestCode: Int,resultCode: Int,intent: Intent?) {
    super.onActivityResult(requestCode,resultCode,intent)
    if (requestCode == REQUEST_CODE_DESTINATION_PIN_FILE_CHOOSER)
        uriOfSelectedFile = intent?.data.path
}

然后在查阅文件时:

val intent = Intent(Intent.ACTION_VIEW)
            activity?.application?.let { application ->
                intent.setDataAndType(uriOfSelectedFile,uriOfSelectedFile.mimeType(application))
                startActivity(intent)
            }

为了获得创建存在的File()的绝对路径,我尝试了许多方法。 当我使用清单标志requestLegacyExternalStorage = true,读取/写入外部存储权限等时,所有这些。

我使用以下代码无济于事

public String getPath(Uri uri) {

String path = null;
String[] projection = { MediaStore.Files.FileColumns.DATA };
Cursor cursor = getContentResolver().query(uri,projection,null,null);

if(cursor == null){
    path = uri.getPath()
}
else{
    cursor.movetoFirst();
    int column_index = cursor.getColumnIndexOrThrow(projection[0]);
    path = cursor.getString(column_index);
    cursor.close();
}

return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);

}

我尝试了许多其他解决方案,以便获得完整的绝对路径以复制文件,但从未成功。现在,我只是放弃了,然后检查所选的URI,以表明该文件位于外部存储上,并且向用户显示失败,表明它是不可能的。

最近有没有人使用MediaStore /范围存储并以Android 10或Android 11为目标?

编辑以得到澄清

  • 我可以创建一个像这样的文件对象val file = File(uri.path)
  • 当我调用file.exists()时,它返回false
  • 当我尝试直接使用文件或Uri打开输入流时,出现NoFileFoundException
  • 对于MediaStore,我也没有尝试投影,_ID和DATA
  • 我想将文件复制到应用程序的目录,即。 context.filesDir

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)