Search code examples
androidandroid-intentandroid-2.1-eclair

How to create an intent from an "extends Application" class, context is null


I have a class which extends android.app.Application, which I use to persist global state around my application.

I want to start off a service when my application starts, so inside the constructor of this GlobalState class I try to create an intent and start a service, but I can't create an intent because I can't get hold of Context

public GlobalState() {
    Log.d(this.getClass().getSimpleName(), "Initialise DatabaseManager");
    dbManager = new DatabaseManager(this);

    Log.d(this.getClass().getSimpleName(), "Requesting start up of ContactsUpdater Service");
    Intent i = new Intent(this, ContactsUpdater.class);
    startService(i);
}

I've tried using getApplicationContext(), but this throws a null pointer exception.

java.lang.NullPointerException at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120) at android.content.ComponentName.(ComponentName.java:75) at android.content.Intent.(Intent.java:2551) at com.jameselsey.apps.cercademi.domain.GlobalState.(GlobalState.java:48) at java.lang.Class.newInstanceImpl(Native Method) at java.lang.Class.newInstance(Class.java:1479) at android.app.Instrumentation.newApplication(Instrumentation.java:957) at android.app.Instrumentation.newApplication(Instrumentation.java:942) at android.app.ActivityThread$PackageInfo.makeApplication(ActivityThread.java:518)

I'm confused, I can create the DatabaseManager fine using this..

Any ideas?


Solution

  • For Activity, Service, ContentProvider and Application, you should not do anything in the constructor. The first place you should do work, when you know the object is initialized and ready for use, is onCreate().

    Further, please think again about "I want to start off a service when my application starts." What you code is doing here is trying to start a service when your process happens to start. I really don't think you want that. You want this service to start because you happened to receive a broadcast in the background?

    If you just want to do some first time init, my recommendation is to not use Application at all. Have a singleton that can be retrieved when it is needed. Then your init happens at the point it is actually needed. There is no need for this to be associated with a service; you can just make a thread. The only reason to use a Service is to tell the system "my app is busy doing background work that the user cares about, please try not to kill me."