Home » Android » Accessing Android Context in Xamarin.Forms

Accessing Android Context in Xamarin.Forms

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’ve seen some old solutions to getting the Android Context using Xamarin.Forms. These older solution suggest the use of Xamarin.Forms.Forms.Context but due to the ever changing Xamarin.Forms platform this no longer works.

In my example I have used the DependencyService.Get<Interface>() from my Shared Code project to use a platform specific implementation of the Interface class.

The use of Android Context is needed a ton when using platform specific functionality using Xamarin.Andriod.

So how do we get the global information interface for an Android Context?

How to&Answers:
  1. Go to the class you created in your App.Droid project part of your solution.
  2. Make sure you have using Android.Content; included at the top.
  3. Create a variable to hold the Context and initialize it with Android.App.Application.Context.

That’s it!

using Android.Content;

[assembly: Xamarin.Forms.Dependency(typeof(DroidClass))]
namespace App.Droid
{
   public class DroidClass : Interface
   {
     Context context = Android.App.Application.Context;

     public DroidClass()
     {
        Toast.MakeText(context, "Grabbed Context!", ToastLength.Long).Show();
         }  
      }
   }