Execute long running operations on the service

旧时模样 提交于 2019-11-28 10:08:14

问题


I'm building an application which have a Service. I know that all application components run in the same UI process, at least you specify it in the manifest. So to avoid ANR's messages i have three ways.

  1. Specify the service in the manifest to run in a separate process like android:process=":remote" but i've read some StackOverflow's post that
    says that it's not a good idea, because it consume a lot of battery and cpu processing. That i really respect since those post are from trusted people.

  2. Use an IntentService. it's probably a good way out. but i need my service running even if the activity isn't visible. Because i need the service keep checking against a web service for new messages from other users and notify thru Notification. Could it be posible using a an IntentService? is that an ellegant solution.

  3. Use a local service. just removing the android:process=":remote" attribute from the manifest file. But i get some ...OnMainThreadException errors. it means that i need to create an special thread to execute those long running operations or use AsyncTask,

maybe there are another ways to do it. please let me know, how to execute long runnig operations on the service. is really imperative.

thanks.


回答1:


First of all, let's accept that there 2 parts: an active part (the networking) and some sleeping part before the next active part. I think you can use a plain local IntentService for active parts. Each active part on its completion should reschedule the next active part using AlarmManager. This approach makes sure your app does not consume resources during sleeping parts. You are right - once the IntentService gets a result to be presented to user it can use Notification.




回答2:


Android Service executing in UI thread. So you should use AsyncTask or another way to work with threads for network requests.



来源:https://stackoverflow.com/questions/14760507/execute-long-running-operations-on-the-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!