Note that there are some explanatory texts on larger screens.

plurals
  1. PORunning multiple services
    text
    copied!<p>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:</p> <pre><code>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 &amp; then call stopSelf() to shut service down */ } } </code></pre> <p>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. </p> <p><strong>I need to know if there is a safe way to run more than one service simultaneously within the same application</strong>. 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. </p> <p>Any suggestions on a workaround to this problem are highly appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload