shadowhorst
shadowhorst

Reputation: 1500

File operations in Android service

Android services might get killed by the operating system at any possible time. There are no guaranteed lifecycle calls like onDestroy() you can rely on. I have to implement a service doing a lot of long running tasks and a bunch of file operations in the background. So my questions are:

I think I won't be the first person having this type of problem/question, but I could not find anything on Google or SO. Thanks in advance.

Upvotes: 0

Views: 372

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006944

Android services might get killed by the operating system at any possible time.

More accurately, Android app processes might get killed by the operating system at any point.

There are no guaranteed lifecycle calls like onDestroy() you can rely on.

Correct. onDestroy() is very likely to be called, but it is not guaranteed.

I have to implement a service doing a lot of long running tasks and a bunch of file operations in the background.

Pretty much any piece of software bigger than "hello, world" fits that description.

Is it generally a good idea to do that in any kind of service?

You do not have much of an option. A service is what is helping to keep your process around when it no longer is in the foreground from a UI standpoint. If you do not use a service, your process lifetime will likely be on the order of minutes, maybe less. With a service, your process lifetime can be hours, though it depends a lot on the device (e.g., amount of system RAM) and user (e.g., how busy the user is and how many other apps want to do background work).

What happens with an open file handle when the process gets killed?

If you have tried writing stuff to the file at about the point of process termination, any bytes not yet handed over to the OS (e.g., buffered in Java) will not be in the file.

Is there a preferred way to achieve this

I have no idea what "this" is.

like using a foreground service?

There are three main patterns for using a foreground service:

  • Brief transactions. K9 Mail, for example, appears to use a foreground service while it is checking for new messages, but only during that short window.

  • User-controlled operations. This is the conventional use case for foreground services. Music players, for example, will usually implement a foreground service for the music playback.

  • "I am going to try to live forever" types of services. That's not especially practical, as foreground services do not live forever. Users also get irritated with foreground services where they do not understand what they are getting as trade-off for the system RAM/CPU consumption and the always-visible notification icon.

Whether any of these patterns fits your project is something you would need to determine for yourself.

Upvotes: 2

Related Questions