Search This Blog

Showing posts with label singleton. Show all posts
Showing posts with label singleton. Show all posts

28 May 2010

Singleton, Lifecycles and the Application class

Start by creating a basic app:
F:\work> mvn archetype:generate -DarchetypeCatalog=http://kallisti.eoti.org:8081/content/repositories/snapshots/archetype-catalog.xml

Choose the galatea-archetype plugin
groupId: org.eoti.android
artifactId: ApplicationTest
version: 1.0-SNAPSHOT
package: org.eoti.android

Make sure you have your emulator running and:
F:\work> cd ApplicationTest
F:\work\ApplicationTest> mvn clean install

Create a new class in the same package as your activity... In my case, I created src\main\java\org\eoti\android\MyMainApplication.java

public class MyMainApplication extends Application
{
    private static String TAG = "MyMainApplication";
    private static MyMainApplication singleton;
    public static MyMainApplication getInstance(){return singleton;}
    private int count = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
        Log.i(TAG, "Singleton created");
    }

    public int count(){return count++;}
}

In your AndroidManifest.xml, replace this line:
    <application android:icon="@drawable/icon" android:label="@string/app_name"> 
with this line:
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:name="MyMainApplication">


Open your activity (src\main\java\org\eoti\android\ApplicationTestActivity in my case)
Add this to the end of your onCreate method:
        Log.i(TAG, "Created instance#" + MyMainApplication.getInstance().count());

Redeploy (mvn clean install) and watch the logs (adb logcat) as you launch the app.
  • You'll see that the singleton is created and the counter is reported.
  • Hit the back button and relaunch the app a few times.  
  • You'll see that the counter increments each time.
  • Hit the home button. 
  • Now, hold down the home button and reselect your app.  
  • You'll notice it is started again, but NOT created again (no counter reported).