Java – How to properly manage the context of an Android application (non-activity class)

How to properly manage the context of an Android application (non-activity class)… here is a solution to the problem.

How to properly manage the context of an Android application (non-activity class)

Similar posts don’t have the answer I’m looking for.

Using Application context everywhere?

http://developer.android.com/reference/android/app/Application.html

Static way to get ‘Context’ on Android?

What’s the difference between the various methods to get a Context?

Problem description:

I have a set of utility classes, some of which write files. Others may use databases, etc. The point is that more than one of my utility classes requires a Context. A simple example is reading from strings.xml via context.getString(r.strings.id).

I

think in most cases I want to avoid singletons. I’ll choose a singleton unless absolutely necessary. This has been resolved and posted on one of the links. I personally think they are an ati model. Just a personal choice. I understand that your application context is by definition a singleton object. There is only one application per application context. If this is the only way, I am willing to accept the above option.

Question:

How can my

utility class access my application context so that I can simply execute new MyContext(). This context needs to reference an application resource. I think this is called applicationContext() when called from an activity. Ideally, this would be a cheap operation.

Thank you.

Edit: (clarifying).
I’m writing an application that binds itself to a service. I don’t think this should affect the answer. Thanks again.

Solution

I think the safest approach is to pass a context instance to every function that needs to access resources etc. This seems to be a common practice adopted by APIs. Actually, I’m confused as to why so many functions seem to need a context instance until this happens.

Related Problems and Solutions