How do I get context in this case?

I need to create a Sensor Manager class on top of sensors like accelerometer , compass , etc. This project will be a class library project that will be referenced and used in other Android projects that need data from the device’s sensor. The problem is that to play with devices like accelerometer and compass in my Sensor Manager class, I need Context . I cannot figure out how I can access the current context in this scenario.

Should I ask callers / users of my Sensor Manager to pass Context in some method parameter? What if more than one class or activity uses my sensor manager? In fact, I would use only one Context, will this cause problems?

or is there a simple, safe and reliable way to get the current application context?

Update

This is my current design ...

I implemented a singleton for the SensorManager as well as for each device inside the SensorManager. So, for example, in SensorManager there will be only one instance of the accelerometer. Caller will receive the SensorManager, and then call the RegisterForAccelerometer method. As a result, whenever the Accelerometer coordinates inside the Accelerometer SensorManager instance are updated, all registered subscribers will be notified. Now the problem arises when I try to start listening to the coordinates of the accelerometer the first time I need context.

0
android android-context
Aug 22 '11 at 11:27
source share
2 answers

One context will not be enough for you. Depending on your implementation and needs, you may want to save contexts on the map or use it only for a specific action, so this will affect the method and time it takes for this context to pass.

I could roughly say that if you use it to create a new object that will use the context, or if you have a singleton, ask for the context in this call, if you create multiple instances of your class, pass it in the / factory constructor.

+1
Aug 22 2018-11-11T00:
source share

In my opinion, you should pass the context this particular Activity that uses these devices. I assume that you are not doing these Singleton classes.

Also, if you want to make the class like Singleton , I think you can pass the Application context , not the Activity context , but I'm not sure if this will work.

Update:

See this section of Application http://developer.android.com/reference/android/app/Application.html .

Typically, there is no need for a subclass of Application. In most cases, static singletones can provide the same functionality in a more modular way. If your singleton needs a global context (for example, to register broadcast receivers), a function can be provided to receive it. A Context that internally uses Context.getApplicationContext () when constructing a singleton for the first time.

So, no matter in what form you will pass, you will pass this Application context

0
Aug 22 2018-11-11T00:
source share



All Articles