问题
I have a service started from an Activity, the service is running fine onCreate
, onStartCommand
called properly. In settings-->running app its showing 1 process and 1 service
.
Now when I swipe out my application from apps recent list. The service recreates, In settings-->running app it shows 0 process and 1 service
restarting...
And onCreate
, onStartCommand
, onTaskRemoved
called.
Now the issue is in one app onTaskRemoved
called immediately after swiping app out then onCreate
called, and in other app onTaskRemoved
takes time and called after onCreate
.
Why this different behavior is there ? Any suggestion will help me. Please provide your comments and observations.
08-26 15:43:48.611: D/PassiveService(15359): PASS_IVE, onCreate...
08-26 15:43:48.611: I/PassiveService(15359): PASS_IVE, registerReceivers...
After swipe out
08-26 15:44:05.789: D/PassiveService(15499): PASS_IVE, onCreate...
08-26 15:44:05.809: I/PassiveService(15499): PASS_IVE, registerReceivers...
08-26 15:44:05.839: I/PassiveService(15499): PASS_IVE, onTaskRemoved...
回答1:
Calling onTaskRemoved of the running service(when app gets swiped out from recent apps) will be generally delayed if we are performing any heavy UI related stuff or broadcasting messages to receivers in service.
E.g , Assume you are downloading the file of size 50MB from web server, so from web server everytime you are reading 1024bytes of stream data as buffer and that data you are writing to a file in device.
Meanwhile you are updating the progress to the UI thread which means every KB you are updating to the UI thread, this will cause the application to freeze.
So in between if you swipe-out from recent app list , then the system will try to stop the service but since the service is in-contact with the UI thread, the system will be unable to stop that service, but it will create new service eventhough the old service is not yet stopped.
Once old service finishes the communication with the UI thread then onTaskRemoved() gets called and the old service will be stopped. The new service will be running in the background.
来源:https://stackoverflow.com/questions/32224233/ontaskremoved-called-after-oncreate-in-started-service-on-swipe-out-from-recent