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?
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();
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With