Question

I'm new to the forum and to android development.

I've been trying to get device orientation data but seem to be doing something wrong. I've been following this link's tutorial: http://www.mail-archive.com/android-beginners@googlegroups.com/msg23415.html .

However, the line

sensorManager =  (SensorManager) getSystemService(SENSOR_SERVICE);

gives me an error that SENSOR_SERVICE is not a valid variable, so I found that it is a public static variable of the Context class so I used

sensorManager =  (SensorManager) getSystemService(Context.SENSOR_SERVICE);

this gives me an error that getSystemService(String) is not a method of my current class. I understand now that getSystemService(String) is a method of Context and so my questions are

1) what is the - I presume it's a cast - (SensorManager) doing in front of the method call?

2) do I have to get my current context and run the method on that? if so how?

I'm sure I'm overthinking this but any help and patience is greatly appreciated.

Was it helpful?

Solution

1) what is the - I presume it's a cast - (SensorManager) doing in front of the method call?

That is indeed a cast. It's necessary because getSystemService is declared to return an undifferentiated Object type (even though it obviously returns something more specific).

2) do I have to get my current context and run the method on that? if so how?

In a custom View class, you can use getContext(). If this code is part of another kind of custom class, you can pass the context in the constructor. I recommend using getApplicationContext() when saving the context as a member field, as Activity contexts should be free to be garbage collected if the activity dies from, say, an orientation change to the device.

OTHER TIPS

yes, getSystemService() is a method of Context, to get Context, use either,

getApplicationContext();

or, use your current activity or service, object to get context by:

ThisService.this.getSystemService();

or

ThisActivity.this.getSystemService();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top