Reputation: 24562
I am getting a message saying FormsContext is obsolete. I saw numerous suggestions on how to fix it but none apply to my case below:
[assembly: Xamarin.Forms.Dependency(typeof(SoundMethods))]
namespace J.Droid
{
public class SoundMethods : ISoundMethods
{
public void IsDeviceSilent()
{
AudioManager am = (AudioManager)Forms.Context.GetSystemService(Context.AudioService);
}
}
}
Can anyone suggest how I can fix this for my example?
Upvotes: 0
Views: 994
Reputation: 1458
I usually use the Plugin.CurrentActivity from James Montemagno.
Nuget: https://www.nuget.org/packages/Plugin.CurrentActivity
Github: https://github.com/jamesmontemagno/CurrentActivityPlugin
You have to initialize the plugin in your AppDelegate OnCreate
:
CrossCurrentActivity.Current.Init(this, bundle);
Then in your services (or in any class in the Android Project) you can get the current context with this:
var context = CrossCurrentActivity.Current.AppContext
Upvotes: 2
Reputation: 2412
You can get the context in your constructor like this:
private Context _context;
public ContentPageRenderer(Context context) : base(context)
{
_context = context;
}
And then access it with the _context
variable.
Upvotes: 1
Reputation: 7179
You can add a method to init and pass the Context from the MainActivity:
static Context _context;
public static void Init(Context context)
{
_context = context;
}
public void IsDeviceSilent()
{
AudioManager am = (AudioManager)_context.GetSystemService(Context.AudioService);
}
then, in MainActivity
SoundMethods.Init(this);
You can read more about in here
Upvotes: 0