I am new to Android. I am developing an application which logs sensor data. I have an activity with two buttons. When the user presses the start button, I want a service to be started and log sensor data until the user presses the stop button. I am not sure which type of service I want to use. I read about local vs remote services but I didn't quite actually understand the difference.
What I tried till now:
I created an activity with two buttons which start and stop a local service:
//Start Service
startService(new Intent(this, MyService.class));
//Stop Service
stopService(new Intent(this, MyService.class));
I also created a sticky service which onStartCommand()
begins to log sensor data:
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, magnetometer,
SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(this, lightSensor,
SensorManager.SENSOR_DELAY_UI);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
AndroidManifest.xml:
<service android:name=".MyService" android:enabled="true" android:process=":HelloSensors_background"/>
It works well, however the problem is that when I kill the application which started the service, this service restarts and loses all the previously logged data. What shall I use in order to have a service which runs smoothly and continue to run even when the application is killed so as not to lose any logged data please?
I think you have to declare the service in the AndroidManifest.xml.
After your clarification regarding the killing:
You probably want to run your
Service
in a different process than yourApplication
, which you can achieve by such a declaration in your manifest:Use the same
android:process
attribute for anyreceiver
declarations in your manifest.If you only want to receive events which can be declared in the manifest, you can consider using an
IntentService
, which will almost never be visible to the user due to its short activity timespan. However, if you need to listen to events which can only be received when you register receivers programmatically (in which case, obviously, thereceiver
clause in the manifest makes no sense) then you cannot do anything against a user (or one of the "smart app killers") killing your service. The advantage, still, would be that users hopefully understand that your app can be killed, while yourService
can't (if they want it to do something).Additionally, you can bring your
Service
to the foreground.