问题
I need to set a FileObserver on a directory. The observation period is linked to a long running activity, long running because it has a ViewPager with a lot of pages. Instead of placing the FileObserver inside the activity, I was thinking of putting it inside a service. Now I am wondering would I use IntentService or should I roll out my own implementation of Service? My real concern is that I do not want the service to stop until I explicitly call stopService(intent). But I understand that IntentService stops itself. So how would an IntentService stopping itself affect the life of my FileObserver? Very importantly, I want to start observing the moment my activity starts to when my activity is destroyed.
So I suppose an important question is: Is it necessary at all to place my FileObserver in a Service, since I plan to startWatching in onCreate and stopWatching in onDestroy of my Activity?
update
I am using the FileObserver to remove the files from the directory being observed to put them in another directory. Actually before putting in the new directory I resize by about a factor of 20. So all that needs to happing in the onEvent
method of the FileObserver, which is why I am thinking a service with an independent thread is important. And I need to observe for about 3 hours at a time.
回答1:
Is it necessary at all to place my FileObserver in a Service, since I plan to startWatching in onCreate and stopWatching in onDestroy of my Activity?
No.
That being said...
would I use IntentService
No.
or should I roll out my own implementation of Service?
Yes.
My real concern is that I do not want the service to stop until I explicitly call stopService(intent).
This is why you would not use IntentService
, as it stops itself when onHandleIntent()
returns.
So how would an IntentService stopping itself affect the life of my FileObserver?
That depends on what you are doing with the FileObserver
with respect to the IntentService
lifecycle. Either:
You are removing the
FileObserver
at the end ofonHandleIntent()
, in which case you won't be observing files for very longYou are removing the
FileObserver
inonDestroy()
, in which case you won't be observing files for very long, as the service will be destroyed shortly afteronHandleIntent()
returnsYou are not removing the
FileObserver
at all, which is a bug in your app
Very importantly, I want to start observing the moment my activity starts to when my activity is destroyed.
Then have the FileObserver
in the activity.
来源:https://stackoverflow.com/questions/34663840/is-intentservice-appropriate-for-fileobserver