Search code examples
androidinitializationandroid-intentstatic-initializerstatic-initialization

Global initialization in Android


I'm writing some library code distributed as a jar file that developers will need to initialize with an application id before using. Initialization is just a function call, like

MyLibrary.initialize("16ea53b");

The tricky thing is that I am not sure how to instruct developers to make this initialization call. At first I thought a single static initializer block in the main activity would be the easiest way to do it. The problem is a user could enter the application through some other activity or intent, and the main activity would not be loaded. Is there a general way to ensure that a line of code is run at the application's startup regardless of how the application was started?

The initialize call is idempotent so I could just tell people to make this initialization call in every place it could be used, but that would be bothersome.


Solution

  • One easy way is to save something in SharedPrefences when your library code is initialized. And then, wherever you deem important, you can check for this value, and continue if it exists or prompt for initialization or anything (error messages etc). This will also allow your developers to not have to initialize more than once.

    Be sure to provide the developers an API to reset this value.

    Also, here is a good talk on API design that may help you, by Joshua Bloch.