Auto-initialize your android library

André Tietz
4 min readJun 21, 2016

I’ve been writing a couple of android libraries open and closed source ones. At one point, a library(not all of them, but a few) need a context to initialise, which is not such an easy task to achieve since the first time that the context is available is in the onCreate method of the Application Object. That’s why many libraries have an init method, which you have to call in the applications Application Object. In this article I’ll show you another way of doing it.

So I guess many of you have seen something like this before:

Why is this? Well the libraries have to do some initialisation to be able to run. Here for example Jake Whartons (btw. great) library ThreeTenABP.

The bad thing on this kind of initialisation is, that even if we wouldn’t need to implement a custom Application, we need to do it. Additionally, we should not forget about this, otherwise we’ll run into crashes.

As library developers we have to think of the developers using our libraries as “Users”. As we all know “Users” especially developers are lazy, when it comes to writing lines of code.

That’s why we want to avoid having those initialisations. I found this solution in the firebase-common package, so they’re using it to initialise firebase exactly the same way.

How does it work?

We create an empty ContentProvider, register it in our manifest and don’t expose it to other apps.

What happens on Application start is, that it registers all ContentProviders in the system (calling onCreate). This means that at this point no activity has been started, but we have access to the (Application)Context, where we can initialise our library using this Context.

Let’s jump right into it and create an empty ContentProvider:

As you can see in the onCreate Method we’re able to initialise whatever we need to…

--

--