在Xamarin Forms中开始Android活动?

问题描述:

我想查看与默认的Android PDF阅读器托管的PDF文件,在我的应用程序下面的代码在Xamarin Forms中开始Android活动?

  var intent = new Intent(Intent.ActionView); 

      intent.SetDataAndType(Uri.Parse("http://sample/url.pdf"), "application/pdf"); 
      intent.SetFlags(ActivityFlags.ClearTop); 
      Android.Content.Context.StartActivity(intent); 

我用一个本地项目的代码,所以我知道它的Android中活动。对于Xamarin Forms,我有没有办法从内容页面开始Android活动,反之亦然?

您可以使用DependencyService来实现这个功能:

INativePagesPCL:在PCL

[assembly: Xamarin.Forms.Dependency(typeof(NativePages))] 
namespace PivotView.Droid 
{ 
    public class NativePages : INativePages 
    { 
     public NativePages() 
     { 
     } 

     public void StartAc() 
     { 
      var intent = new Intent(Forms.Context, typeof(YourActivity)); 
      Forms.Context.StartActivity(intent); 
     } 

    } 
} 

开始在Android Activity

public interface INativePages 
{ 
    void StartActivityInAndroid(); 
} 

Xamarin.Android实现接口

private void Button_Clicked(object sender, EventArgs e) 
    { 
     Xamarin.Forms.DependencyService.Register<INativePages>(); 
     DependencyService.Get<INativePages>().StartAc(); 
    } 

在Android项目创建此功能的类:

public class PdfLauncher : IPdfLauncher 
{ 
    public void LaunchPdf(string url) 
    { 
     //implementation 
    } 
} 

在便携式项目

public interface IPdfLauncher 
{ 
    void LaunchPdf(string url); 
} 

创建的接口属性添加到您的视图模型,以便可以从调用函数你便携式项目

public IPdfLauncher PdfLauncher {get;set;} 

将接口添加到您的viewmodel构造r并传入你在android主要活动中创建的实例。您现在可以从xforms命令调用android代码,如果您添加了iOS或UWP,则只需在这些项目中实现该接口并在运行时传递它们即可。我使用MVVM的注入框架来自动创建这些特定于平台的实现,如果您经常发现这些实现,我建议您查看它。