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.
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.