Search This Blog

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).

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hello,

    Thanks for the tutorial, it is very helpful:) I would like to add a small observation: if you create your "Singleton" class in a package, you have to add the package name in your AndroidManifest class too.
    Such as: android:name="the.package.where.the.class.is.MyMainApplication"

    ReplyDelete
  3. Hi molly, thank you for the feedback.

    You should be able to avoid that by putting a package="the.packager.where.the.class.is" on the manifest -- thus letting the application/activities/services all inherit from it. I think that is also required to publish on the Android Market.

    ReplyDelete