让系统打开我的应用程序在Xamarin中创建的文件

时间:2018-10-25 10:03:08

标签: xamarin xamarin.forms

我的应用基于现有数据创建文件。有时是.pdf,有时是.doc。我想允许用户使用他想使用的任何应用程序打开文件。

是否可以使用Xamarin.forms跨平台打开文件?

1 个答案:

答案 0 :(得分:0)

您将需要创建自定义平台代码以启用Share功能。

我在GitHub的https://github.com/Depechie/XamarinFormsOffice上有一个示例,但是从本质上讲,您需要在项目中使用以下平台代码。

这里是Android版之一

   public class ShareService : IShare
    {
        public void Share(string filePath)
        {
            Java.IO.File file = new Java.IO.File(filePath);

            Intent intent = new Intent(Intent.ActionView);
            string mimeType = string.Empty;

            if (Path.GetExtension(filePath).ToLower() == ".pdf")
                mimeType = "application/pdf";
            else if (Path.GetExtension(filePath).ToLower() == ".doc")
                mimeType = "application/msword";
            else if (Path.GetExtension(filePath).ToLower() == ".docx")
                mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            else if (Path.GetExtension(filePath).ToLower() == ".xls")
                mimeType = "application/vnd.ms-excel";
            else if (Path.GetExtension(filePath).ToLower() == ".xlsx")
                mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            else if (Path.GetExtension(filePath).ToLower() == ".ppt")
                mimeType = "application/vnd.ms-powerpoint";
            else if (Path.GetExtension(filePath).ToLower() == ".jpg")
                mimeType = "image/jpeg";

            var t = Uri.FromFile(file);
            intent.SetDataAndType(t, mimeType);

            intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
            this.StartActivity(intent);
        }
    }

    public static class ObjectExtensions
    {
        public static void StartActivity(this object o, Intent intent)
        {
            var context = o as Context;
            if (context != null)
                context.StartActivity(intent);
            else
            {
                intent.SetFlags(ActivityFlags.NewTask);
                Application.Context.StartActivity(intent);
            }
        }
    }

这是一个iOS版

   public class ShareService : IShare
    {
        private UIDocumentInteractionController _controller;

        public void Share(string filePath)
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                _controller = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath));
                _controller.Name = Path.GetFileName(filePath);
                var window = UIApplication.SharedApplication.KeyWindow;
                var subviews = window.Subviews;
                var view = subviews.Last();
                var frame = view.Frame;
                frame = new CGRect((float)Math.Min(10, frame.Width), (float)frame.Bottom, 0, 0);
                _controller.PresentOptionsMenu(frame, view, true);
            });            
        }
    }