简体   繁体   中英

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();
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM