0
服务是否有可能成为SensorEventListener?Android服务是否也可以接收SensorEvent?
我想要做的是有一个后台服务运行,当传感器值发生变化时会执行某些操作。我能够看到说服务启动和停止的Toast消息,但是当我认为传感器值发生变化时,我不知道传感器被激活。
这是我有:
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();
}
}
如果你想接收事件,你应该['mSensorManager.registerListener(this ...'](http://www.vogella.com/articles/AndroidSensor/article.html#accelerometer)在某处.. – zapl
@ zapl这正是我需要的!谢谢! – JTate