Reputation: 468
In my main activity I start a service. In that service, I try to get the sensor manager but I get the following exception
Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference.
The error doesn't occur if I try to get the sensor manager in an activity class, it only happens in service class.
This is my main activity class:
public class MainActivity extends AppCompatActivity
{
GridLayout mainGrid;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, accelerometerBackgroundService.class);
startService(intent);
mainGrid = (GridLayout) findViewById(R.id.mainGrid);
//Set Event
setSingleEvent(mainGrid);
// setToggleEvent(mainGrid);
}
...
}
This is my service class:
public class accelerometerBackgroundService extends Service implements SensorEventListener
{
//We need to log our activity to check what happens
private static final String TAG = "Accelerometer_Activity";
private SensorManager mSensorManager; //defining a sensor manager and the accelerometer
private Sensor accelerometer;
public accelerometerBackgroundService()
{
Log.i(TAG, "GOT HERE 100");
//getting the sensor manager services
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//getting the accelerometer sensor
accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(accelerometer != null)
{
//If accelerometer sensor is available, create a listener
mSensorManager.registerListener(this,mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
else
{
String noAccelError = "This device does not support accelerometer sensor!";
}
}
...
}
I imagine it has to do with the context. I've searched similar questions but didn't help me.
Thank you.
Upvotes: 1
Views: 2063
Reputation: 13019
Since Service
is a subclass of ContextWrapper
which in turn is a subclass of Context
, you don't need to pass a Context
into the constructor of your AccelerometerBackgroundService.
But you can only take advantage of this relationship after the constructor code has been executed. So if you call the Context
method getSystemService()
for example in onCreate()
, then everything should work as desired.
Upvotes: 1
Reputation: 16224
You should move your initialization code inside Service#onCreate()
not in its constructor.
So, override the method onCreate()
of Service
and you can access its Context
.
Furthermore, since the Android framework requires an empty constructor on the Service
you should NOT pass the parameters in the Service
's constructor otherwise a java.lang.InstantiationException
can be thrown.
Upvotes: 2