JTate
JTate

Reputation: 327

Can Android service also receive SensorEvent?

Is it possible/allowed for a service to also be a SensorEventListener?

What I'm trying to do is have a background service run that does something when the sensor value changes. I am able to see the Toast messages that say the Service starts and stops, but when I would think the sensor value changes, I don't get the toast saying the sensor was activated.

This is what I have:

public class MyService extends Service implements SensorEventListener
{
    private SensorManager mSensorManager;
    private Sensor mSensor;

    public void onCreate()
    {
         Toast.makeText(this,"Service Created", Toast.LENGTH_SHORT).show();
         mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
         mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

    }

    public void onStart(Intent intent, int startId)
    {
        Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
    }
    public void onDestroy() 
    {
         super.onDestroy();
         Toast.makeText(this,"Service DESTROYED!!", Toast.LENGTH_SHORT).show();
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy)
    {
         //do nothing
    }


    public void onSensorChanged(SensorEvent event)
    {
        Toast.makeText(this,"Sensor active", Toast.LENGTH_SHORT).show();
    }
}

Upvotes: 0

Views: 87

Answers (1)

JTate
JTate

Reputation: 327

As mentioned by @zapl in the comments above

If you want to recieve events you should do mSensorManager.registerListener(this...) somewhere.. – zapl

was just the answer that I needed.

Upvotes: 1

Related Questions