I read the whole documentation about AsyncTasks, Services,…
It’s pretty clear what a remote Service is for. But I’m having troubles, getting the benefit of a LocalService? The typical example is ‘playing music’ or downloading a big file. But why should I start a local Service for that?
I made a small Async task, simulating such a task.
AsyncTask<String, Integer, String> async = new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(500);
System.out.println(i);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
return null;
}
};
async.execute("");
Most answer is, that a (Local)Service is for long running activities, that have to run even when the main activity is closed. OK – but I can do this also with an Async task in the Main Activity:
Button btnFinish = (Button) findViewById(R.id.button1);
btnFinish.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Pressing the button calls onDestroy(), but the Async task is still running? So isn’t that the same like starting the AsyncTask from a Service?
//EDIT:
I ran a couple of tests and I’m pretty sure that the Async Task lives as long as the process does. So if I would wrap it into a local Service (common way) – it would also live as long as the process…
So why does everyone use a local Service for tasks such as downloading files, synchronising,…?!
Not without leaking memory. Never leak threads from a component. When an activity is destroyed, ensure all threads started by that activity will be closed quickly.
Correct. However, without a service, the process might live for just a few milliseconds after the user leaves the foreground activity and goes to some other app.
A service is a marker, telling Android “yo! I’m still doing work here, yo!”. This marker cannot keep the process alive indefinitely, but it usually works well for things that will be running on the order of minutes or hours.
The service also has its own lifecycle, independent of activities. For example, if you want to get control every 15 minutes to do some work, the proper solution is to use
AlarmManagerand anIntentService, and there might be no activity of this app around.Because we want it to work properly.