using Android.Content;
using Android.Graphics.Drawables;
using Android.Runtime;
using AndroidX.Annotations;
using AndroidX.Core.Content;
using AndroidApplication = Android.App.Application;
// ReSharper disable once CheckNamespace
namespace System
{
public static class ContextExtensions
{
///
public static TService GetSystemService(this Context context) where TService : class, IJavaObject
{
var type = typeof(TService);
var cls = Java.Lang.Class.FromType(type);
var service = ContextCompat.GetSystemService(context, cls).JavaCast();
if (service == null)
throw new NullReferenceException(
$"ContextCompat.GetSystemService return null, type: {type}");
return service;
}
///
public static TService GetSystemService(this Context context, string name) where TService : class, IJavaObject
{
var service = context.GetSystemService(name)?.JavaCast();
if (service == null)
throw new NullReferenceException(
$"Context.GetSystemService return null, name: {name}");
return service;
}
///
/// Return the context of the single, global Application object of the current process.
///
///
///
public static Context ApplicationContext(this Context? context) => context?.ApplicationContext ?? AndroidApplication.Context;
///
/// Returns a color associated with a particular resource ID.
/// Starting in android.os.Build.VERSION_CODES#M, the returned color will be styled for the specified Context's theme.
/// https://developer.android.google.cn/reference/androidx/core/content/ContextCompat#getColor(android.content.Context,%20int)
///
///
/// The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
///
public static int GetColorCompat(this Context context, [ColorRes] int id)
=> ContextCompat.GetColor(context, id);
///
/// Returns a drawable object associated with a particular resource ID.
/// Starting in Build.VERSION_CODES.LOLLIPOP, the returned drawable will be styled for the specified Context's theme.
/// https://developer.android.google.cn/reference/androidx/core/content/ContextCompat#getDrawable(android.content.Context,%20int)
///
///
/// The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
///
public static Drawable GetDrawableCompat(this Context context, [DrawableRes] int id)
=> ContextCompat.GetDrawable(context, id);
}
}