android 四大组件之 Service

  前篇介绍了第一个组件activity,用view的方式实现了人机交互,手机接收用户输入的信息,然后执行相关命令,service则是在后台执行相关命令,完成相关工作。A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.这个是google官网上的说明,大概意思是要执行的任务时间比较长,但是又不想用view实现,这个就是service要做的事情。

  service和activity一样,要在AndroidMainfest.xml文件里面注册,和注册activity是一样,不同的是 action和category不需要。

<intent-filter>
<action android:name="android.intent.action.set" />

<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

只要 <service android:name=".CalculateService" />这样就完成了注册,CalculateService是自定义的service的类。

  service不是一个独立的process,是整个application的一部分,同时service也不是一个thread,,所以service只是一个很简单的工作。如何启动一个server?我们通过context.startService()或者是context.bindService()。这二者启动service后作用不相同,通过bindService, service和application是绑在一起了,系统会开始调用 oncreate方法,然后调用onBind()的方法,application结束,service就调用onUnbind-->onDestroyed,这就像结拜兄弟,“不求同时生,只求同时死”。context.startService(),这里service启动后,就和应用程序没有直接关系,就算是应用程序突出了,service依然在后台运行,在service为起来前,系统就先调用了oncreate的方法,然后紧跟着启动onstart()方法。

  

posted @ 2013-04-14 21:41  heavenliu  阅读(107)  评论(0)    收藏  举报