Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start an Android activity in Xamarin Forms?

I am trying to view a hosted PDF file with the default Android pdf viewer in my App with the following code

            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);

I have used this code in a Native project, so I know that it works within an Android activity. For Xamarin Forms, is there a way for me to start an Android activity from a content page, and vice versa?

like image 997
jcbrowni Avatar asked Jun 02 '17 22:06

jcbrowni


2 Answers

You can use DependencyService to implement this function:

INativePages in PCL:

 public interface INativePages
{
    void StartActivityInAndroid();
}

Implement the interface in Xamarin.Android:

[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);
        }

    }
}

Start an Android Activity in PCL :

    private void Button_Clicked(object sender, EventArgs e)
    {
        Xamarin.Forms.DependencyService.Register<INativePages>();
        DependencyService.Get<INativePages>().StartAc();
    }
like image 195
York Shen Avatar answered Oct 16 '22 20:10

York Shen


Forms.Context is obsolete now. The workaround is to instantiate the current context in Main activity class of Android project as under:

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity 
{
  public static Xamarin.Forms.Platform.Android.FormsAppCompatActivity Instance { get; private set; }

  protected override void OnCreate(Bundle bundle)
  {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        LoadApplication(new App());
        Instance = this;
  }

And retrieve the local context in your NativePages StartAc() method as under:

public void StartAc()
    {
      var intent = new Intent(MainActivity.Instance, typeof(YourActivity));
      MainActivity.Instance.StartActivity(intent);
    }
like image 29
CloudArch Avatar answered Oct 16 '22 20:10

CloudArch