I'm currently building some movement-detection functionality into my application. I haven't found a way of continually monitoring the accelerometer without keeping the phone awake all the time. In trying to overcome this, I currently have a Service implementing SensorEventListener. I can start this service at intervals (using alarm manager), get readings from the device acclerometer, determine if the device is moving, and then shut down the service. Generally, this appears as follows:
public class MyService extends Service implements SensorEventListener {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
/* Register this SensorEventListener with Android sensor service */
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
/* Unregister SensorEventListener */
}
/* SensorEventListener Implementation ************************/
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
/* Receives callback when sensor values change */
@Override
public void onSensorChanged(SensorEvent event) {
/* Determine if moving & then call stopSelf() to shut service down */
}
}
I have a further problem, however, in that my application has a second service which is invoked on a different schedule. As far as I know, both of the services will be run in the same thread, which is not good as they could conflict.
I need to know if there is a safe way to run more than one service simultaneously within the same application. I have considered the use of IntentService instead of the standard Service class. I am aware that these implement their own worker thread for handling invocations. The problem there is that I have no idea how I can implement the type of asynchronous callbacks required by SensorEventListener from within an IntentService. To put it another way, I have no guarantee that a method like onSensorChanged will receive a callback before IntentService completes its work and shuts down.
Any suggestions on a workaround to this problem are highly appreciated.
as they could conflict.
How?
I need to know if there is a safe way to run more than one service simultaneously within the same application
There is no intrinsic problem in having more than one service simultaneously within the same application, any more than there is an intrinsic problem in having more than one activity in the same application.
Any suggestions on a workaround to this problem are highly appreciated.
You have not demonstrated a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With