WEB开发网
开发学院手机开发Android 开发 android之service的用途 阅读

android之service的用途

 2010-09-15 00:08:00 来源:WEB开发网   
核心提示:1. This presents a problem when the response to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away f

1. This presents a problem when the response to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away from the main thread where other components of the user interface run. If onReceive() spawns the thread and then returns, the entire process, including the new thread, is judged to be inactive (unless other application components are active in the process), putting it in jeopardy of being killed. The solution to this problem is for onReceive() to start a service and let the service do the job, so the system knows that there is still active work being done in the process.

就是说broadcast的OnReceive得到响应时,一般在主线程里,如果OnReceive需要执行很耗时的任务,则需要在内部创建一个线程,否则会阻塞UI响应;但如果进程中没有任何活动的组件,虽然OnReceive内创建线程在执行中,却依然被判为非激活状态,仍然会被系统作为“kill” 的对象。

2.Because a process running a service is ranked higher than one with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply spawn a thread — particularly if the operation will likely outlast the activity. Examples of this are playing music in the background and uploading a picture taken by the camera to a web site. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. As noted in the Broadcast receiver lifecycle section earlier, this is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread.

即,包含一个执行任务的服务的进程,相对于后台活动的进程来说,其排名靠前(后被杀死)。那么,如果有繁重的任务需要执行的话,启用一个服务比启用一个线程能保证让该活动生命更持久。比如,后台播放音乐,把相机拍摄的相片上传到网页均可以采用service方式。

Tags:android service 用途

编辑录入:coldstar [复制链接] [打 印]
赞助商链接