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?
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.
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.
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.
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.
using Android.Content;
included at the top.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();
}
}
}
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