How to properly manage contexts for an Android application (inactive classes)

Related posts that do not have the answer I'm looking for.

Using application context everywhere?

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

A static way to get "Context" on Android?

What is the difference between the various methods for obtaining context?

Description of the problem:

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

I think in most cases I would like to avoid singles. If it is not absolutely necessary, I will go with the single. This was resolved and published on one of the links. I personally consider them an ati-model. Just a personal choice. I understand that your application context is, by definition, a singleton object. For each application context, there is only one application. I am open to go with the option described above if this is the only way.

Question:

How my utility classes access my application context, so I can just create a new MyContext (). This context should have a link to application resources. I think this is called applicationContext () when called from an action. Ideally, this would be a cheap operation.

Thanks.

Edit: (lightening) I am writing a service to which the application is bound. I think this should not affect the answer. Thanks again.

+4
source share
1 answer

I would think that the safest way to do this is to pass a context instance to every function that needs access to resources, etc. This is apparently the usual practice used by the API. I was really confused by why so many functions seemed to require an instance of context until it worked out.

0
source

Source: https://habr.com/ru/post/1387063/


All Articles