4

Similar posts that do not 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?

Description of problem:

I have a set of utility classes, some of which write files. Others may use databases, etc. The point being that more than one of my utility classes need Contexts. One trivial example is reading from the strings.xml via context.getString(r.strings.id).

I think in most cases I'd like to avoid singletons. Unless absolutely necessary i'll go with a singleton. This has been solved and posted on one of the links. I personally consider them an ati-pattern. Just a personal choice. I understand that your application context by definition is a singleton object. There is only one application for each app-context. I am open to go with the option described above if it is the only way.

Question:

How can my utility classes get acces to my app context such that I can simply do new MyContext(). This context needs to have a reference to the app resources. I think this is called applicationContext() when called from an activity. Ideally this would be a cheap operation.

Thank you.

Edit:(clarification) I'm writing a service that an application is going to bind itself to. I think this should not affect the answer. Thanks again.

Community
  • 1
  • 1
agallego
  • 91
  • 4
  • nice first question. Good explanation, plus shows what you already know. But what are you looking for, if you don't want to use the ApplicationContext()? – Entreco Dec 19 '11 at 23:39
  • 1
    @Entreco: I was hoping there would be an elegant way of doing the same thing. I do want to get the ApplicationContext, and I think that it makes sense to accept a singleton in this case. I actually downloaded the entire android source for Froyo and looked at the way google is handling this problem. It turns out that for all of the classes I've looked at the context is passed around as a parameter, either as an arg. to the Ctor or arg. to the function. More specifically if you look inside the froyo release, under this path packages/apps/Contacts/src/com/android/contacts/util/* – agallego Dec 20 '11 at 15:52

1 Answers1

0

I would think that the safest way to do this would be to pass the context instance into each function that needs access to the resrouces, etc. This seems to be the common practice that's employed by the API. I was actually confused as to why so many functions seemed to have required a context instance until this came up.

pasha
  • 130
  • 3
  • That seems to be a lot of book keeping todo. I'll wait for other answers. Now all the functions/objects that need contexts have an added parameter, either on the constructor or the function itself. – agallego Dec 19 '11 at 18:22