Service中文意思为服务,在android帮助文档中的解释为“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. ”,中文意思大概为:一个服务是应用组成的一部分,它呈现一个程序的意愿或者运行一个不需要向用户交互或者不被其他应用程序所使用的一个长时间运行的操作。
下面了解一下service不是什么:
1.A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
service不是一个单独的进程,service对象本身不能调用使自己运行在自己独有的进程总,它必须被别的所调用,它运行在应用的进程中,并且作为其中的一部分。
2.A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
service不是一个线程,它不是一个方法让自己工作于主线程之外(避免应用程序出现无法响应的错误)
每个Service的调用必须在应用程序中的manifest文件中注册,调用可以使用Context.startService()或者Context.bindService()这两个方法。
两种调用方法的区别简单地总结可以是:
通过startService()方法调用service,service启动会经历onCreate->onStart这两个阶段,service停止的时候直接进入销毁onDestory,如果调用者直接退出(非调用stopService)后,service还将继续运行,知道调用者再次被启动,调用stopService,服务才结束。
通过bindService()方法调用service,service启动只经历onCreate,这时候调用者就和service绑定在一起了,如果调用者退出,服务自动调用unBind->onDestory,结束服务。
关于如果多个方法交叉调用的情况,符合这样的结果,如果在一个命令所做的部分已,则完成剩下的结果,但是如果只要调用了onBind,就不能使用stopService结束服务了。这里留给大家依次列举可能的情况。
主activity程序源码: