我正在尝试添加通过其他应用程序共享文件的可能性,但我无法做到。
我有兴趣通过WhatsApp和Telegram做到这一点,但是当我尝试时,它说"未任命格式"或类似的错误。
System.IO.Stream inputStream= data.context.Resources.OpenRawResource(data.context.Resources.GetIdentifier(path, "raw", data.context.ApplicationContext.PackageName));
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.PutExtra(Intent.ExtraStream, ReadFully(inputStream));
sharingIntent.SetType("audio/*");
data.context.StartActivity(Intent.CreateChooser(sharingIntent, "Share..."));
和转换为字节[]
public static byte[] ReadFully(System.IO.Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
谢谢!
我有兴趣通过WhatsApp和Telegram做到这一点,但是当我尝试时,它说"未任命格式"或类似的错误。
从您的代码中,您试图共享一个大字节数组,该数组既不支持也不建议。正确的方法是将音频文件从内部存储复制到外部存储,然后将其分享到其他应用程序:
:protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
//Create a new file in the exteranl storage and copy the file from assets folder to external storage folder
Java.IO.File dstFile = new Java.IO.File(Environment.ExternalStorageDirectory.Path + "/TestSound.mp3");
dstFile.CreateNewFile();
var inputStream = new FileInputStream(Assets.OpenFd("fileName.mp3").FileDescriptor);
var outputStream = new FileOutputStream(dstFile);
CopyFile(inputStream,outputStream);
//to let system scan the audio file and detect it
Intent intent = new Intent(Intent.ActionMediaScannerScanFile);
intent.SetData(Uri.FromFile(dstFile));
this.SendBroadcast(intent);
//share the Uri of the file
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(dstFile));
sharingIntent.SetType("audio/*");
this.StartActivity(Intent.CreateChooser(sharingIntent, "Share..."));
}
public void CopyFile(FileInputStream inputStream,FileOutputStream outputStream)
{
//FileChannel inChannel = new FileInputStream(src).Channel;
FileChannel inChannel = inputStream.Channel;
FileChannel outChannel = outputStream.Channel;
try
{
inChannel.TransferTo(0, inChannel.Size(), outChannel);
}
finally
{
if (inChannel != null)
{
inChannel.Close();
}
if (outChannel != null)
{
outChannel.Close();
}
}
}
更新:
如果音频文件在资源/原始文件夹中,则可以使用以下代码获取FileInputStream:
//My_Heart_Will_Go_On.mp3 in Resources/raw folder
AssetFileDescriptor descripter = this.Resources.OpenRawResourceFd(Resource.Raw.My_Heart_Will_Go_On);
var inputStream = new FileInputStream(descripter.FileDescriptor);
注意:如果Visual Studio未更新Resource.Designer.cs
的CC_1,则可以手动更新Resource.Designer.cs
,如下所示:
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
...
public partial class Raw
{
static Raw()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Raw()
{
}
}
}
重建项目时,部分类Raw
不会被覆盖。