Android Service学习笔记

来源:互联网 发布:2017网络洗脑神曲 编辑:程序博客网 时间:2024/05/16 11:53

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

Service是一种在后台长期运行并且不提供用户界面的应用组件。其它应用组件能启动一个service,而service甚至可以在用户转向另外一个应用时在后台继续运行。此外,一个组件可以绑定到一个service,与service进行交互,甚至执行进程间通信(IPC)。举例来讲,一个service可以在后台处理网络事物、播放音乐、进行文件I/O或与content provider交互。

A service can essentially take two forms:
本质上service有两种形式:

Started(启动)

A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, 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.

一个应用组件可以通过调用startService()启动一个service;一旦启动,服务就可以在后无限期运行,甚至在启动它的组件销毁以后。通常,一个被启动的service执行一个单一的操作,并不会给调用者返回结果。举例来讲,它可以在网络下载或上传文件。当操作完成后,service应当自行停止自己的运行。


Bound(绑定)

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even 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.

应用组件可以通过调用bindService()绑定一个service。绑定的service提供一个客户-服务器接口供组件与service交互:发送请求、获得结果,甚至在进程间使用进程间通信(IPC)进行这些交互。绑定service只能在其它应用组件绑定它时运行。多个组件可以同时绑定该service,当所有这些绑定解绑后,service将被销毁。

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.

实际上,service既可以被启动,同时又被绑定,这取决于你是否实现了回调方法:onStartCommand()和onBind()。
思考: 如果一个service同时被启动和绑定,它的生命周期是怎样的?

Regardless of whether your application is started, bound, or both, any application component can use the service (even from a separate application), in the same way that any component can use an activity—by starting it with an Intent. However, you can declare the service as private, in the manifest file, and block access from other applications. This is discussed more in the section about Declaring the service in the manifest.

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run 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.

注意:服务运行在宿主进程的主线程上下文环境中。

Traditionally, there are two classes you can extend to create a started service:
传统上,为了创建一个启动的service,有两个类你可以继承:

Service
This is the base class for all services. When you extend this class, it's important that you create a new thread in which to do all the service's work, because the service uses your application's main thread, by default, which could slow the performance of any activity your application is running.

这是所有service的基类。


IntentService
This is a subclass of Service that uses 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 implement onHandleIntent(), which receives the intent for each start request so you can do the background work.

这是一个服务的子类,它使用一个工作线程处理所有的启动请求,一次处理一个请求。如果你不需要你的service同时处理多个请求,这是最好的选择。所有需要你做的事情就是实现onHandleIntent(),来接收每个启动请求的Intent,然后你就能做后台工作了。


The IntentService does the following:

  • Creates a default worker thread that executes all intents delivered to onStartCommand() separate from your application's main thread.
  • Creates a work queue that passes one intent at a time to your onHandleIntent() implementation, so you never have to worry about multi-threading.
  • Stops the service after all start requests have been handled, so you never have to call stopSelf().
  • Provides default implementation of onBind() that returns null.
  • Provides a default implementation of onStartCommand() that sends the intent to the work queue and then to your onHandleIntent() implementation.

  • 创建一个默认的工作者线程执行所有提交到onStartCommand()的intent,与应用的主线程分开;
  • 创建一个工作队列,一次传递一个intent到你的onHandleIntent()实现,这样你就不用担心多线程问题;
  • 所有的启动请求都被处理以后停止service,不必再调用stopSelf();
  • 提供一个默认的返回null的onBind()实现;
  • 提供一个默认的onStartCommand()实现,即发送intent到工作队列中,然后到你的onHandleIntent() 的实现。
Here's an example implementation of IntentService:
public class HelloIntentService extends IntentService {  /**    * A constructor is required, and must call the super IntentService(String)   * constructor with a name for the worker thread.   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   * The IntentService calls this method from the default worker thread with   * the intent that started the service. When this method returns, IntentService   * stops the service, as appropriate.   */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }}

If you decide to also override other callback methods, such as onCreate(), onStartCommand(), or onDestroy(), be sure to call the super implementation, so that the IntentService can properly handle the life of the worker thread.

如果你决定重写其它回调方法,如onCreate(), onStartCommand(), 或onDestroy(),确保调用父类实现,以便IntentService可以正确的处理工作线程的生命周期。

For example, onStartCommand() must return the default implementation (which is how the intent gets delivered to onHandleIntent()):

下面是个例子:

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();    return super.onStartCommand(intent,flags,startId);}

Creating a Bound Service
创建绑定service

A bound service is one that allows application components to bind to it by calling bindService() in order to create a long-standing connection (and generally does not allow components to start it by calling startService()).
绑定service允许应用组件调用bindService()进行绑定service,绑定service用来建立长期的连接(通常不允许组件调用startService()启动service)。

You should create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications, through interprocess communication (IPC).
当你想要从activities和应用程序中其它组件,与service进行交互,或者通过进程间通信(IPC)向其它应用暴露你的应用的功能,这时候你当创建绑定service。

To create a bound service, you must implement the onBind() callback method to return an IBinder that defines the interface for communication with the service. Other application components can then call bindService() to retrieve the interface and begin calling methods on the service. The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it (you do not need to stop a bound service in the way you must when the service is started through onStartCommand()).
为了创建绑定service,你必须实现onBind()回调方法并返回IBinder定义与service通信接口。

To create a bound service, the first thing you must do is define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. Once the client receives the IBinder, it can begin interacting with the service through that interface.


Multiple clients can bind to the service at once. When a client is done interacting with the service, it calls unbindService() to unbind. Once there are no clients bound to the service, the system destroys the service.


There are multiple ways to implement a bound service and the implementation is more complicated than a started service, so the bound service discussion appears in a separate document about Bound Services.

Running a Service in the Foreground
在前景中运行service

A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.
前景servive是用户积极意识到的一些东西,因而当手机内存很低时候它不是系统要杀死的候选。前景service必须为状态条提供通知,放置在“正在进行”的标题下, 即通知不能被解除,除非service停止了或者从前景中被删除掉。

For example, a music player that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.


To request that your service run in the foreground, call startForeground(). This method takes two parameters: an integer that uniquely identifies the notification and the Notification for the status bar. For example:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),        System.currentTimeMillis());Intent notificationIntent = new Intent(this, ExampleActivity.class);PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);notification.setLatestEventInfo(this, getText(R.string.notification_title),        getText(R.string.notification_message), pendingIntent);startForeground(ONGOING_NOTIFICATION, notification);
To remove the service from the foreground, call stopForeground(). This method takes a boolean, indicating whether to remove the status bar notification as well. This method does not stop the service. However, if you stop the service while it's still running in the foreground, then the notification is also removed.

Note: The methods startForeground() and stopForeground() were introduced in Android 2.0 (API Level 5). In order to run your service in the foreground on older versions of the platform, you must use the previous setForeground() method—see the startForeground() documentation for information about how to provide backward compatibility.


For more information about notifications, see Creating Status Bar Notifications.

待续...

原创粉丝点击