android 官方文档可以看出 service是运行在主线程中的

Note that services, like other application objects,run in the main thread of their hosting process.

  • A Service isnota 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.

  • A Service isnota thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).


    • Started

    • A service is "started" when an application component (such as an activity) starts it by callingstartService(). Once started, a service can run in the backgroundindefinitely(无限的), even if the component that started it is destroyed.Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

    • Bound

    • A service is "bound" when an application component binds to it by callingbindService(). A bound service offers aclient-serverinterface that allows components to interact with the service, send requests, get results, andeven do so across processes with interprocess communication (IPC).A bound service runs only as long as another application component is bound to it.Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

    • Although this documentation generally discusses these two types of services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding(可以同时被两种方法开启). It's simply a matter of whether you implement a couple callback methods: onStartCommand() to allow components to start it and onBind() to allow binding.
      Caution:Aservice runs in the main thread of its hosting process—the service doesnotcreate its own thread and doesnotrun in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
  • service的销毁

    If a component starts the service by callingstartService()(which results in a call toonStartCommand()), then the service remains running untilit stops itself withstopSelf()or another component stops it by callingstopService().(另一个组件调用stopService()也可以停止service)

    If a component callsbindService()to create the service (andonStartCommand()isnotcalled), then the service runs only as long as the component is bound to it.Once the service is unbound fromall clients,the system destroys it.
    销毁时的优先级:

    The Android system will force-stop a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, then it's less likely to be killed, and if the service is declared torun in the foreground(discussed later), then it will almost never be killed. Otherwise, if the service was started and is long-running, then the system will lower its position in the list of background tasks over time and the service will become highly susceptible to killing—if your service is started, then you must design it to gracefully handle restarts by the system. If the system kills your service, it restarts it as soon as resources become available again (though this also depends on the value you return fromonStartCommand(), as discussed later). For more information about when the system might destroy a service, see theProcesses and Threadingdocument.(注:只有当内存所剩无几的时候系统才会强制杀死service,而且service具有优先级,如果所属的activity是正在获取用户焦点则最不容易被杀死,相比下,运行的时间越长的service 最容易被杀死,如果是声明为run in the foreground永远不会被杀死)

    Caution:A services runs in the same process as the application in which it is declared and in the main thread of that application,(service在应用的同一进程,并且运行在主线程中)by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.

    Creating a Started Service

    Extending the IntentService class

    Becausemost started services don't need to handle multiple requests simultaneously(which can actually be a dangerous multi-threading scenario), it's probably best if you implement your service using theIntentServiceclass.(并发性不强的情况下使用,每次只执行一个线程,当一个线程执行完成在执行下一个线程)

    • IntentService

    • This is a subclass ofServicethatuses a worker thread to handle all start requests, one at a time.(每发一个请求就有一个线程来处理)This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implementonHandleIntent(), which receives the intent for each start request so you can do the background work.

    • Notice thatthe onStartCommand() method must return an integer. The integer is a value that describes how the system should continue the service in the event that the system kills it(as discussed above, the default implementation for IntentService handles this for you, though you are able to modify it). The return value from onStartCommand() must be one of the following constants:(onStartCommand()的返回值决定了系统 如何杀死service)
  • Stopping a service

    A started service must manage its own lifecycle. That is, the system does not stop or destroy the service unless it must recover system memory and the service continues to run afteronStartCommand()returns. So,the service must stop itself by callingstopSelf()or another component can stop it by callingstopService().

    Caution:It's important that your application stops its services when it's done working, to avoid wasting system resources and consuming battery power. If necessary, other components can stop the service by callingstopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever received a call toonStartCommand().




更多相关文章

  1. Android Handler线程间通信机制分析
  2. android 多线程下载原理
  3. Android中的线程模型
  4. android 的线程模型和AsyncTask
  5. Android中的多线程之handler
  6. 《第一行代码--Android》读书笔记之多线程与服务
  7. Android异步机制一:使用Thread+Handler实现非UI线程更新UI界面
  8. Android主线程消息循环
  9. android 多任务多线程断点下载

随机推荐

  1. Android(安卓)Studio使用Android(安卓)Bu
  2. android 官方文档阅读记录-多屏幕适配
  3. Android(安卓)网络请求库Retrofit简单使
  4. Android(安卓)9 Pie 兼容性常见问题及注
  5. Android(安卓)VideoView播放视频控制:开始
  6. Binder机制原理学习笔记(4)_ServiceManag
  7. Android(安卓)中Odex文件生成与合并
  8. Android评论布局,针对TextView换行和与其
  9. Android(安卓)system 分区讲解
  10. Android(安卓)AdbCommandRejectedExcepti