我有一个实现文件上传服务的类。 Activites 绑定(bind)到它并为它提供要上传的文件列表,然后立即解除绑定(bind)。然后,服务在后台线程 (asynctask) 中一个一个地上传文件。
我使用 startService() 在我的仪表板 actvity 中启动此服务,以便它一直运行,直到专门调用 stopService()。
现在,我的问题是什么时候停止该服务?
基本上我需要检查两个条件:1:所有文件都已上传; 2:应用程序已退出。 此外,要退出应用程序,用户必须在仪表板 Activity 上按返回按钮。
我本可以覆盖后退按钮按下并查询服务是否还有任何文件,但我不想使用该方法。
有什么建议吗?
最佳答案
Activites bind to it and supply it a list of files to be uploaded, and then unbind immediately.
然后我建议使用 startService()
而不是 bindService()
。
The files are then uploaded one-by-one by the service in a background thread(asynctask).
这似乎更适合 startService()
和 IntentService
(或者 a WakefulIntentService
,如果您担心设备在上传期间睡着了) .
I start this service in my dashboard actvity using startService()
如果您使用 startService()
发送工作,则不需要这样做。
so that it keeps running until specifically stopService() is called.
理想情况下,服务会自行关闭,就像 IntentService
那样。毕竟,只有服务知道服务何时完成。
my question is when do I stop this service?
当你没有更多工作要做时。 IntentService
会自动执行此操作。如果您真的想维护自己的线程池来完成工作,那么当您的工作队列为空并且所有线程都已完成时,从服务中调用 stopSelf()
。
Basically I need to check two conditions: 1: all files are uploaded
是的。
2: app has exited
没有。您的 UI 不应该关心服务是否正在运行。该服务应该自行处理。
Also, to exit the App, user has to press back button on dashboard activity.
欢迎用户以他们喜欢的方式离开您的应用:返回、主页、最近、通知
、来电等。
Any suggestions?
使用 IntentService
。通过调用 startService()
发送要上传的作业,将所有需要的数据打包到与 startService()
一起使用的 Intent
中(例如,额外)。在 onHandleIntent()
中完成上传工作。如果需要,请使用 LocalBroadcastManager
让您应用中的 Activity 了解上传状态,以便它们可以根据需要在 UI 中反射(reflect)该状态。 IntentService
将在其工作队列为空时自行停止。
关于android - 何时以及如何退出文件上传服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14081823/