我应该为我的Android应用程序使用Service还是IntentService吗? [英] Should I use Service or IntentService for my android app?

查看:69
本文介绍了我应该为我的Android应用程序使用Service还是IntentService吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我错了,请纠正我:

Please correct me If I am wrong :

1) Service 用于在后台执行较长的任务.服务在UI线程中运行,因此,如果任务很长,则可能会冻结我们的UI.只要我们告知服务停止,服务就会继续独立于应用程序运行.

1) A Service is used to perform long tasks in background. A service runs in the UI thread so if there comes a long task then it may freeze our UI. A service will continue to run independent of application as long as we tell it to stop.

2)另一方面, IntentService 用于在单独的线程中执行简短的任务.完成任务后,它将自动终止.

2) An IntentService on the other hand is used to perform short tasks in separate thread. It automatically terminates when it finishes its task.

我该怎么做:

1)每5秒检查一次位置

1) check for location every 5 seconds

2)如果位置发生变化,请将其发送到服务器并使用新的位置值更新UI

2) if there is a change in location send it to server and Update the UI with new location values

让我感到困惑的是:

我应该使用 Service 还是 IntentService ,因为我需要在5秒后连续执行操作,并且不希望UI线程变得无响应.

Should I use a Service or IntentService as I need to do it continuously after 5 seconds and does not want my UI thread to become unresponsive.

此应用将用于跟踪车辆.

This app will be used to track a vehicle.

推荐答案

我不会使用 IntentService ,因为一旦工作完成,它便会自动完成,您需要重新安排时间5秒钟后.要重新计划它,您可能需要与应用程序 Context 相关联的一些复杂的外部 Timer 机制,或者更糟糕的是,使用会吸吮的 AlarmManager 你的电池像疯了一样.

I wouldn't use an IntentService because it finishes itself once the job is done and you would need to re-schedule it again after 5 seconds. To re-schedule it you would need either some complicated external Timer mechanism associated with an application Context or, even worse, use AlarmManager that will suck your battery like crazy.

我将使用内部带有 Timer 的服务来每5秒安排 TimerTasks 的时间,并在始终在工作线程上执行的每个 TimerTask 上进行调度我会得到这个职位并提出一个Http请求.

I would use a Service with a Timer inside for scheduling TimerTasks each 5 seconds and on each TimerTask that anyway executes on a worker thread I would get the position and make an Http request.

别忘了在Service的 onDestroy 方法上取消计时器,否则您将泄漏 Service 实例.

Just don't forget to cancel the timer on Service's onDestroy method otherwise you'll leak the Service instance.

编辑我刚刚注意到了这个并使用新的位置值更新UI ...继续使用 Service ,但是要么使用 AsyncTask 发送请求在 doInBackground 中,然后在 onPostExecute 中发送广播消息,要么继续使用相同的 TimerTask 机制,但使用 Handler 可以使用UI Looper实例化,并在该处理程序上发出UI更新请求.

EDIT I just noticed this and Update the UI with new location values ... Keep using the Service, but either use an AsyncTask for sending the request in doInBackground and then send a broadcast message in onPostExecute, either keep using the same TimerTask mechanism but use a Handler that is instantiated with a UI Looper and make UI update requests on that handler.

这篇关于我应该为我的Android应用程序使用Service还是IntentService吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆