问题
Does anybody know how to get the application context in monodroid (I'm searching for the monodroid implementation of getApplicationContext())? I tried Application.ApplicationContext but it doesn't work. I wrote a class inheriting Application and I want to explicitly cast the ApplicationContext to this type. At this point mono dies with a really unhelpful message on the output:
10-12 11:58:31.045 I/mono ( 1919): Stacktrace:
10-12 11:58:31.045 I/mono ( 1919):
Edit: I want to access it from an Activity
回答1:
In Mono for Android, Java getter/setter methods like getApplicationContext() get translated into properties: ApplicationContext
You don't mention in the question where you're trying to call this from. Is it from inside an activity? If so, try casting the Application property to your custom application class. Something like:
((CustomApplication) Application).DoSomething();
Edit
You should also make sure that your custom application class is decorated with ApplicationAttribute:
[Application(Theme = "@style/ApplicationTheme", Label = "@string/ApplicationName", Icon = "@drawable/icon")]
public class CustomApplication : Application
回答2:
(Disclaimer: I'm a monodroid newbie)
Based on what I can find, there isn't a static context. Instead, the context is a property of your current activity.
Thus, in your current activity, access this.ApplicationContext.
You will need to pass the context via the application stack; which I can anticipate could become cumbersome.
来源:https://stackoverflow.com/questions/7738901/monodroid-getapplicationcontext