android - 何时以及如何退出文件上传服务

标签 android

  1. 我有一个实现文件上传服务的类。 Activites 绑定(bind)到它并为它提供要上传的文件列表,然后立即解除绑定(bind)。然后,服务在后台线程 (asynctask) 中一个一个地上传文件。

  2. 我使用 startService() 在我的仪表板 actvity 中启动此服务,以便它一直运行,直到专门调用 stopService()。

  3. 现在,我的问题是什么时候停止该服务?

基本上我需要检查两个条件: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/

相关文章:

android - 如何使用挂起函数作为参数在 View 模型中初始化流

java - 搜索 View 在 Android 工具栏中无法正常工作

android - 接收从 Google Cloud Messaging 发送的消息 - Android

android - 在 Android 4.0+ 上显示光标而不使用真正的鼠标

android - 带有 fromHtml 的 TextView 中的 <img>

android - 如何将数据从本地服务发送到 ANDROID 中的 Activity

android - 拍摄给定尺寸的照片 Android

android - 我的适配器没有正确更新我的 ListView 选项

android - 致命信号 6 SIGABRT 代码=-6

java - 在/sdcard/Pictures中创建目录