2017-06-02 62 views
1

我想查看與默認的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活動,反之亦然?

回答

4

您可以使用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(); 
    } 
0

在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的注入框架來自動創建這些特定於平臺的實現,如果您經常發現這些實現,我建議您查看它。