独立工作线程还是 IntentService?
我是安卓新手。我一直在阅读有关线程/服务的几篇文章和文档,但我仍然无法弄清楚哪一个是最适合我的应用程序的解决方案,所以我想知道您是否可以给我您的建议。
我的主用户界面应该有“开始”和“停止”按钮。 “start”将创建一个线程,开始将信息(即电池统计信息、RSSI 或其他内容)写入文件。按“开始”后,我将切换到其他应用程序,因此我的用户界面将处于“已停止”状态(如果我没有误解生命周期)。最终,我将回到我的应用程序,我希望能够停止线程。
对于像下载/上传大文件这样的长时间运行的任务,我读到最合适的方法是使用 IntentService,这样即使应用程序停止(或在内存不足的情况下被销毁),服务也会继续其任务直到完成。由于在我的应用程序中,服务不会自行停止(我希望使用 stopService 命令停止它),服务仍然是继续的最佳方式吗?或者我应该只使用工作线程,因为我的 UI 在正常情况下不太可能被杀死?
您会建议直接写入文件,还是使用 sqlite?
I'm new to Android. I've been reading several posts and documentation about Threads/Services, and I still can't figure out which would be the most suitable solution for my app, so I was wondering if you could give me your advice.
My main UI is supposed to have "start" and "stop" buttons. "start" would create a Thread that starts writing info (i.e battery statistics, RSSI, or whatever) to a file. After pressing "start", I will be switching to other applications, so my UI will be on "Stopped" state (If I didn't misunderstand the life cycle). Eventually, I will come back to my app and I want to be able to stop the thread.
For a long-running task like downloading/upload a large file I read the most suitable way is to have an IntentService, so that even if the application is stopped (or destroyed if not enough memory) the services continues its task until finished. As in my app the service won't stop by itself (I want it to be stopped with a stopService command), is a service still the best way to proceed? or should I just use a worker thread as my UI is not likely to be killed under normal circumstances?
Would you recommend writing directly to a file, or using sqlite?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您所描述的内容类似于
Service
。它独立于活动而工作,但可以在必要时停止。线程或类似 android 的更好解决方案,AsyncTask
,用于不太长的事情,比如下载不太大的文件。至于第二个问题,那就要看情况了。如果您的数据相当复杂,内部有关系并且应该以多种方式查询,那么 sqlite 是正确的选择。否则,您可以简单地将数据写入文件。
What you described is looks like
Service
. It works independently of activity, but can be stopped from it when necessary. Threads or like a better solution from android,AsyncTask
, are used for not so long things, like downloading not a large file.As for the second question, it depends. If you data is rather complicated, has relationships inside and should be queried in several ways, then sqlite is the right choice. Otherwise you can simply write data to the file.