gpt4 book ai didi

android - 如何从文件选择的 Intent 中获取非空数据?

转载 作者:搜寻专家 更新时间:2023-11-01 08:29:35 24 4
gpt4 key购买 nike

我想让用户选择一个音频文件,然后我想获取它的文件路径。但是我有更简单的问题,因为我得到的 Intent 的 Uri 是空的。我怎样才能得到有意义的东西,即非空值?

开始 Intent :

    private void MainActivity_Click1(object sender, System.EventArgs e)
{
//var intent = new Intent();
var intent = new Intent(Intent.ActionPick, Android.Provider.MediaStore.Audio.Media.ExternalContentUri);

intent.SetType("audio/*");
intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(
Intent.CreateChooser(intent, "Select audio file"), SelectAudioCode);
}

并响应选择:

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);

if (resultCode == Result.Ok && requestCode==SelectAudioCode)
{
Android.Net.Uri uri = Intent.Data;
audioFileNameText.Text = uri == null ? "<NULL>" : uri.ToString();
}
}

无论我如何创建 intent(请参阅上面的代码),我总是看到 NULL

更新:如果我使用通过参数传递的Intent,它的Data 属性是null好吧。

最佳答案

I would like to let user select an audio file, and then I would like to get the file path of it. However I have even simpler problem, because Uri of the intent I get is null.

您可以从data.Data 获取内容Uri。但是如果你想从content uri中获取文件路径,你需要将content uri转换为真实路径:

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
string abc= getRealPathFromURI(this,data.Data);
}


public string getRealPathFromURI(Context context, Uri contentUri)
{
ICursor cursor = null;
try
{
string[] proj = { MediaStore.Audio.AudioColumns.Data};
cursor = ContentResolver.Query(contentUri, proj, null, null, null);
int column_index = cursor.GetColumnIndexOrThrow(MediaStore.Audio.AudioColumns.Data);
cursor.MoveToFirst();
return cursor.GetString(column_index);
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
}

解释更新:

Intent.Data 当前使用的 Intent 是启动当前 Activity 的 Intent ,而不是选择器返回的 Intent :

enter image description here

因此,您需要使用选择器 Activity 返回的 intent,而不是使用 Intent.Data,它是 data 参数:

enter image description here

关于android - 如何从文件选择的 Intent 中获取非空数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com