C++程序员进军Android系列:Android Service

重要的基础概念

  1. By default, every application runs in its own Linux process. Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications.
  2. Each process has its own virtual machine (VM), so application code runs in isolation from the code of all other applications.
  3. By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only to that user and only to the application itself — although there are ways to export them to other applications as well.原文出处



小结

  • Android的一个进程就有一个虚拟机
  • Android的一个应用分配一个user ID来进行权限的管理,但可以设置两个应用共用一个user ID,但是这样的话,它们会运行在同一个进程空间,只有一个Virtual Machine
  • 一般来说,我们说一个应用就是指一个.apk,但是应该应用可以调用其它Activity和service,Android上还有Task这个概念,可以自己去了解一下



What's service in Android

  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.
  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)
  3. When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread原文出处

小结

  • service不是进程也不是线程,它是Android定义的component,跟Activity、content provider、Broadcast是并列关系的。肤浅的可以看作windows COM。COM就是一个具有特定接口的代码。Service也是实现一定接口的代码,至于这个service怎么运行是另外指定的。例如可以指定在自己的进程也可以在其它的进程启动,但是他们的执行onBind等接口都是在主线程里,因此,耗时的工作请另外开线程执行
  • 绝对不能跟windows的service混为一谈!
  • 关于如何指定服务在哪个进程运行问题
如大为所说,这跟进程外COM和进程内COM是类似的,只不过,Android上面做这样的区别实现非常的容易,只要在AndroidManifest.xml文件里面特定的服务里加上android:process=":remote"属性即可。如下所示:
<service android:name=".Music" android:process=":remote">
......
</service>
在DDMS看系统的进程可见,多了一个remote结尾的进程,如下图:
![](https://www.ccppcoding.com/wp-content/uploads/2011012218000144.jpg)

  • 有service S, application A1和A2,A1 用remote process的方式startService S叫S1吧,A2也用remote process的方式startService S叫S2吧,他们那么是不是S1和S2是不是在同一个进程里面呢?
基于这样的想法,我编写了这样的代码证明了我的猜想S1、S2应该是在同一个进程里面的是对的,因为它们都在主线程执行。而且必须等S1执行完了在可以执行S2,因此S1要做耗时的工作是,必须另外开一个thread来处理,防止阻塞它的组件工作

原文链接: https://www.cnblogs.com/chenyingzhong/archive/2011/01/15/1936286.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/20081

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午9:31
下一篇 2023年2月7日 下午9:31

相关推荐