Xamarin Forms:与其他应用共享媒体





0/5 (0投票)
本文将帮助您开发一个基于 Xamarin.Forms 的应用程序,以便与其他移动应用程序分享媒体文件。
引言
本文提供了一种从 Xamarin.Forms
移动应用程序向其他移动应用程序分享媒体文件的方法。
背景
在继续阅读本文之前,请先了解 Xamarin.Forms
、依赖服务、Xamarin.Android
和 Xamarin.iOS
的一些基本知识。这将有助于您理解项目的流程。
Using the Code
这里,我们将使用两个客户端(Android 和 iOS)。
Xamarin.Portable
我们将使用 DependencyService
为不同的客户端提供不同的实现。以下是使用的 interface
。
public interface IShareImage
{
Task Share(string url);
}
在您的 XAML 页面中,添加以下带有 Command
的 ToolBarItem
var share = new ToolbarItem
{
Text = "Share",
Command = new Command(async () =>
{
try
{
await DependencyService.Get<IShareImage>().Share("Your Media Link");
}
catch (Exception ex)
{
Console.WriteLine(ex);
await DisplayAlert("Error", "Something went wrong.
Please try again later", "OK");
}
})
};
ToolbarItems.Add(share);
Xamarin.Android
对于 Android 实现,首先我们需要将图像临时保存到设备上,然后我们可以使用 Intent 分享它。为了使此流程正常工作,用户需要在移动设备设置中的应用程序信息中允许应用程序的权限。
将图像临时保存到设备上
var path = Android.OS.Environment.GetExternalStoragePublicDirectory("Temp");
if (!File.Exists(path.Path))
{
Directory.CreateDirectory(path.Path);
}
string absPath = path.Path + "tempfile.jpg";
File.WriteAllBytes(absPath, GetBytes(url));
现在创建一个 Intent 来分享图像
var _context = Android.App.Application.Context;
Intent sendIntent = new Intent(global::Android.Content.Intent.ActionSend);
sendIntent.PutExtra(global::Android.Content.Intent.ExtraText, "Application Name");
sendIntent.SetType("image/*");
sendIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + absPath));
_context.StartActivity(Intent.CreateChooser(sendIntent, "Sharing"));
AndroidManifest.XML
为了使其正常工作,我们需要为我们的应用程序允许这些权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
文件提供者访问
如果您的 targetSdkVersion >= 24
,那么我们必须使用 FileProvider
类来授予对特定文件或文件夹的访问权限,以便其他应用程序可以访问它们。有不同的方法可以做到这一点,但这就是我所做的方式。在 MAINACTIVITY.CS 类中添加以下行
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.SetVmPolicy(builder.Build());
Xamarin.iOS
这是 Xamarin.iOS
的 IShareImage
实现。
var imgSource = ImageSource.FromUri(new Uri(url));
var handler = new ImageLoaderSourceHandler();
var uiImage = await handler.LoadImageAsync(imgSource);
var img = NSObject.FromObject(uiImage);
var mess = NSObject.FromObject("App Name");
var activityItems = new[] { mess, img };
var activityController = new UIActivityViewController(activityItems, null);
var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
while (topController.PresentedViewController != null)
{
topController = topController.PresentedViewController;
}
topController.PresentViewController(activityController, true, () => { });
Info.plist
如果您想将媒体/图像保存到您的设备,请不要忘记在 Info.plist
上设置以下 Property
。
Privacy
- Photo Library Additions Usage Description
关注点
通过一些小的修改,这段代码可以被重用于不同的媒体类型,例如 mp3、mp4、文档、pdf 等。