Services简介,翻译自官方文档

原文:http://developer.android.com/guide/components/services.html

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

 Service 是一个应用程序组件,可以在后台进行长时间运行的操作,不提供用户界面。另一个应用程序组件可以启动一个服务,它将继续在后台运行,即使在用户切换到另一个应用程序。此外,一个组件可以绑定到一个Service来与之交互, 甚至执行进程间通信(IPC)。例如,一个服务可能处理网络交易,播放音乐,执行文件I / O,或与一个内容提供者,所有的背景。

 A service can essentiallytake two forms:

一个服务基本上可以采取两种形式:

Started

A service is "started" when anapplication component (such as an activity) starts it by calling startService(). Once started, a service can run in thebackground indefinitely, even if the component that started it is destroyed.Usually, a started service performs a single operation and does not return aresult to the caller. For example, it might download or upload a file over thenetwork. When the operation is done, the service should stop itself.

一个Service处于“started”,让一个application组件(比如Activity)调用startService()。Service一旦开始,Service可以在后台运行下去,即使组件,开始它被摧毁。通常,一个开始服务执行一个操作,不返回结果给调用者。例如,它可能下载或上传一个文件通过网络。操作完成后,服务应该停止本身。

Bound 

A service is "bound" when anapplication component binds to it by calling bindService(). A bound service offers a client-serverinterface 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 isbound to it. Multiple components can bind to the service at once, but when allof them unbind, the service is destroyed.

Bound

Service是“Bound”当一个应用程序组件绑定到它通过调用bindService()。一个绑定Service提供了一个客户端-服务器接口,允许组件与Service交互,发送请求,得到结果,甚至这样做跨进程与进程间通信(IPC)。一个绑定服务仅运行只要另一个应用程序组件绑定到它。多个组件可以绑定到服务在一次,但是当他们解开,服务被摧毁。

Although this documentationgenerally discusses these two types of services separately, your service canwork 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.

虽然这个文档通常讨论了这两种类型的服务,另外,您的服务可以工作两个方面,它可以启动(不确定地运行),也允许绑定。这是一个简单的事你是否实现几回调方法:onStartCommand()允许组件来启动它和onBind()允许绑定。

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

无论您的应用程序已启动,绑定,或者两者兼有,任何应用程序组件可以使用服务(甚至从一个单独的应用程序),以同样的方式,任何组件都可以使用一个Activity启动通过Intent<http://developer.android.com/reference/android/content/Intent.html >。然而,您可以声明为私有的service,在manifest文件,并从其他应用程序屏蔽。这是一节中讨论更多关于申报服务清单中的<http://developer.android.com/guide/components/services.html >。

Caution: A service runs in the main thread of its hostingprocess—the service does not create its own thread and does not run in a separate process (unless youspecify otherwise). This means that, if your service is going to do any CPUintensive work or blocking operations (such as MP3 playback or networking), youshould create a new thread within the service to do that work. By using aseparate thread, you will reduce the risk of Application Not Responding (ANR)errors and the application's main thread can remain dedicated to userinteraction with your activities.

注意:一个Service运行在主线程的托管进程服务并不创建自己的线程,不运行在单独的进程(除非您指定否则)。这意味着,如果您的service将做一些CPU密集型工作或阻塞操作(如MP3播放或网络),您应该创建一个新线程,在service工作。通过使用一个单独的线程,你会减少应用程序没有响应的风险(ANR)错误和应用程序的主线程可以继续致力于用户交互和你的活动。

The Basics

To create a service, youmust create a subclass of Service (or one of its existing subclasses). In yourimplementation, you need to override some callback methods that handle keyaspects of the service lifecycle and provide a mechanism for components to bindto the service, if appropriate. The most important callback methods you shouldoverride are:

创建一个Service,您必须创建一个子类的Service(或者它的一个现有的子类)。在您的实现,需要覆盖一些回调方法,处理服务生命周期的关键方面,并提供一个机制来将组件绑定到服务,如果适当的。最重要的回调方法你应该覆盖:

onStartCommand()

The system calls this method when anothercomponent, such as an activity, requests that the service be started, bycallingstartService(). Once this method executes, the service isstarted and can run in the background indefinitely. If you implement this, itis your responsibility to stop the service when its work is done, by calling stopSelf() orstopService(). (If you only want to provide binding, youdon't need to implement this method.)

onStartCommand()

系统调用这个方法在另一个组件中,比如一个Activity,要求服务开始,通过调用startService()<http://developer.android.com/reference/android/content/Context.html >。 一旦这个方法执行,服务启动,可以在后台运行下去。如果你实现这个,你有责任停止服务当此项工作完成,通过调用stopSelf()<http://developer.android.com/reference/android/app/Service.html >orstopService()<http://developer.android.com/reference/android/content/Context.html >。 (如果你只是想提供绑定,您不需要执行这个方法。)

onBind()

The system calls this method when anothercomponent wants to bind with the service (such as to perform RPC), by callingbindService(). In your implementation of this method,you must provide an interface that clients use to communicate with the service,by returning an IBinder. You must always implement this method,but if you don't want to allow binding, then you should return null.

onBind()<http://developer.android.com/reference/android/app/Service.html >

系统调用这个方法当另一个组件想绑定服务(如执行RPC),通过调用bindService()<http://developer.android.com/reference/android/content/Context.html >。在你实现这种方法,您必须提供一个接口,客户端使用与服务,通过返回一个IBinder<http://developer.android.com/reference/android/os/IBinder.html > 你必须实现这个方法,但是如果你不希望允许绑定,那么您应该返回null。

onCreate()

The system calls this method when theservice is first created, to perform one-time setup procedures (before it callseitheronStartCommand() or onBind()). If the service is already running, thismethod is not called.

onCreate()

系统调用这个方法当服务第一次被创建,执行一次性安装程序(在它调用onStartCommand()或onBind())。如果服务已经在运行,这个方法不叫。

onDestroy()

The system calls this method when theservice is no longer used and is being destroyed. Your service should implementthis to clean up any resources such as threads, registered listeners,receivers, etc. This is the last call the service receives.

onDestroy()

系统调用这个方法当服务已经不再使用,并被摧毁了。你的service应该实现这个清理任何资源例如线程、注册监听器,接收器,等等。这是最后一次通知服务接收到。

If a component starts theservice by calling startService() (which results in a call to onStartCommand()), then the service remains running until it stops itselfwith stopSelf() or another component stops it by callingstopService().

如果一个组件启动服务通过调用由startService()(它导致调用onStartCommand()),然后服务一直运行,直到它停止本身与stopSelf()或另一个组件停止它通过调用stopService()。

If a component calls bindService() to create the service (and onStartCommand() is not called),then the service runs only as long as the component is bound to it. Once theservice is unbound from all clients, the system destroys it.

如果一个组件调用bindService()来创建服务(和onStartCommand()不会被调用),那么该服务仅运行只要组件绑定到它。一旦service从所有的客户端unbound,系统销毁它。

The Android system willforce-stop a service only when memory is low and it must recover systemresources for the activity that has user focus. If the service is bound to anactivity that has user focus, then it's less likely to be killed, and if theservice is declared to run 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 willlower its position in the list of background tasks over time and the servicewill become highly susceptible to killing—if your service is started, then youmust design it to gracefully handle restarts by the system. If the system killsyour 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 thesystem might destroy a service, see the Processes and Threading document.

Android系统将强制停止服务当内存很低的时候,必须恢复系统资源和所有的用户关注的Activity。如果Service被绑定到一个Activity,有用户的焦点,那么它就是不容易被杀死,如果服务是声明在前台运行(稍后讨论),那么它将几乎从未被杀死。否则,如果service是开始,是长期运行的,那么系统会降低它的位置随着时间的后台任务列表和服务将变得非常容易杀死,如果您的服务已经启动,那么你必须设计更优雅地处理由系统重新启动。如果系统杀死你的服务,它重新启动时,只要资源成为再次可用(尽管这也取决于从onStartCommand()的返回值,稍后讨论)。为更多的信息关于当系统可能会销毁一个service,看到流程和线程文档。

In the following sections,you'll see how you can create each type of service and how to use it from otherapplication components.

在下面几节中,您将看到如何创建每个类型的service和如何使用它从其他应用程序组件。

Should you use a service or a thread?

应该使用service还是一个线程

A service is simply a component thatcan run in the background even when the user is not interacting with yourapplication. Thus, you should create a service only if that is what you need.

服务是一个简单的组件,可以在后台运行甚至当用户不与应用程序交互。因此,您应该只创建一个服务,如果是你需要的。

If you need to perform work outside your mainthread, but only while the user is interacting with your application, then youshould probably instead create a new thread and not a service. For example, ifyou want to play some music, but only while your activity is running, you mightcreate a thread in onCreate(), start running it in onStart(), then stop it inonStop(). Also consider usingAsyncTask or HandlerThread, instead of thetraditional Thread class. See the Processes and Threadingdocument for moreinformation about threads.

如果您需要执行工作外你的主线程,但只有在用户与应用程序交互,那么你应该创建一个新的线程,而不是服务。例如,如果你想玩一些音乐,但只有当你的活动正在运行,您可能会创建一个线程在onCreate(),开始运行它在onStart(),然后阻止它在onStop()。也可以考虑使用AsyncTask或HandlerThread,而不是传统的线程类。看到流程和线程文档获取更多信息关于线程。

Remember that if you do use a service,it still runs in your application's main thread by default, so you should stillcreate a new thread within the service if it performs intensive or blockingoperations.

记住,如果你使用一个服务,它仍然运行在应用程序的主线程在默认情况下,你仍然应该创建一个新的线程在服务如果它执行密集或阻塞操作。

Declaring a service in the manifest

Like activities (and othercomponents), you must declare all services in your application's manifest file.

To declare your service, add a <service> element as a child of the <application> element. For example:

如活动(和其他组件),你必须声明所有服务在您的应用程序清单文件。

<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      ...
  </application>
</manifest>

There are other attributesyou can include in the <service> element to define properties such as permissions requiredto start the service and the process in which the service should run. The android:name attribute is the only required attribute—it specifies theclass name of the service. Once you publish your application, you should notchange this name, because if you do, you might break some functionality whereexplicit intents are used to reference your service (read the blog post, Things That Cannot Change).

还有其他属性可以包括在<service>元素定义属性如权限需要启动服务和流程服务应该运行。android:name属性是唯一所需的属性,指定服务的类名。一旦你发布你的应用程序,您不应该改变这个名字,因为如果你这样做,你可能会打破一些功能,显式意图用于参考您的服务(阅读博客,都无法改变)。

See the <service> element reference for more informationabout declaring your service in the manifest.

Just like an activity, a service candefine intent filters that allow other components to invoke the service usingimplicit intents. By declaring intent filters, components from any applicationinstalled on the user's device can potentially start your service if yourservice declares an intent filter that matches the intent another applicationpasses to startService().

见<service >元素引用为更多的信息关于声明你的服务在manifest。

就像一个Activity,一个service可以定义intentfilters,允许其他组件调用service使用隐式Intent。通过声明intent filters,组件从任何应用程序安装在用户的装置,可以开始你的service,如果您的服务声明了一个intentfilters的intent传递给另一个应用程序由startService()。

If you plan on using yourservice only locally (other applications do not use it), then you don't need to(and should not) supply any intent filters. Without any intent filters, youmust start the service using an intent that explicitly names the service class.More information about starting a service is discussed below.

如果你打算使用你的服务只在本地(其他应用程序不使用它),那么你不需要(也不应该)供应intent filters。没有任何intent filters,您必须启动服务使用一个意图,明确名称服务类。更多的信息关于启动一个服务是下面要讨论的。

Additionally, you can ensure that yourservice is private to your application only if you include theandroid:exported attribute and set it to "false". This iseffective even if your service supplies intent filters.

For more information about creatingintent filters for your service, see the Intents and Intent Filters document.

此外,您可以确保您的服务是私人对您的应用程序只有如果你包括android:exported ,将其设置为“false”。这是有效的,即使你的服务供应intentfilters

为更多的信息关于创建意图过滤器为您服务,请参见Intents and Intent Filters 文件。

Creating aStarted Service

创建一个启动的服务

A started service is onethat another component starts by callingstartService(), resulting in a call to the service'sonStartCommand() method.

一开始服务,首先调用另一个组件由startService(),导致调用服务的onStartCommand()方法。

When a service is started,it has a lifecycle that's independent of the component that started it and theservice can run in the background indefinitely, even if the component thatstarted it is destroyed. As such, the service should stop itself when its jobis done by calling stopSelf(), or another component can stop it by calling stopService().

当一个服务启动了,它有一个生命周期,独立的组件,开始它和服务可以在后台运行下去,即使组件,开始它被摧毁。因此,服务应该停止自己的工作是做当它通过调用stopSelf(),或另一个组件可以阻止它通过调用stopService()。

An application componentsuch as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for theservice to use. The service receives this Intent in the onStartCommand() method.

一个应用程序组件如一个Activity可以开始服务通过调用由startService()和通过Intent,指定了服务,包括任何数据服务使用。服务接收到此intent在onStartCommand()方法。

For instance, suppose anactivity needs to save some data to an online database. The activity can starta companion service and deliver it the data to save by passing an intent to startService(). The service receives the intent in onStartCommand(), connects to the Internet and performs the databasetransaction. When the transaction is done, the service stops itself and it isdestroyed.

例如,假设一个Activity需要保存一些数据到一个在线数据库。这个Activity可以开始一个同伴service,并将它保存的数据通过一个intent由startService()。服务接收意图在onStartCommand(),连接到互联网和执行数据库事务。当事务完成,服务停止本身和它被摧毁。

Caution: A services runs in the same process as the application inwhich it is declared and in the main thread of that application, by default.So, if your service performs intensive or blocking operations while the userinteracts with an activity from the same application, the service will slowdown activity performance. To avoid impacting application performance, youshould start a new thread inside the service.

注意:一个服务运行在相同的进程在声明它的应用和在应用程序的主线程,默认情况下。所以,如果你的服务执行密集或阻塞操作,同时在用户与一个活动从相同的应用程序中,服务将减缓活动性能。为了避免影响应用程序的性能,您应该开始一个新的线程内部服务。

Traditionally, there are two classesyou can extend to create a started service:

传统上,有两类可以扩展来创建一个启动服务:

Service

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

服务

这是所有服务的基类。当你扩展这个类,重要的是你创建一个新的线程来做所有的服务的工作,因为服务使用应用程序的主线程,默认情况下,这可能会减缓性能的任何活动应用程序正在运行。

IntentService

This is a subclass of Service that uses aworker thread to handle all start requests, one at a time. This is the bestoption if you don't require that your service handle multiple requestssimultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each startrequest so you can do the background work.

IntentService

这是一个子类的service使用一个线程来处理所有请求开始,每次一个。这是最好的选择,如果你不需要,你的服务同时处理多个请求。所有您需要做的就是实现onHandleIntent(),它接收意图为每个请求开始,这样你就可以做后台工作。

The followingsections describe how you can implement your service using either one for theseclasses.

以下部分描述如何实现你的服务或者使用一个用于这些类。

Extending the IntentService class

继承IntentService

Because most started services don'tneed to handle multiple requests simultaneously (which can actually be adangerous multi-threading scenario), it's probably best if you implement yourservice using the IntentServiceclass.

因为很多开始服务不需要同时处理多个请求(这实际上可以是一个危险的多线程的场景),它可能是最好的如果你实现你的服务使用IntentService类。

The IntentService does thefollowing:

·                       Createsa default worker thread that executes all intents delivered to onStartCommand() separatefrom your application's main thread.

·                       Createsa work queue that passes one intent at a time to your onHandleIntent() implementation,so you never have to worry about multi-threading.

·                       Stopsthe service after all start requests have been handled, so you never have tocall stopSelf().

·                       Providesdefault implementation of onBind() that returnsnull.

·                       Providesa default implementation of onStartCommand() that sendsthe intent to the work queue and then to your onHandleIntent() implementation.

这个IntentService执行以下操作:

创建一个默认的工作线程,执行所有的intent传递给onStartCommand()独立于应用程序的主线程。

创建一个工作队列,通过一个intent,你onHandleIntent()的实现,所以你永远不必担心多线程。

停止服务,当所有的请求都被处理过了。所以你永远不会调用stopSelf()。

提供的默认实现onBind()返回null。

提供了一个默认实现的onStartCommand(),发送Intent到工作队列,然后到你的onHandleIntent()实现。

All this adds up to the fact that allyou need to do is implement onHandleIntent() to do the workprovided by the client. (Though, you also need to provide a small constructorfor the service.)

所有这一切构成了事实,所有您需要做的就是实现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) {
              }
          }
      }
  }
}

 

That's all you need: a constructor andan implementation of onHandleIntent().

If you decide to also override othercallback methods, such as onCreate()onStartCommand(), oronDestroy(), be sure to call thesuper implementation, so that the IntentService can properly handlethe life of the worker thread.

这是你所需要的:一个构造函数和一个实现onHandleIntent()。

如果你决定也覆盖其他的回调方法,如onStartCommand onCreate(),(),或onDestroy(),一定要叫超级实现,这样IntentService可以妥善处理生活的工作线程。

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

例如,onStartCommand()必须返回默认的实现(这是意图如何被送到onHandleIntent()):

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

Besides onHandleIntent(), the onlymethod from which you don't need to call the super class is onBind()(but you only need toimplement that if your service allows binding).

In the next section, you'll see howthe same kind of service is implemented when extending the base Serviceclass, which is a lotmore code, but which might be appropriate if you need to handle simultaneousstart requests.

除了onHandleIntent(),唯一的方法,你不需要调用父类是onBind()(但你只需要实现,如果你的服务允许绑定)。

在下一节中,您将看到如何将同样的服务是实现当扩展基础服务类,它是更多的代码,但这可能是合适的,如果你需要处理并发请求的开始。

Extending the Service class

继承service

As you saw in the previous section,using IntentService makes yourimplementation of a started service very simple. If, however, you require yourservice to perform multi-threading (instead of processing start requeststhrough a work queue), then you can extend the Service class to handle eachintent.

当你看到在前面的部分中,使用IntentService让你实现一个开始服务非常简单。但是,如果你要求你的服务来执行多线程(而不是处理开始请求通过一个工作队列),然后你可以扩展服务类来处理每个意图。

For comparison, the following examplecode is an implementation of the Service class that performsthe exact same work as the example above using IntentService. That is, for eachstart request, it uses a worker thread to perform the job and processes onlyone request at a time.

相比之下,下面的示例代码是一个服务的实现类,执行同样的工作IntentService如上例使用。那是,对于每个请求,它使用一个启动工作线程来执行工作和流程一次只有一个请求。

ublic class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      @Override
      public void handleMessage(Message msg) {
          // 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) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

  @Override
  public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    
    // Get the HandlerThread's Looper and use it for our Handler 
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the
      // start ID so we know which request we're stopping when we finish the job
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);
      
      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }
  
  @Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
  }
}

 As you can see, it's a lot more workthan using IntentService.

正如您可以看到的,这是一个比使用IntentService更多的工作。

 However, because you handle each callto onStartCommand() yourself, you canperform multiple requests simultaneously. That's not what this example does,but if that's what you want, then you can create a new thread for each requestand run them right away (instead of waiting for the previous request tofinish).

然而,由于你处理每次调用onStartCommand()你自己,你可以执行多个请求同时。那不是这个例子并,但如果那是你想要的,然后您可以创建一个新的线程对于每个请求和运行它们马上(而不是等待前面的请求完成)。

 Notice that the onStartCommand() method must return an integer. The integer is a value thatdescribes how the system should continue the service in the event that thesystem 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()方法必须返回一个整数。整数是一个值,描述系统如何应该继续服务时,该系统将它杀死(正如上面所讨论的,默认的实现IntentService处理这个给你,尽管你能够修改它)。返回值从onStartCommand()必须是下列之一常量:

START_NOT_STICKY

If the system kills the service after onStartCommand() returns, do not recreate the service, unless there arepending intents to deliver. This is the safest option to avoid running yourservice when not necessary and when your application can simply restart anyunfinished jobs.

START_NOT_STICKY

如果系统杀死服务onStartCommand后()<http://developer.android.com/reference/android/app/Service.html >,不要重新创建服务,除非有未决的intent传递。 这是最安全的选择,以避免运行您的服务当没有必要的,当你的应用程序可以简单地重新启动任何未完成的工作。

START_STICKY

If the system kills the service after onStartCommand() returns,recreate the service and callonStartCommand(), but do not redeliver the last intent. Instead, the system calls onStartCommand() with a nullintent, unless there were pending intents to start the service, in which case,those intents are delivered. This is suitable for media players (or similarservices) that are not executing commands, but running indefinitely and waitingfor a job.

START_STICKY

如果系统杀死服务onStartCommand后(),重新创建服务和呼叫onStartCommand(),但不要再投递过去的intent。相反,系统调用onStartCommand()和一个空的intent,除非有未决的intent开始服务,在这种情况下,那些意图传递。这是适合媒体播放器(或者类似的服务),不执行命令,但运行下去,等待工作。

START_REDELIVER_INTENT

If the system kills the service after onStartCommand() returns,recreate the service and callonStartCommand() with thelast intent that was delivered to the service. Any pending intents aredelivered in turn. This is suitable for services that are actively performing ajob that should be immediately resumed, such as downloading a file.

START_REDELIVER_INTENT

如果系统杀死服务onStartCommand后(),重新创建服务和调用onStartCommand()和最后一次交付服务的intent。任何悬而未决的intent是依次传递。这种服务,时候积极的工作需要理解恢复,例如下载文件。

For more details about these returnvalues, see the linked reference documentation for each constant.

为更多的细节关于这些返回值,请参阅相关参考文档对于每个常数。

Creating a Bound Service

A bound service is onethat allows application components to bind to it by calling bindService() in order to create a long-standing connection (andgenerally does not allow components to start itby callingstartService()).

一个绑定服务,是一个让应用程序组件绑定到它通过调用bindService()来创建一个长期存在的连接(和一般不允许组件来启动它通过调用由startService())。

You should create a bound service whenyou want to interact with the service from activities and other components inyour application or to expose some of your application's functionality to otherapplications, through interprocess communication (IPC).

你应该创建一个绑定服务,当你想与服务交互从活动和其他组件在应用程序或暴露你的一些应用程序的功能,其他的应用程序,通过进程间通信(IPC)。

To create a bound service, you mustimplement the onBind() callback method toreturn an IBinder that defines theinterface for communication with the service. Other application components canthen callbindService() to retrieve theinterface and begin calling methods on the service. The service lives only toserve the application component that is bound to it, so when there are nocomponents bound to the service, the system destroys it (you do not needto stop a bound service in the way you must when the service is started through onStartCommand()).

创建一个绑定服务,您必须实现onBind()回调方法返回一个IBinder,它定义了接口通信与服务。其他应用程序组件可以调用bindService()来检索界面,开始对服务调用方法。服务只生活服务应用程序组件绑定到它,所以当没有组件绑定到服务,系统销毁它(你不需要停止一个绑定服务在你必须当服务是通过onStartCommand开始())。

To create a bound service, the firstthing you must do is define the interface that specifies how a client cancommunicate with the service. This interface between the service and a clientmust be an implementation ofIBinder and is what yourservice must return from the onBind() callback method. Oncethe client receives theIBinder, it can begininteracting with the service through that interface.

创建一个绑定服务,首先你必须做的是定义接口,指定客户端可以交流与服务。这个接口在服务和客户端必须的一个实现,就是你的服务内部必须返回从onBind()回调方法。一旦客户端收到的内部,它可以进行交互与服务通过接口。

Multiple clients can bind to the service atonce. When a client is done interacting with the service, it callsunbindService() to unbind. Once there are no clients bound to the service, thesystem destroys the service.

Thereare multiple ways to implement a bound service and the implementation is morecomplicated than a started service, so the bound service discussion appears ina separate document about Bound Services.

多个客户端可以同时绑定服务。当客户端与服务进行交互,它调用unbindService()来解开。一旦没有客户绑定到服务,系统销毁服务。

有多种方式来实现绑定服务和实现更复杂的比一开始服务,所以绑定服务讨论出现在一个单独的文档关于绑定服务。

Running aService in the Foreground

A foreground service is a servicethat's considered to be something the user is actively aware of and thus not acandidate for the system to kill when low on memory. A foreground service mustprovide a notification for the status bar, which is placed under the"Ongoing" heading, which means that the notification cannot bedismissed unless the service is either stopped or removed from the foreground.

一个前台服务是一种服务,被认为是一些用户是主动意识到,因此不是一个候选系统杀死当低内存。一个前台服务必须提供一个状态栏通知,这是放置在“持续的”标题,这意味着通知不能被忽略,除非服务要么停止或删除从前台。

For example, a music player that playsmusic from a service should be set to run in the foreground, because the useris explicitly aware of its operation. The notification in the status bar mightindicate the current song and allow the user to launch an activity to interactwith the music player.

例如,一个音乐播放器,播放音乐从服务应该设置为运行在前台,因为用户显式地意识到它的操作。通知在状态栏会显示当前的歌曲和允许用户启动一个活动可以与音乐播放器。

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

请求你的服务运行在前台,叫startForeground()。该方法接受两个参数:一个整数唯一地标识该通知和状态栏的通知。例如:

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 theforeground, call stopForeground(). Thismethod takes a boolean, indicating whether to remove the status barnotification as well. This method does not stop the service. However, if you stopthe service while it's still running in the foreground, then the notificationis also removed.

删除服务从前台,调用stopForeground()。该方法以一个boolean,指示是否要删除状态栏通知一样。这个方法不会停止服务。但是,如果你停止服务虽然它仍然是在前台运行,然后通知也被移除。

 Note: The methods startForeground() and stopForeground() were introduced in Android 2.0 (API Level 5). In order torun your service in the foreground on older versions of the platform, you mustuse the previoussetForeground() method—see the startForeground() documentation for information about how to provide backwardcompatibility.

注意:这个方法startForeground()和()stopForeground介绍了Android2.0(API 5级)。为了运行服务前景在老版本的平台,你必须使用前面的setForeground()方法看到了startForeground()的文档了解如何提供向后兼容性。

 

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值