[Monodroid] How to load Assets outside of an Activity?
Jonathan Pryor
jpryor at novell.com
Tue Mar 1 10:30:55 EST 2011
On Mar 1, 2011, at 10:11 AM, Amir Waldman wrote:
> That can't be good... What if you were in the middle of editing data? The
> main activity (marked with: MainLauncher = true) holds the entire state of
> the application. How can it kill and recreate itself?
It can and does happen -- just rotate your device and watch the activity get destroyed and recreated. It's trivial to test. :-)
What if you're in the middle of editing? It's up to you to store the data "elsewhere" so that it isn't lost. Might I suggest the Application [0, 1] instance (which _is_ "global" in that there's only one instance ever created for a process), and can be obtained from the Context.ApplicationContext property, though you could add a "hack" to make the Application instance truly global [1].
Furthermore, you should note that in Android the Activity is _not_ the application itself; it's a _screen_ in the app. For example, with "panel"-style apps (the Settings app, the Email app, etc.), each "screen" is usually a separate Activity, and it's common to navigate between the screens by using Activity.StartActivity(), and pressing the Back button will return you to the previously running Activity in an "activity stack" [2].
> Is there an easier way to instantly get a reference to Context? All I want
> is to load an Asset using external code without worrying about it too much.
If you follow the technique in [1], you'll have access to an Application instance from global context (MyApp.Instance), and since Application is a Context subclass, this should work for you.
- Jon
[0] http://docs.monodroid.net/index.aspx?link=T:Android.App.Application
[1] http://docs.monodroid.net/index.aspx?link=T:Android.App.ApplicationAttribute
Note that this can also be placed on a class, and will register the adorned class as the single Application instance to create, e.g.:
[Application]
public class MyApp : Android.App.Application {
// Yes, this is required, though it's one of the few places an (IntPtr) constructor is required.
public MyApp(IntPtr handle)
: base (handle)
{
Instance = this;
}
public static MyApp Instance {get; private set;}
// other members...
}
[2] http://developer.android.com/reference/android/app/Activity.html#StartingActivities
More information about the Monodroid
mailing list