Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Android Context in Xamarin.Forms

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?

like image 219
B Best Avatar asked Jul 05 '17 23:07

B Best


People also ask

How do I get application context in Xamarin?

In Xamarin, this is a static. There is no corresponding static method-or-property in Android's native java - you must have an instance of an application, a context, or an activity, to obtain the application context. Google "stackoverflow get application context", and you will see multiple pages showing ad-hoc ways to create such a static.

What is Xamarin forms in Android?

Xamarin.Forms is a library of APIs that allows developers to build native apps for Android, iOS, and Windows completely in C#. Perhaps the most compelling feature of Xamarin.Forms is its support for native UI - you code the user interface of your application using Xamarin.Forms-specific forms and controls.

How do I get the context of an application in Android?

There is no corresponding static method-or-property in Android's native java - you must have an instance of an application, a context, or an activity, to obtain the application context. Google "stackoverflow get application context", and you will see multiple pages showing ad-hoc ways to create such a static.

What is Xamarin assets in Android?

Xamarin. Android Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data. If you want to access data untouched, Assets are one way to do it.


1 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();
         }  
      }
   }
like image 166
B Best Avatar answered Sep 29 '22 13:09

B Best