From 9748d76be90a90c112874fc7ce46e5ca279488eb Mon Sep 17 00:00:00 2001 From: George French Date: Wed, 7 Sep 2016 09:59:32 -0700 Subject: [PATCH] docs: Update startService() & bindService() documentation (Proj13) Updated Update startService() and bindService() docs to mention that they no longer support implicit intent. And mentioned that the Intellegent job scheduling is now the preferred method for launching services. We also performed a copy edit, implementing Google styles. Bug: 18333456 Change-Id: I2b2ec666be870aea15045d30fbc822256d1b9a81 --- docs/html/google/play/billing/billing_integrate.jd | 267 ++++++----- docs/html/guide/components/bound-services.jd | 276 ++++++----- docs/html/guide/components/fundamentals.jd | 312 +++++++------ docs/html/guide/components/intents-filters.jd | 292 ++++++------ docs/html/guide/components/services.jd | 517 ++++++++++----------- docs/html/training/articles/security-tips.jd | 470 ++++++++++--------- docs/html/training/location/display-address.jd | 130 +++--- docs/html/training/run-background-service/index.jd | 14 +- 8 files changed, 1202 insertions(+), 1076 deletions(-) diff --git a/docs/html/google/play/billing/billing_integrate.jd b/docs/html/google/play/billing/billing_integrate.jd index 5d6b3a8f2e3f..506a44006bdb 100755 --- a/docs/html/google/play/billing/billing_integrate.jd +++ b/docs/html/google/play/billing/billing_integrate.jd @@ -9,18 +9,18 @@ page.tags="inapp, billing, iap"

In this document

  1. Adding the AIDL file
  2. -
  3. Updating Your Manifest
  4. +
  5. Updating your manifest
  6. Creating a ServiceConnection
  7. -
  8. Making In-app Billing Requests +
  9. Making In-app Billing requests
      -
    1. Querying Items Available for Purchase
    2. -
    3. Purchasing an Item
    4. -
    5. Querying Purchased Items
    6. -
    7. Consuming a Purchase
    8. -
    9. Implementing Subscriptions
    10. +
    11. Querying items available for purchase
    12. +
    13. Purchasing an item
    14. +
    15. Querying purchased items
    16. +
    17. Consuming a purchase
    18. +
    19. Implementing subscriptions
  10. -
  11. Securing Your App +
  12. Securing your app

Reference

    @@ -42,7 +42,7 @@ page.tags="inapp, billing, iap" In-app Billing on Google Play provides a straightforward, simple interface for sending In-app Billing requests and managing In-app Billing transactions using Google Play. The information below covers the basics of how to make - calls from your application to the In-app Billing service using the Version 3 + calls from your application to the In-app Billing service using the In-app Billing Version 3 API.

    @@ -51,26 +51,25 @@ page.tags="inapp, billing, iap" your application, see the Selling In-app Products training class. The training class provides a complete sample In-app Billing - application, including convenience classes to handle key tasks related to - setting up your connection, sending billing requests and processing responses + application, including convenience classes to handle key tasks that are related to + setting up your connection, sending billing requests, processing responses from Google Play, and managing background threading so that you can make In-app Billing calls from your main activity.

    - Before you start, be sure that you read the In-app Billing - Overview to familiarize yourself with concepts that will make it easier + Overview to familiarize yourself with concepts that make it easier for you to implement In-app Billing.

    -

    To implement In-app Billing in your application, you need to do the -following:

    +

    Complete these steps to implement In-app Billing in your application:

    1. Add the In-app Billing library to your project.
    2. Update your {@code AndroidManifest.xml} file.
    3. -
    4. Create a {@code ServiceConnection} and bind it to +
    5. Create a {@code ServiceConnection} and bind it to the {@code IInAppBillingService}.
    6. Send In-app Billing requests from your application to {@code IInAppBillingService}.
    7. @@ -79,55 +78,56 @@ following:

      Adding the AIDL file to your project

      -

      {@code IInAppBillingService.aidl} is an Android Interface Definition +

      The {@code IInAppBillingService.aidl} is an Android Interface Definition Language (AIDL) file that defines the interface to the In-app Billing Version -3 service. You will use this interface to make billing requests by invoking IPC +3 service. You can use this interface to make billing requests by invoking IPC method calls.

      -

      To get the AIDL file:

      + +

      Complete these steps to get the AIDL file:

      1. Open the Android SDK Manager.
      2. In the SDK Manager, expand the {@code Extras} section.
      3. Select Google Play Billing Library.
      4. Click Install packages to complete the download.
      -

      The {@code IInAppBillingService.aidl} file will be installed to {@code /extras/google/play_billing/}.

      +

      The {@code IInAppBillingService.aidl} file will be installed to {@code <sdk>/extras/google/play_billing/}.

      -

      To add the AIDL to your project:

      +

      Complete these steps to add the AIDL to your project:

        -
      1. First, download the Google Play Billing Library to your Android project: +
      2. Download the Google Play Billing Library to your Android project:
        1. Select Tools > Android > SDK Manager.
        2. Under Appearance & Behavior > System Settings > Android SDK, select the SDK Tools tab to select and download Google Play Billing Library.
        -
      3. Next, copy the {@code IInAppBillingService.aidl} file to your project. +
      4. Copy the {@code IInAppBillingService.aidl} file to your project.
          -
        • If you are using Android Studio: +
        • If you are using Android Studio, complete these steps to copy the file:
          1. Navigate to {@code src/main} in the Project tool window.
          2. -
          3. Select File > New > Directory and enter {@code aidl} in the - New Directory window, then select OK. +
          4. Select File > New > Directory, enter {@code aidl} in the + New Directory window, and select OK. -
          5. Select File > New > Package and enter - {@code com.android.vending.billing} in the New Package window, then select +
          6. Select File > New > Package, enter + {@code com.android.vending.billing} in the New Package window, and select OK.
          7. Using your operating system file explorer, navigate to - {@code /extras/google/play_billing/}, copy the + {@code <sdk>/extras/google/play_billing/}, copy the {@code IInAppBillingService.aidl} file, and paste it into the {@code com.android.vending.billing} package in your project.
        • -
        • If you are developing in a non-Android Studio environment: Create the - following directory {@code /src/com/android/vending/billing} and copy the - {@code IInAppBillingService.aidl} file into this directory. Put the AIDL - file into your project and use the Gradle tool to build your project so that - the IInAppBillingService.java file gets generated. +
        • If you are developing in a non-Android Studio environment, create the + following directory: {@code /src/com/android/vending/billing}. Copy the + {@code IInAppBillingService.aidl} file into this directory. Place the AIDL + file in your project and use the Gradle tool to build your project so that + the IInAppBillingService.java file is generated.
      5. @@ -137,16 +137,16 @@ method calls.

      -

      Updating Your App's Manifest

      +

      Updating your app's manifest

      In-app billing relies on the Google Play application, which handles all - communication between your application and the Google Play server. To use the + of the communication between your application and the Google Play server. To use the Google Play application, your application must request the proper permission. You can do this by adding the {@code com.android.vending.BILLING} permission to your AndroidManifest.xml file. If your application does not declare the In-app Billing permission, but attempts to send billing requests, Google Play - will refuse the requests and respond with an error. + refuses the requests and responds with an error.

      @@ -182,7 +182,7 @@ method calls.

      onServiceDisconnected} and {@link android.content.ServiceConnection#onServiceConnected onServiceConnected} methods to get a reference to the {@code IInAppBillingService} instance after - a connection has been established. + a connection is established.

      @@ -208,20 +208,25 @@ ServiceConnection mServiceConn = new ServiceConnection() {
         bindService} method. Pass the method an {@link android.content.Intent} that
         references the In-app Billing service and an instance of the {@link
         android.content.ServiceConnection} that you created, and explicitly set the
      -  Intent's target package name to com.android.vending — the
      +  Intent's target package name to com.android.vending—the
         package name of Google Play app.
       

      Caution: To protect the security of billing transactions, - always make sure to explicitly set the intent's target package name to + always explicitly set the intent's target package name to com.android.vending, using {@link - android.content.Intent#setPackage(java.lang.String) setPackage()} as shown in - the example below. Setting the package name explicitly ensures that + android.content.Intent#setPackage(java.lang.String) setPackage()}. + Setting the package name explicitly ensures that only the Google Play app can handle billing requests from your app, preventing other apps from intercepting those requests.

      +

      + The following code sample demonstrates how to set the intent's target package + to protect the security of transactions: +

      +
      @Override
       public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
      @@ -233,6 +238,13 @@ public void onCreate(Bundle savedInstanceState) {
       }
       
      +

      Caution: To ensure that your app is secure, always use an +explicit intent when starting a {@link android.app.Service} and do not declare intent filters for +your services. Using an implicit intent to start a service is a security hazard because you cannot +be certain of the service that will respond to the intent, and the user cannot see which service +starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call +{@link android.content.Context#bindService bindService()} with an implicit intent.

      +

      You can now use the mService reference to communicate with the Google Play service. @@ -242,10 +254,14 @@ public void onCreate(Bundle savedInstanceState) { Important: Remember to unbind from the In-app Billing service when you are done with your {@link android.app.Activity}. If you don’t unbind, the open service connection could cause your device’s - performance to degrade. This example shows how to perform the unbind + performance to degrade. +

      + +

      + This example shows how to perform the unbind operation on a service connection to In-app Billing called {@code mServiceConn} by overriding the activity’s {@link - android.app.Activity#onDestroy onDestroy} method. + android.app.Activity#onDestroy onDestroy} method:

      @@ -264,29 +280,29 @@ public void onDestroy() {
         "{@docRoot}training/in-app-billing/preparing-iab-app.html">Selling In-app
         Products training class and associated sample.
       

      -

      Making In-app Billing Requests

      +

      Making In-app Billing requests

      - Once your application is connected to Google Play, you can initiate purchase + After your application is connected to Google Play, you can initiate purchase requests for in-app products. Google Play provides a checkout interface for - users to enter their payment method, so your application does not need to + users to enter their payment method, so your application doesn't need to handle payment transactions directly. When an item is purchased, Google Play recognizes that the user has ownership of that item and prevents the user from purchasing another item with the same product ID until it is consumed. - You can control how the item is consumed in your application, and notify + You can control how the item is consumed in your application and notify Google Play to make the item available for purchase again. You can also query - Google Play to quickly retrieve the list of purchases that were made by the - user. This is useful, for example, when you want to restore the user's + Google Play to quickly retrieve the list of purchases that the + user made. This is useful, for example, when you want to restore the user's purchases when your user launches your app.

      -

      Querying for Items Available for Purchase

      +

      Querying for items available for purchase

      In your application, you can query the item details from Google Play using the In-app Billing Version 3 API. To pass a request to the In-app Billing - service, first create a {@link android.os.Bundle} that contains a String + service, create a {@link android.os.Bundle} that contains a String {@link java.util.ArrayList} of product IDs with key "ITEM_ID_LIST", where - each string is a product ID for an purchasable item. + each string is a product ID for an purchasable item. Here is an example:

      @@ -299,9 +315,9 @@ querySkus.putStringArrayList(“ITEM_ID_LIST”, skuList);
       
       

      To retrieve this information from Google Play, call the {@code getSkuDetails} - method on the In-app Billing Version 3 API, and pass the method the In-app + method on the In-app Billing Version 3 API and pass the In-app Billing API version (“3”), the package name of your calling app, the purchase - type (“inapp”), and the {@link android.os.Bundle} that you created. + type (“inapp”), and the {@link android.os.Bundle} that you created, into the method:

      @@ -310,35 +326,35 @@ Bundle skuDetails = mService.getSkuDetails(3,
       

      - If the request is successful, the returned {@link android.os.Bundle}has a + If the request is successful, the returned {@link android.os.Bundle} has a response code of {@code BILLING_RESPONSE_RESULT_OK} (0).

      - Warning: Do not call the {@code getSkuDetails} method on the - main thread. Calling this method triggers a network request which could block + Warning: Don't call the {@code getSkuDetails} method on the + main thread. Calling this method triggers a network request that could block your main thread. Instead, create a separate thread and call the {@code - getSkuDetails} method from inside that thread. + getSkuDetails} method from inside of that thread.

      - To see all the possible response codes from Google Play, see In-app Billing Reference.

      The query results are stored in a String ArrayList with key {@code - DETAILS_LIST}. The purchase information is stored in the String in JSON - format. To see the types of product detail information that are returned, see + DETAILS_LIST}. The purchase information is stored within the String in JSON + format. To view the types of product detail information that are returned, see In-app Billing Reference.

      - In this example, you are retrieving the prices for your in-app items from the - skuDetails {@link android.os.Bundle} returned from the previous code snippet. + In this example shows how to retrieve the prices for your in-app items from the + skuDetails {@link android.os.Bundle} that is returned from the previous code snippet:

      @@ -357,15 +373,15 @@ if (response == 0) {
       }
       
      -

      Purchasing an Item

      +

      Purchasing an item

      To start a purchase request from your app, call the {@code getBuyIntent} - method on the In-app Billing service. Pass in to the method the In-app + method on the In-app Billing service. Pass the In-app Billing API version (“3”), the package name of your calling app, the product ID for the item to purchase, the purchase type (“inapp” or "subs"), and a - {@code developerPayload} String. The {@code developerPayload} String is used + {@code developerPayload} String into the method. The {@code developerPayload} String is used to specify any additional arguments that you want Google Play to send back - along with the purchase information. + along with the purchase information. Here is an example:

      @@ -377,10 +393,13 @@ Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
         If the request is successful, the returned {@link android.os.Bundle} has a
         response code of {@code BILLING_RESPONSE_RESULT_OK} (0) and a {@link
         android.app.PendingIntent} that you can use to start the purchase flow. To
      -  see all the possible response codes from Google Play, see In-app
      -  Billing Reference. Next, extract a {@link android.app.PendingIntent} from
      -  the response {@link android.os.Bundle} with key {@code BUY_INTENT}.
      +  Billing Reference.
      +
      +

      + The next step is to extract a {@link android.app.PendingIntent} from + the response {@link android.os.Bundle} with key {@code BUY_INTENT}, as shown here:

      @@ -390,8 +409,8 @@ PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
       

      To complete the purchase transaction, call the {@link android.app.Activity#startIntentSenderForResult startIntentSenderForResult} - method and use the {@link android.app.PendingIntent} that you created. In - this example, you are using an arbitrary value of 1001 for the request code. + method and use the {@link android.app.PendingIntent} that you created. This + example uses an arbitrary value of 1001 for the request code:

      @@ -404,9 +423,9 @@ startIntentSenderForResult(pendingIntent.getIntentSender(),
         Google Play sends a response to your {@link android.app.PendingIntent} to the
         {@link android.app.Activity#onActivityResult onActivityResult} method of your
         application. The {@link android.app.Activity#onActivityResult
      -  onActivityResult} method will have a result code of {@code
      -  Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To see the
      -  types of order information that is returned in the response {@link
      +  onActivityResult} method has a result code of {@code
      +  Activity.RESULT_OK} (1) or {@code Activity.RESULT_CANCELED} (0). To view the
      +  types of order information that are returned in the response {@link
         android.content.Intent}, see In-app
         Billing Reference.
      @@ -415,7 +434,7 @@ startIntentSenderForResult(pendingIntent.getIntentSender(),
       

      The purchase data for the order is a String in JSON format that is mapped to the {@code INAPP_PURCHASE_DATA} key in the response {@link - android.content.Intent}, for example: + android.content.Intent}. Here is an example:

      @@ -436,13 +455,13 @@ startIntentSenderForResult(pendingIntent.getIntentSender(),
         long. Pass this entire token to other methods, such as when you consume the
         purchase, as described in Consume
      -  a Purchase. Do not abbreviate or truncate this token; you must save and
      +  a Purchase. Don't abbreviate or truncate this token; you must save and
         return the entire token.
       

      - Continuing from the previous example, you get the response code, purchase - data, and signature from the response {@link android.content.Intent}. + Continuing from the previous example, you receive the response code, purchase + data, and signature from the response {@link android.content.Intent}:

      @@ -472,23 +491,23 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       

      Security Recommendation: When you send a purchase request, create a String token that uniquely identifies this purchase request and - include this token in the {@code developerPayload}.You can use a randomly - generated string as the token. When you receive the purchase response from - Google Play, make sure to check the returned data signature, the {@code + include this token in the {@code developerPayload}. You can use a randomly-generated + string as the token. When you receive the purchase response from + Google Play, ensure that you check the returned data signature, the {@code orderId}, and the {@code developerPayload} String. For added security, you - should perform the checking on your own secure server. Make sure to verify + should perform the checking on your own secure server. Verify that the {@code orderId} is a unique value that you have not previously - processed, and the {@code developerPayload} String matches the token that you + processed and that the {@code developerPayload} String matches the token that you sent previously with the purchase request.

      -

      Querying for Purchased Items

      +

      Querying for purchased items

      - To retrieve information about purchases made by a user from your app, call + To retrieve information about purchases that are made by a user from your app, call the {@code getPurchases} method on the In-app Billing Version 3 service. Pass - in to the method the In-app Billing API version (“3”), the package name of - your calling app, and the purchase type (“inapp” or "subs"). + the In-app Billing API version (“3”), the package name of + your calling app, and the purchase type (“inapp” or "subs") into the method. Here is an example:

      @@ -507,18 +526,18 @@ Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
         To improve performance, the In-app Billing service returns only up to 700
         products that are owned by the user when {@code getPurchase} is first called.
         If the user owns a large number of products, Google Play includes a String
      -  token mapped to the key {@code INAPP_CONTINUATION_TOKEN} in the response
      +  token that is mapped to the key {@code INAPP_CONTINUATION_TOKEN} in the response
         {@link android.os.Bundle} to indicate that more products can be retrieved.
      -  Your application can then make a subsequent {@code getPurchases} call, and
      +  Your application can then make a subsequent {@code getPurchases} call and
         pass in this token as an argument. Google Play continues to return a
         continuation token in the response {@link android.os.Bundle} until all
      -  products that are owned by the user has been sent to your app.
      +  of the products that are owned by the user are sent to your app.
       

      -

      For more information about the data returned by {@code getPurchases}, see +

      For more information about the data that is returned by {@code getPurchases}, see In-app Billing Reference. The following example shows how you can - retrieve this data from the response. + retrieve this data from the response:

      @@ -548,26 +567,26 @@ if (response == 0) {
       
      -

      Consuming a Purchase

      +

      Consuming a purchase

      You can use the In-app Billing Version 3 API to track the ownership of purchased in-app products in Google Play. Once an in-app product is - purchased, it is considered to be "owned" and cannot be purchased from Google + purchased, it is considered to be owned and cannot be purchased from Google Play. You must send a consumption request for the in-app product before Google Play makes it available for purchase again.

      -

      +

      Important: Managed in-app products are consumable, but subscriptions are not.

      - How you use the consumption mechanism in your app is up to you. Typically, - you would implement consumption for in-app products with temporary benefits + The way that you use the consumption mechanism in your app is up to you. Typically, + you implement consumption for in-app products with temporary benefits that users may want to purchase multiple times (for example, in-game currency - or equipment). You would typically not want to implement consumption for + or equipment). You typically don't want to implement consumption for in-app products that are purchased once and provide a permanent effect (for example, a premium upgrade).

      @@ -576,21 +595,21 @@ if (response == 0) { To record a purchase consumption, send the {@code consumePurchase} method to the In-app Billing service and pass in the {@code purchaseToken} String value that identifies the purchase to be removed. The {@code purchaseToken} is part - of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google - Play service following a successful purchase request. In this example, you - are recording the consumption of a product that is identified with the {@code - purchaseToken} in the {@code token} variable. + of the data that is returned in the {@code INAPP_PURCHASE_DATA} String by the Google + Play service following a successful purchase request. This example + records the consumption of a product that is identified with the {@code + purchaseToken} in the {@code token} variable:

       int response = mService.consumePurchase(3, getPackageName(), token);
       
      -

      - Warning: Do not call the {@code consumePurchase} method on - the main thread. Calling this method triggers a network request which could +

      + Warning: Don't call the {@code consumePurchase} method on + the main thread. Calling this method triggers a network request that could block your main thread. Instead, create a separate thread and call the {@code - consumePurchase} method from inside that thread. + consumePurchase} method from inside of that thread.

      @@ -600,20 +619,20 @@ int response = mService.consumePurchase(3, getPackageName(), token); purchased.

      -

      - Security Recommendation: You must send a consumption request +

      + Security Recommendation: Send a consumption request before provisioning the benefit of the consumable in-app purchase to the - user. Make sure that you have received a successful consumption response from + user. Ensure that you receive a successful consumption response from Google Play before you provision the item.

      -

      Implementing Subscriptions

      +

      Implementing subscriptions

      Launching a purchase flow for a subscription is similar to launching the purchase flow for a product, with the exception that the product type must be set to "subs". The purchase result is delivered to your Activity's {@link android.app.Activity#onActivityResult onActivityResult} method, exactly -as in the case of in-app products.

      +as in the case of in-app products. Here is an example:

       Bundle bundle = mService.getBuyIntent(3, "com.example.myapp",
      @@ -629,18 +648,18 @@ if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) {
       

      To query for active subscriptions, use the {@code getPurchases} method, again -with the product type parameter set to "subs".

      +with the product type parameter set to "subs":

       Bundle activeSubs = mService.getPurchases(3, "com.example.myapp",
                          "subs", continueToken);
       
      -

      The call returns a {@code Bundle} with all the active subscriptions owned by -the user. Once a subscription expires without renewal, it will no longer appear +

      The call returns a {@code Bundle} with all of the active subscriptions that are owned by +the user. When a subscription expires without renewal, it no longer appears in the returned {@code Bundle}.

      -

      Securing Your Application

      +

      Securing your application

      To help ensure the integrity of the transaction information that is sent to your application, Google Play signs the JSON string that contains the response @@ -648,21 +667,21 @@ data for a purchase order. Google Play uses the private key that is associated with your application in the Developer Console to create this signature. The Developer Console generates an RSA key pair for each application.

      -

      Note:To find the public key portion of this key -pair, open your application's details in the Developer Console, then click on -Services & APIs, and look at the field titled +

      Note: To find the public key portion of this key +pair, open your application's details in the Developer Console, click +Services & APIs, and review the field titled Your License Key for This Application.

      -

      The Base64-encoded RSA public key generated by Google Play is in binary +

      The Base64-encoded RSA public key that is generated by Google Play is in binary encoded, X.509 subjectPublicKeyInfo DER SEQUENCE format. It is the same public key that is used with Google Play licensing.

      -

      When your application receives this signed response you can +

      When your application receives this signed response, you can use the public key portion of your RSA key pair to verify the signature. -By performing signature verification you can detect responses that have +By performing signature verification, you can detect any responses that have been tampered with or that have been spoofed. You can perform this signature verification step in your application; however, if your application connects -to a secure remote server then we recommend that you perform the signature +to a secure remote server, Google recommends that you perform the signature verification on that server.

      For more information about best practices for security and design, see

      In this document

        -
      1. The Basics
      2. -
      3. Creating a Bound Service +
      4. The basics
      5. +
      6. Creating a bound service
        1. Extending the Binder class
        2. Using a Messenger
      7. -
      8. Binding to a Service +
      9. Binding to a service
        1. Additional notes
      10. -
      11. Managing the Lifecycle of a Bound Service
      12. +
      13. Managing the lifecycle of a bound service

      Key classes

      @@ -32,9 +32,13 @@ parent.link=services.html

      Samples

        -
      1. {@code +
      2. + {@code RemoteService}
      3. -
      4. {@code +
      5. + {@code LocalService}
      @@ -45,19 +49,23 @@ parent.link=services.html -

      A bound service is the server in a client-server interface. A bound service allows components -(such as activities) to bind to the service, send requests, receive responses, and even perform +

      A bound service is the server in a client-server interface. It allows components +(such as activities) to bind to the service, send requests, receive responses, and perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.

      -

      This document shows you how to create a bound service, including how to bind -to the service from other application components. However, you should also refer to the Services document for additional -information about services in general, such as how to deliver notifications from a service, set -the service to run in the foreground, and more.

      +

      Note: If your app targets Android 5.0 (API level 21) or later, +it's recommended that you use the {@link android.app.job.JobScheduler} to execute background + services. For more information about {@link android.app.job.JobScheduler}, see its + {@link android.app.job.JobScheduler API-reference documentation}.

      +

      This document describes how to create a bound service, including how to bind +to the service from other application components. For additional information about services in + general, such as how to deliver notifications from a service and set the service to run + in the foreground, refer to the + Services document.

      -

      The Basics

      +

      The basics

      A bound service is an implementation of the {@link android.app.Service} class that allows other applications to bind to it and interact with it. To provide binding for a @@ -67,57 +75,61 @@ clients can use to interact with the service.

      -

      A client can bind to the service by calling {@link android.content.Context#bindService +

      A client can bind to a service by calling {@link android.content.Context#bindService bindService()}. When it does, it must provide an implementation of {@link android.content.ServiceConnection}, which monitors the connection with the service. The {@link -android.content.Context#bindService bindService()} method returns immediately without a value, but +android.content.Context#bindService bindService()} method returns immediately without a + value, but when the Android system creates the connection between the client and service, it calls {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} on the {@link android.content.ServiceConnection}, to deliver the {@link android.os.IBinder} that the client can use to communicate with the service.

      -

      Multiple clients can connect to the service at once. However, the system calls your service's -{@link android.app.Service#onBind onBind()} method to retrieve the {@link android.os.IBinder} only +

      Multiple clients can connect to a service simultaneously. However, the system calls your service's +{@link android.app.Service#onBind onBind()} method to retrieve the + {@link android.os.IBinder} only when the first client binds. The system then delivers the same {@link android.os.IBinder} to any -additional clients that bind, without calling {@link android.app.Service#onBind onBind()} again.

      +additional clients that bind, without calling {@link android.app.Service#onBind onBind()} + again.

      -

      When the last client unbinds from the service, the system destroys the service (unless the -service was also started by {@link android.content.Context#startService startService()}).

      +

      When the last client unbinds from the service, the system destroys the service, unless the +service was also started by {@link android.content.Context#startService startService()}.

      -

      When you implement your bound service, the most important part is defining the interface -that your {@link android.app.Service#onBind onBind()} callback method returns. There are a few -different ways you can define your service's {@link android.os.IBinder} interface and the following -section discusses each technique.

      +

      The most important part of your bound service implementation is defining the interface +that your {@link android.app.Service#onBind onBind()} callback method returns. The following +section discusses several different ways that you can define your service's + {@link android.os.IBinder} interface.

      - - -

      Creating a Bound Service

      +

      Creating a bound service

      When creating a service that provides binding, you must provide an {@link android.os.IBinder} that provides the programming interface that clients can use to interact with the service. There @@ -125,12 +137,14 @@ are three ways you can define the interface:

      Extending the Binder class
      -
      If your service is private to your own application and runs in the same process as the client -(which is common), you should create your interface by extending the {@link android.os.Binder} class +
      If your service is private to your own application and runs in the same process + as the client +(which is common), you should create your interface by extending the {@link android.os.Binder} + class and returning an instance of it from {@link android.app.Service#onBind onBind()}. The client receives the {@link android.os.Binder} and can use it to directly access public methods available in either the {@link android.os.Binder} -implementation or even the {@link android.app.Service}. +implementation or the {@link android.app.Service}.

      This is the preferred technique when your service is merely a background worker for your own application. The only reason you would not create your interface this way is because your service is used by other applications or across separate processes.

      @@ -143,20 +157,20 @@ android.os.Message} objects. This {@link android.os.Handler} is the basis for a {@link android.os.Messenger} that can then share an {@link android.os.IBinder} with the client, allowing the client to send commands to the service using {@link android.os.Message} objects. Additionally, the client can define a {@link android.os.Messenger} of -its own so the service can send messages back. +its own, so the service can send messages back.

      This is the simplest way to perform interprocess communication (IPC), because the {@link android.os.Messenger} queues all requests into a single thread so that you don't have to design your service to be thread-safe.

      -
      Using AIDL
      -
      AIDL (Android Interface Definition Language) performs all the work to decompose objects into -primitives that the operating system can understand and marshall them across processes to perform +
      Using AIDL
      +
      Android Interface Definition Language (AIDL) decomposes objects into +primitives that the operating system can understand and marshals them across processes to perform IPC. The previous technique, using a {@link android.os.Messenger}, is actually based on AIDL as its underlying structure. As mentioned above, the {@link android.os.Messenger} creates a queue of all the client requests in a single thread, so the service receives requests one at a time. If, however, you want your service to handle multiple requests simultaneously, then you can use AIDL -directly. In this case, your service must be capable of multi-threading and be built thread-safe. +directly. In this case, your service must be thread-safe and capable of multi-threading.

      To use AIDL directly, you must create an {@code .aidl} file that defines the programming interface. The Android SDK tools use this file to generate an abstract class that implements the interface and handles IPC, which you @@ -164,19 +178,18 @@ can then extend within your service.

      -

      Note: Most applications should not use AIDL to +

      Note: Most applications shouldn't use AIDL to create a bound service, because it may require multithreading capabilities and -can result in a more complicated implementation. As such, AIDL is not suitable for most applications +can result in a more complicated implementation. As such, AIDL is not suitable for + most applications and this document does not discuss how to use it for your service. If you're certain that you need to use AIDL directly, see the AIDL document.

      - - -

      Extending the Binder class

      -

      If your service is used only by the local application and does not need to work across processes, +

      If your service is used only by the local application and does not need to + work across processes, then you can implement your own {@link android.os.Binder} class that provides your client direct access to public methods in the service.

      @@ -187,13 +200,14 @@ background.

      Here's how to set it up:

        -
      1. In your service, create an instance of {@link android.os.Binder} that either: +
      2. In your service, create an instance of {@link android.os.Binder} that does + one of the following:
          -
        • contains public methods that the client can call
        • -
        • returns the current {@link android.app.Service} instance, which has public methods the -client can call
        • -
        • or, returns an instance of another class hosted by the service with public methods the -client can call
        • +
        • Contains public methods that the client can call.
        • +
        • Returns the current {@link android.app.Service} instance, which has public methods the +client can call.
        • +
        • Returns an instance of another class hosted by the service with public methods the +client can call.
      3. Return this instance of {@link android.os.Binder} from the {@link android.app.Service#onBind onBind()} callback method.
      4. @@ -202,12 +216,13 @@ android.content.ServiceConnection#onServiceConnected onServiceConnected()} callb make calls to the bound service using the methods provided.
      -

      Note: The reason the service and client must be in the same -application is so the client can cast the returned object and properly call its APIs. The service +

      Note: The service and client must be in the same +application so that the client can cast the returned object and properly call its APIs. + The service and client must also be in the same process, because this technique does not perform any -marshalling across processes.

      +marshaling across processes.

      -

      For example, here's a service that provides clients access to methods in the service through +

      For example, here's a service that provides clients with access to methods in the service through a {@link android.os.Binder} implementation:

      @@ -316,32 +331,30 @@ section provides more information about this process of binding to the service.<
       

      Note: In the example above, the {@link android.app.Activity#onStop onStop()} method unbinds the client from the service. Clients should unbind from services at appropriate times, as discussed in -Additional Notes. +Additional notes.

      For more sample code, see the {@code +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html"> +{@code LocalService.java} class and the {@code +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html"> +{@code LocalServiceActivities.java} class in ApiDemos.

      - - - -

      Using a Messenger

      @@ -352,10 +365,11 @@ you to perform interprocess communication (IPC) without the need to use AIDL.

      Here's a summary of how to use a {@link android.os.Messenger}:

      -
        +
        1. The service implements a {@link android.os.Handler} that receives a callback for each call from a client.
        2. -
        3. The {@link android.os.Handler} is used to create a {@link android.os.Messenger} object +
        4. The service uses the {@link android.os.Handler} to create a {@link android.os.Messenger} + object (which is a reference to the {@link android.os.Handler}).
        5. The {@link android.os.Messenger} creates an {@link android.os.IBinder} that the service returns to clients from {@link android.app.Service#onBind onBind()}.
        6. @@ -365,11 +379,12 @@ returns to clients from {@link android.app.Service#onBind onBind()}.
        7. The service receives each {@link android.os.Message} in its {@link android.os.Handler}—specifically, in the {@link android.os.Handler#handleMessage handleMessage()} method.
        8. -
      +
    -

    In this way, there are no "methods" for the client to call on the service. Instead, the -client delivers "messages" ({@link android.os.Message} objects) that the service receives in +

    In this way, there are no methods for the client to call on the service. Instead, the +client delivers messages ({@link android.os.Message} objects) that the service + receives in its {@link android.os.Handler}.

    Here's a simple example service that uses a {@link android.os.Messenger} interface:

    @@ -488,41 +503,42 @@ public class ActivityMessenger extends Activity { } -

    Notice that this example does not show how the service can respond to the client. If you want the -service to respond, then you need to also create a {@link android.os.Messenger} in the client. Then -when the client receives the {@link android.content.ServiceConnection#onServiceConnected +

    Notice that this example does not show how the service can respond to the client. + If you want the +service to respond, you need to also create a {@link android.os.Messenger} in the client. +When the client receives the {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback, it sends a {@link android.os.Message} to the service that includes the client's {@link android.os.Messenger} in the {@link android.os.Message#replyTo} parameter of the {@link android.os.Messenger#send send()} method.

    You can see an example of how to provide two-way messaging in the {@code +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html"> +{@code MessengerService.java} (service) and {@code +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerServiceActivities.html"> +{@code MessengerServiceActivities.java} (client) samples.

    - - - - -

    Binding to a Service

    +

    Binding to a service

    Application components (clients) can bind to a service by calling {@link android.content.Context#bindService bindService()}. The Android system then calls the service's {@link android.app.Service#onBind -onBind()} method, which returns an {@link android.os.IBinder} for interacting with the service.

    +onBind()} method, which returns an {@link android.os.IBinder} for interacting with + the service.

    -

    The binding is asynchronous. {@link android.content.Context#bindService -bindService()} returns immediately and does not return the {@link android.os.IBinder} to -the client. To receive the {@link android.os.IBinder}, the client must create an instance of {@link +

    The binding is asynchronous, and {@link android.content.Context#bindService +bindService()} returns immediately without not returning the {@link android.os.IBinder} to +the client. To receive the {@link android.os.IBinder}, the client must create an + instance of {@link android.content.ServiceConnection} and pass it to {@link android.content.Context#bindService bindService()}. The {@link android.content.ServiceConnection} includes a callback method that the system calls to deliver the {@link android.os.IBinder}.

    Note: Only activities, services, and content providers can bind -to a service—you cannot bind to a service from a broadcast receiver.

    +to a service—you can't bind to a service from a broadcast receiver.

    -

    So, to bind to a service from your client, you must:

    +

    To bind to a service from your client, follow these steps:

    1. Implement {@link android.content.ServiceConnection}.

      Your implementation must override two callback methods:

      @@ -533,7 +549,8 @@ the service's {@link android.app.Service#onBind onBind()} method.
      {@link android.content.ServiceConnection#onServiceDisconnected onServiceDisconnected()}
      The Android system calls this when the connection to the service is unexpectedly -lost, such as when the service has crashed or has been killed. This is not called when the +lost, such as when the service has crashed or has been killed. This is not + called when the client unbinds.
    2. @@ -548,12 +565,12 @@ android.content.Context#unbindService unbindService()}.

      If your client is still bound to a service when your app destroys the client, destruction causes the client to unbind. It is better practice to unbind the client as soon as it is done interacting with the service. Doing so allows the idle service to shut down. For more information -about appropriate times to bind and unbind, see Additional Notes. +about appropriate times to bind and unbind, see Additional notes.

    -

    For example, the following snippet connects the client to the service created above by +

    The following example connects the client to the service created above by extending the Binder class, so all it must do is cast the returned {@link android.os.IBinder} to the {@code LocalService} class and request the {@code LocalService} instance:

    @@ -579,8 +596,9 @@ private ServiceConnection mConnection = new ServiceConnection() { }; -

    With this {@link android.content.ServiceConnection}, the client can bind to a service by passing -it to {@link android.content.Context#bindService bindService()}. For example:

    +

    With this {@link android.content.ServiceConnection}, the client can bind to a service + by passing +it to {@link android.content.Context#bindService bindService()}, as shown in the following example:

     Intent intent = new Intent(this, LocalService.class);
    @@ -589,11 +607,21 @@ bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
     
     
    • The first parameter of {@link android.content.Context#bindService bindService()} is an -{@link android.content.Intent} that explicitly names the service to bind (thought the intent -could be implicit).
    • +{@link android.content.Intent} that explicitly names the service to bind. +

      Caution: If you use an intent to bind to a + {@link android.app.Service}, ensure that your app is secure by using an explicit +intent. Using an implicit intent to start a service is a +security hazard because you can't be certain what service will respond to the intent, +and the user can't see which service starts. Beginning with Android 5.0 (API level 21), + the system +throws an exception if you call {@link android.content.Context#bindService bindService()} +with an implicit intent.

      + +
    • The second parameter is the {@link android.content.ServiceConnection} object.
    • The third parameter is a flag indicating options for the binding. It should usually be {@link -android.content.Context#BIND_AUTO_CREATE} in order to create the service if its not already alive. +android.content.Context#BIND_AUTO_CREATE} in order to create the service if it's not already + alive. Other possible values are {@link android.content.Context#BIND_DEBUG_UNBIND} and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.
    @@ -606,10 +634,11 @@ and {@link android.content.Context#BIND_NOT_FOREGROUND}, or {@code 0} for none.<
  1. You should always trap {@link android.os.DeadObjectException} exceptions, which are thrown when the connection has broken. This is the only exception thrown by remote methods.
  2. Objects are reference counted across processes.
  3. -
  4. You should usually pair the binding and unbinding during -matching bring-up and tear-down moments of the client's lifecycle. For example: +
  5. You usually pair the binding and unbinding during +matching bring-up and tear-down moments of the client's lifecycle, as described in the + following examples:
      -
    • If you only need to interact with the service while your activity is visible, you +
    • If you need to interact with the service only while your activity is visible, you should bind during {@link android.app.Activity#onStart onStart()} and unbind during {@link android.app.Activity#onStop onStop()}.
    • If you want your activity to receive responses even while it is stopped in the @@ -619,33 +648,34 @@ activity needs to use the service the entire time it's running (even in the back the service is in another process, then you increase the weight of the process and it becomes more likely that the system will kill it.
    -

    Note: You should usually not bind and unbind +

    Note: You don't usually bind and unbind during your activity's {@link android.app.Activity#onResume onResume()} and {@link -android.app.Activity#onPause onPause()}, because these callbacks occur at every lifecycle transition +android.app.Activity#onPause onPause()}, because these callbacks occur at every + lifecycle transition and you should keep the processing that occurs at these transitions to a minimum. Also, if -multiple activities in your application bind to the same service and there is a transition between -two of those activities, the service may be destroyed and recreated as the current activity unbinds -(during pause) before the next one binds (during resume). (This activity transition for how +multiple activities in your application bind to the same service and there is a + transition between +two of those activities, the service may be destroyed and recreated as the current + activity unbinds +(during pause) before the next one binds (during resume). This activity transition for how activities coordinate their lifecycles is described in the Activities -document.)

    +document.

    For more sample code, showing how to bind to a service, see the {@code +href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/RemoteService.html"> +{@code RemoteService.java} class in ApiDemos.

    - - - - -

    Managing the Lifecycle of a Bound Service

    +

    Managing the lifecycle of a bound service

    When a service is unbound from all clients, the Android system destroys it (unless it was also started with {@link android.app.Service#onStartCommand onStartCommand()}). As such, you don't have to manage the lifecycle of your service if it's purely a bound -service—the Android system manages it for you based on whether it is bound to any clients.

    +service—the Android system manages it for you based on whether it is bound to + any clients.

    However, if you choose to implement the {@link android.app.Service#onStartCommand onStartCommand()} callback method, then you must explicitly stop the service, because the @@ -660,17 +690,11 @@ your {@link android.app.Service#onUnbind onUnbind()} method, you can optionally onRebind()} the next time a client binds to the service. {@link android.app.Service#onRebind onRebind()} returns void, but the client still receives the {@link android.os.IBinder} in its {@link android.content.ServiceConnection#onServiceConnected onServiceConnected()} callback. -Below, figure 1 illustrates the logic for this kind of lifecycle.

    - +The following figure illustrates the logic for this kind of lifecycle.

    Figure 1. The lifecycle for a service that is started and also allows binding.

    -

    For more information about the lifecycle of a started service, see the Services document.

    - - - - diff --git a/docs/html/guide/components/fundamentals.jd b/docs/html/guide/components/fundamentals.jd index ed3ba7dc2249..eaa82c8fe25e 100644 --- a/docs/html/guide/components/fundamentals.jd +++ b/docs/html/guide/components/fundamentals.jd @@ -6,28 +6,29 @@ page.title=Application Fundamentals

    In this document

      -
    1. App Components +
    2. App components
      1. Activating components
    3. -
    4. The Manifest File +
    5. The manifest file
      1. Declaring components
      2. Declaring app requirements
    6. -
    7. App Resources
    8. +
    9. App resources

    Android apps are written in the Java programming language. The Android SDK tools compile -your code—along with any data and resource files—into an APK: an Android package, +your code along with any data and resource files into an APK, an Android package, which is an archive file with an {@code .apk} suffix. One APK file contains all the contents of an Android app and is the file that Android-powered devices use to install the app.

    -

    Once installed on a device, each Android app lives in its own security sandbox:

    +

    Each Android app lives in its own security sandbox, protected by + the following Android security features:

    • The Android operating system is a multi-user Linux system in which each app is a @@ -40,54 +41,61 @@ app so that only the user ID assigned to that app can access them.
    • Each process has its own virtual machine (VM), so an app's code runs in isolation from other apps.
    • -
    • By default, every app runs in its own Linux process. Android starts the process when any -of the app's components need to be executed, then shuts down the process when it's no longer +
    • By default, every app runs in its own Linux process. The Android system starts + the process when any +of the app's components need to be executed, and then shuts down the process + when it's no longer needed or when the system must recover memory for other apps.
    -

    In this way, the Android system implements the principle of least privilege. That is, +

    The Android system implements the principle of least privilege. That is, each app, by default, has access only to the components that it requires to do its work and no more. This creates a very secure environment in which an app cannot access parts of -the system for which it is not given permission.

    - -

    However, there are ways for an app to share data with other apps and for an +the system for which it is not given permission. However, there are ways for an app to share + data with other apps and for an app to access system services:

    • It's possible to arrange for two apps to share the same Linux user ID, in which case they are able to access each other's files. To conserve system resources, apps with the -same user ID can also arrange to run in the same Linux process and share the same VM (the -apps must also be signed with the same certificate).
    • +same user ID can also arrange to run in the same Linux process and share the same VM. The +apps must also be signed with the same certificate.
    • An app can request permission to access device data such as the user's -contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. The user has +contacts, SMS messages, the mountable storage (SD card), camera, and Bluetooth. The user has to explicitly grant these permissions. For more information, see Working with System Permissions.
    -

    That covers the basics regarding how an Android app exists within the system. The rest of -this document introduces you to:

    +

    The rest of this document introduces the following concepts:

    • The core framework components that define your app.
    • -
    • The manifest file in which you declare components and required device features for your +
    • The manifest file in which you declare the components and the required device + features for your app.
    • -
    • Resources that are separate from the app code and allow your app to +
    • Resources that are separate from the app code and that allow your app to gracefully optimize its behavior for a variety of device configurations.
    -

    App Components

    +

    App components

    App components are the essential building blocks of an Android app. Each component is a different point through which the system can enter your app. Not all -components are actual entry points for the user and some depend on each other, but each one exists -as its own entity and plays a specific role—each one is a unique building block that -helps define your app's overall behavior.

    - -

    There are four different types of app components. Each type serves a distinct purpose -and has a distinct lifecycle that defines how the component is created and destroyed.

    +components are actual entry points for the user and some depend on each other, + but each one exists +as its own entity and plays a specific role.

    -

    Here are the four types of app components:

    +

    There are four different types of app components: +

      +
    • Activities.
    • +
    • Services.
    • +
    • Content providers.
    • +
    • Broadcast receivers.
    • +

    +Each type serves a distinct purpose +and has a distinct lifecycle that defines how the component is created and destroyed. + The following sections describe the four types of app components.

    @@ -98,11 +106,12 @@ an email app might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email app, each one is independent of the others. As such, a different app can start any one of these -activities (if the email app allows it). For example, a camera app can start the -activity in the email app that composes new mail, in order for the user to share a picture. +activities if the email app allows it. For example, a camera app can start the +activity in the email app that composes new mail to allow the user to share a picture. -

    An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more -about it in the Activities +

    An activity is implemented as a subclass of {@link android.app.Activity}. You can learn more +about {@link android.app.Activity} in the + Activities developer guide.

    @@ -111,13 +120,16 @@ developer guide.

    A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service -does not provide a user interface. For example, a service might play music in the background while +does not provide a user interface. For example, a service might play music in the + background while the user is in a different app, or it might fetch data over the network without -blocking user interaction with an activity. Another component, such as an activity, can start the +blocking user interaction with an activity. Another component, such as an activity, + can start the service and let it run or bind to it in order to interact with it. -

    A service is implemented as a subclass of {@link android.app.Service} and you can learn more -about it in the Services developer +

    A service is implemented as a subclass of {@link android.app.Service}. You can learn more +about {@link android.app.Service} in the +Services developer guide.

    @@ -125,12 +137,14 @@ guide.

    Content providers
    A content provider manages a shared set of app data. You can store the data in -the file system, an SQLite database, on the web, or any other persistent storage location your -app can access. Through the content provider, other apps can query or even modify -the data (if the content provider allows it). For example, the Android system provides a content +the file system, in a SQLite database, on the web, or on any other persistent storage + location that your +app can access. Through the content provider, other apps can query or modify +the data if the content provider allows it. For example, the Android system provides a content provider that manages the user's contact information. As such, any app with the proper -permissions can query part of the content provider (such as {@link -android.provider.ContactsContract.Data}) to read and write information about a particular person. +permissions can query part of the content provider, such as {@link +android.provider.ContactsContract.Data}, to read and write information about + a particular person.

    Content providers are also useful for reading and writing data that is private to your app and not shared. For example, the

    Broadcast receivers
    A broadcast receiver is a component that responds to system-wide broadcast -announcements. Many broadcasts originate from the system—for example, a broadcast announcing +announcements. Many broadcasts originate from the system—for example, + a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Apps can also initiate broadcasts—for example, to let other apps know that -some data has been downloaded to the device and is available for them to use. Although broadcast +some data has been downloaded to the device and is available for them to use. + Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is -just a "gateway" to other components and is intended to do a very minimal amount of work. For -instance, it might initiate a service to perform some work based on the event. +just a gateway to other components and is intended to do a very minimal amount of work. + For instance, it might initiate a service to perform some work based on the event.

    A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver} and each broadcast is delivered as an {@link android.content.Intent} object. For more information, @@ -170,52 +186,59 @@ see the {@link android.content.BroadcastReceiver} class.

    A unique aspect of the Android system design is that any app can start another app’s component. For example, if you want the user to capture a photo with the device camera, there's probably another app that does that and your -app can use it, instead of developing an activity to capture a photo yourself. You don't +app can use it instead of developing an activity to capture a photo yourself. You don't need to incorporate or even link to the code from the camera app. Instead, you can simply start the activity in the camera app that captures a photo. When complete, the photo is even returned to your app so you can use it. To the user, it seems as if the camera is actually a part of your app.

    -

    When the system starts a component, it starts the process for that app (if it's not -already running) and instantiates the classes needed for the component. For example, if your +

    When the system starts a component, it starts the process for that app if it's not +already running and instantiates the classes needed for the component. For example, if your app starts the activity in the camera app that captures a photo, that activity runs in the process that belongs to the camera app, not in your app's process. Therefore, unlike apps on most other systems, Android apps don't have a single entry -point (there's no {@code main()} function, for example).

    +point (there's no {@code main()} function).

    Because the system runs each app in a separate process with file permissions that restrict access to other apps, your app cannot directly activate a component from -another app. The Android system, however, can. So, to activate a component in -another app, you must deliver a message to the system that specifies your intent to +another app. However, the Android system can. To activate a component in +another app, deliver a message to the system that specifies your intent to start a particular component. The system then activates the component for you.

    -

    Activating Components

    +

    Activating components

    Three of the four component types—activities, services, and broadcast receivers—are activated by an asynchronous message called an intent. -Intents bind individual components to each other at runtime (you can think of them -as the messengers that request an action from other components), whether the component belongs +Intents bind individual components to each other at runtime. You can think of them +as the messengers that request an action from other components, whether the component belongs to your app or another.

    +

    Note: If your app targets Android 5.0 (API level 21) or later, + use the {@link android.app.job.JobScheduler} to execute background + services. For more information about using this class, see the + {@link android.app.job.JobScheduler} reference documentation.

    +

    An intent is created with an {@link android.content.Intent} object, which defines a message to -activate either a specific component or a specific type of component—an intent -can be either explicit or implicit, respectively.

    +activate either a specific component (explicit intent) or a specific type of component + (implicit intent).

    -

    For activities and services, an intent defines the action to perform (for example, to "view" or -"send" something) and may specify the URI of the data to act on (among other things that the -component being started might need to know). For example, an intent might convey a request for an +

    For activities and services, an intent defines the action to perform (for example, to + view or +send something) and may specify the URI of the data to act on, among other things that the +component being started might need to know. For example, an intent might convey a request for an activity to show an image or to open a web page. In some cases, you can start an -activity to receive a result, in which case, the activity also returns -the result in an {@link android.content.Intent} (for example, you can issue an intent to let -the user pick a personal contact and have it returned to you—the return intent includes a -URI pointing to the chosen contact).

    +activity to receive a result, in which case the activity also returns +the result in an {@link android.content.Intent}. For example, you can issue an intent to let +the user pick a personal contact and have it returned to you. The return intent includes a +URI pointing to the chosen contact.

    For broadcast receivers, the intent simply defines the -announcement being broadcast (for example, a broadcast to indicate the device battery is low -includes only a known action string that indicates "battery is low").

    +announcement being broadcast. For example, a broadcast to indicate the device battery is low +includes only a known action string that indicates battery is low.

    -

    The other component type, content provider, is not activated by intents. Rather, it is +

    Unlike activities, services, and broadcast receivers, content providers are not activated + by intents. Rather, they are activated when targeted by a request from a {@link android.content.ContentResolver}. The content resolver handles all direct transactions with the content provider so that the component that's performing transactions with the provider doesn't need to and instead calls methods on the {@link @@ -224,15 +247,19 @@ provider and the component requesting information (for security).

    There are separate methods for activating each type of component:

      -
    • You can start an activity (or give it something new to do) by +
    • You can start an activity or give it something new to do by passing an {@link android.content.Intent} to {@link android.content.Context#startActivity startActivity()} or {@link android.app.Activity#startActivityForResult startActivityForResult()} (when you want the activity to return a result).
    • -
    • You can start a service (or give new instructions to an ongoing service) by + + +
    • With Android 5.0 (API level 21) and later, you can start a service with + {@link android.app.job.JobScheduler}. For earlier Android versions, you can start + a service (or give new instructions to an ongoing service) by passing an {@link android.content.Intent} to {@link android.content.Context#startService -startService()}. Or you can bind to the service by passing an {@link android.content.Intent} to -{@link android.content.Context#bindService bindService()}.
    • -
    • You can initiate a broadcast by passing an {@link android.content.Intent} to methods like +startService()}. You can bind to the service by passing an {@link android.content.Intent} to +{@link android.content.Context#bindService bindService()}.
    • +
    • You can initiate a broadcast by passing an {@link android.content.Intent} to methods such as {@link android.content.Context#sendBroadcast(Intent) sendBroadcast()}, {@link android.content.Context#sendOrderedBroadcast(Intent, String) sendOrderedBroadcast()}, or {@link android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.
    • @@ -242,35 +269,35 @@ android.content.ContentProvider#query query()} on a {@link android.content.Conte

      For more information about using intents, see the Intents and -Intent Filters document. More information about activating specific components is also provided -in the following documents: Activities, Services, {@link -android.content.BroadcastReceiver} and Content Providers.

      - +Intent Filters document. + The following documents provide more information about activating specifc components: + Activities, + Services + {@link android.content.BroadcastReceiver}, and + Content Providers.

      -

      The Manifest File

      +

      The manifest file

      Before the Android system can start an app component, the system must know that the -component exists by reading the app's {@code AndroidManifest.xml} file (the "manifest" -file). Your app must declare all its components in this file, which must be at the root of -the app project directory.

      +component exists by reading the app's manifest file, {@code AndroidManifest.xml}. + Your app must declare all its components in this file, which must be at the root of the + app project directory.

      The manifest does a number of things in addition to declaring the app's components, -such as:

      +such as the following:

        -
      • Identify any user permissions the app requires, such as Internet access or +
      • Identifies any user permissions the app requires, such as Internet access or read-access to the user's contacts.
      • -
      • Declare the minimum API Level +
      • Declares the minimum + API Level required by the app, based on which APIs the app uses.
      • -
      • Declare hardware and software features used or required by the app, such as a camera, +
      • Declares hardware and software features used or required by the app, such as a camera, bluetooth services, or a multitouch screen.
      • -
      • API libraries the app needs to be linked against (other than the Android framework +
      • Declares API libraries the app needs to be linked against (other than the Android framework APIs), such as the Google Maps -library.
      • -
      • And more
      • +href="http://code.google.com/android/add-ons/google-apis/maps-overview.html"> +Google Maps library. +
      @@ -301,47 +328,59 @@ the {@code android:name} attribute specifies the fully qualified class name of t android.app.Activity} subclass and the {@code android:label} attribute specifies a string to use as the user-visible label for the activity.

      -

      You must declare all app components this way:

      +

      You must declare all app components using the following elements:

      • <activity> elements -for activities
      • +for activities.
      • <service> elements for -services
      • +services.
      • <receiver> elements -for broadcast receivers
      • +for broadcast receivers.
      • <provider> elements -for content providers
      • +for content providers.

      Activities, services, and content providers that you include in your source but do not declare in the manifest are not visible to the system and, consequently, can never run. However, broadcast -receivers can be either declared in the manifest or created dynamically in code (as -{@link android.content.BroadcastReceiver} objects) and registered with the system by calling +receivers can be either declared in the manifest or created dynamically in code as +{@link android.content.BroadcastReceiver} objects and registered with the system by calling {@link android.content.Context#registerReceiver registerReceiver()}.

      For more about how to structure the manifest file for your app, see The AndroidManifest.xml File documentation.

      +

      Declaring component capabilities

      +

      As discussed above, in Activating components, you can use an +{@link android.content.Intent} to start activities, services, and broadcast receivers. -

      Declaring component capabilities

      -

      As discussed above, in Activating Components, you can use an -{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so -by explicitly naming the target component (using the component class name) in the intent. However, -the real power of intents lies in the concept of implicit intents. An implicit intent -simply describes the type of action to perform (and, optionally, the data upon which you’d like to -perform the action) and allows the system to find a component on the device that can perform the -action and start it. If there are multiple components that can perform the action described by the -intent, then the user selects which one to use.

      -

      The way the system identifies the components that can respond to an intent is by comparing the +You can use an {@link android.content.Intent} + by explicitly naming the target component (using the component class name) in the intent. + You can also use an implicit intent, which +describes the type of action to perform and, optionally, the data upon which you’d like to +perform the action. The implicit intent allows the system to find a component on the device + that can perform the +action and start it. If there are multiple components that can perform the action described by the +intent, the user selects which one to use.

      + +

      Caution: If you use an intent to start a + {@link android.app.Service}, ensure that your app is secure by using an + explicit +intent. Using an implicit intent to start a service is a +security hazard because you cannot be certain what service will respond to the intent, +and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system +throws an exception if you call {@link android.content.Context#bindService bindService()} +with an implicit intent. Do not declare intent filters for your services.

      + +

      The system identifies the components that can respond to an intent by comparing the intent received to the intent filters provided in the manifest file of other apps on the device.

      @@ -351,8 +390,9 @@ from other apps. You can declare an intent filter for your component by adding an {@code } element as a child of the component's declaration element.

      -

      For example, if you've built an email app with an activity for composing a new email, you can -declare an intent filter to respond to "send" intents (in order to send a new email) like this:

      +

      For example, if you build an email app with an activity for composing a new email, you can +declare an intent filter to respond to "send" intents (in order to send a new email), + as shown in the following example:

       <manifest ... >
           ...
      @@ -368,8 +408,9 @@ declare an intent filter to respond to "send" intents (in order to send a new em
       </manifest>
       
      -

      Then, if another app creates an intent with the {@link -android.content.Intent#ACTION_SEND} action and passes it to {@link android.app.Activity#startActivity +

      If another app creates an intent with the {@link +android.content.Intent#ACTION_SEND} action and passes it to + {@link android.app.Activity#startActivity startActivity()}, the system may start your activity so the user can draft and send an email.

      @@ -382,7 +423,7 @@ href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filter

      Declaring app requirements

      There are a variety of devices powered by Android and not all of them provide the -same features and capabilities. In order to prevent your app from being installed on devices +same features and capabilities. To prevent your app from being installed on devices that lack features needed by your app, it's important that you clearly define a profile for the types of devices your app supports by declaring device and software requirements in your manifest file. Most of these declarations are informational only and the system does not read @@ -391,7 +432,7 @@ for users when they search for apps from their device.

      For example, if your app requires a camera and uses APIs introduced in Android 2.1 (API Level 7), -you should declare these as requirements in your manifest file like this:

      +you must declare these as requirements in your manifest file as shown in the following example:

       <manifest ... >
      @@ -402,10 +443,10 @@ you should declare these as requirements in your manifest file like this:

      </manifest>
      -

      Now, devices that do not have a camera and have an -Android version lower than 2.1 cannot install your app from Google Play.

      - -

      However, you can also declare that your app uses the camera, but does not +

      With the declarations shown in the example, devices that do not have a + camera and have an +Android version lower than 2.1 cannot install your app from Google Play. + However, you can declare that your app uses the camera, but does not require it. In that case, your app must set the {@code required} attribute to {@code "false"} and check at runtime whether @@ -417,15 +458,15 @@ document.

      -

      App Resources

      +

      App resources

      An Android app is composed of more than just code—it requires resources that are separate from the source code, such as images, audio files, and anything relating to the visual -presentation of the app. For example, you should define animations, menus, styles, colors, +presentation of the app. For example, you can define animations, menus, styles, colors, and the layout of activity user interfaces with XML files. Using app resources makes it easy -to update various characteristics of your app without modifying code and—by providing -sets of alternative resources—enables you to optimize your app for a variety of -device configurations (such as different languages and screen sizes).

      +to update various characteristics of your app without modifying code. Providing +sets of alternative resources enables you to optimize your app for a variety of +device configurations, such as different languages and screen sizes.

      For every resource that you include in your Android project, the SDK build tools define a unique integer ID, which you can use to reference the resource from your app code or from @@ -435,20 +476,22 @@ named {@code R.drawable.logo}, which you can use to reference the image and inse user interface.

      One of the most important aspects of providing resources separate from your source code -is the ability for you to provide alternative resources for different device -configurations. For example, by defining UI strings in XML, you can translate the strings into other -languages and save those strings in separate files. Then, based on a language qualifier +is the ability to provide alternative resources for different device +configurations. For example, by defining UI strings in XML, you can translate + the strings into other +languages and save those strings in separate files. Then Android applies the + appropriate language strings +to your UI based on a language qualifier that you append to the resource directory's name (such as {@code res/values-fr/} for French string -values) and the user's language setting, the Android system applies the appropriate language strings -to your UI.

      +values) and the user's language setting.

      Android supports many different qualifiers for your alternative resources. The qualifier is a short string that you include in the name of your resource directories in order to -define the device configuration for which those resources should be used. As another -example, you should often create different layouts for your activities, depending on the -device's screen orientation and size. For example, when the device screen is in portrait +define the device configuration for which those resources should be used. For +example, you should create different layouts for your activities, depending on the +device's screen orientation and size. When the device screen is in portrait orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in -landscape orientation (wide), the buttons should be aligned horizontally. To change the layout +landscape orientation (wide), the buttons could be aligned horizontally. To change the layout depending on the orientation, you can define two different layouts and apply the appropriate qualifier to each layout's directory name. Then, the system automatically applies the appropriate layout depending on the current device orientation.

      @@ -465,15 +508,15 @@ create alternative resources for different device configurations, read
      Intents and Intent Filters
      -
      Information about how to use the {@link android.content.Intent} APIs to +
      How to use the {@link android.content.Intent} APIs to activate app components, such as activities and services, and how to make your app components available for use by other apps.
      Activities
      -
      Information about how to create an instance of the {@link android.app.Activity} class, +
      How to create an instance of the {@link android.app.Activity} class, which provides a distinct screen in your application with a user interface.
      Providing Resources
      -
      Information about how Android apps are structured to separate app resources from the +
      How Android apps are structured to separate app resources from the app code, including how you can provide alternative resources for specific device configurations.
      @@ -484,14 +527,13 @@ href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resou
      Device Compatibility
      -
      Information about Android works on different types of devices and an introduction +
      How Android works on different types of devices and an introduction to how you can optimize your app for each device or restrict your app's availability to different devices.
      System Permissions
      -
      Information about how Android restricts app access to certain APIs with a permission +
      How Android restricts app access to certain APIs with a permission system that requires the user's consent for your app to use those APIs.
      - diff --git a/docs/html/guide/components/intents-filters.jd b/docs/html/guide/components/intents-filters.jd index d1d8c78fae3f..8f41bc3d3675 100644 --- a/docs/html/guide/components/intents-filters.jd +++ b/docs/html/guide/components/intents-filters.jd @@ -7,21 +7,21 @@ page.tags="IntentFilter"

      In this document

        -
      1. Intent Types
      2. -
      3. Building an Intent +
      4. Intent types
      5. +
      6. Building an intent
        1. Example explicit intent
        2. Example implicit intent
        3. Forcing an app chooser
      7. -
      8. Receiving an Implicit Intent +
      9. Receiving an implicit intent
        1. Example filters
      10. -
      11. Using a Pending Intent
      12. -
      13. Intent Resolution +
      14. Using a pending intent
      15. +
      16. Intent resolution
        1. Action test
        2. Category test
        3. @@ -46,13 +46,14 @@ page.tags="IntentFilter"

          An {@link android.content.Intent} is a messaging object you can use to request an action from another app component. Although intents facilitate communication between components in several ways, there are three -fundamental use-cases:

          +fundamental use cases:

            -
          • To start an activity: +
          • Starting an activity

            An {@link android.app.Activity} represents a single screen in an app. You can start a new instance of an {@link android.app.Activity} by passing an {@link android.content.Intent} -to {@link android.content.Context#startActivity startActivity()}. The {@link android.content.Intent} +to {@link android.content.Context#startActivity startActivity()}. + The {@link android.content.Intent} describes the activity to start and carries any necessary data.

            If you want to receive a result from the activity when it finishes, @@ -63,10 +64,16 @@ android.app.Activity#onActivityResult onActivityResult()} callback. For more information, see the Activities guide.

          • -
          • To start a service: +
          • Starting a service

            A {@link android.app.Service} is a component that performs operations in the background -without a user interface. You can start a service to perform a one-time operation -(such as download a file) by passing an {@link android.content.Intent} +without a user interface. With Android 5.0 (API level 21) and later, you can start a service + with {@link android.app.job.JobScheduler}. For more information + about {@link android.app.job.JobScheduler}, see its + {@link android.app.job.JobScheduler API-reference documentation}.

            +

            For versions earlier than Android 5.0 (API level 21), you can start a service by using +methods of the {@link android.app.Service} class. You can start a service + to perform a one-time operation +(such as downloading a file) by passing an {@link android.content.Intent} to {@link android.content.Context#startService startService()}. The {@link android.content.Intent} describes the service to start and carries any necessary data.

            @@ -75,7 +82,7 @@ from another component by passing an {@link android.content.Intent} to {@link android.content.Context#bindService bindService()}. For more information, see the Services guide.

          • -
          • To deliver a broadcast: +
          • Delivering a broadcast

            A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. You can deliver a broadcast to other apps by passing an {@link android.content.Intent} @@ -89,7 +96,7 @@ android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.

            -

            Intent Types

            +

            Intent types

            There are two types of intents:

            @@ -97,7 +104,7 @@ android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.

          • Explicit intents specify the component to start by name (the fully-qualified class name). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. For -example, start a new activity in response to a user action or start a service to download +example, you can start a new activity in response to a user action or start a service to download a file in the background.
          • Implicit intents do not name a specific component, but instead declare a general action @@ -106,12 +113,13 @@ show the user a location on a map, you can use an implicit intent to request tha app show a specified location on a map.
          -

          When you create an explicit intent to start an activity or service, the system immediately +

          Figure 1 shows how an intent is delivered to start an activity. When you create an + explicit intent to start an activity or service, the system immediately starts the app component specified in the {@link android.content.Intent} object.

          -

          Figure 1. Illustration of how an implicit intent is +

          Figure 1. How an implicit intent is delivered through the system to start another activity: [1] Activity A creates an {@link android.content.Intent} with an action description and passes it to {@link android.content.Context#startActivity startActivity()}. [2] The Android System searches all @@ -135,11 +143,12 @@ you make it possible for other apps to directly start your activity with a certa Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.

          -

          Caution: To ensure your app is secure, always use an explicit +

          Caution: To ensure that your app is secure, always + use an explicit intent when starting a {@link android.app.Service} and do not declare intent filters for your services. Using an implicit intent to start a service is a -security hazard because you cannot be certain what service will respond to the intent, -and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system +security hazard because you can't be certain what service will respond to the intent, +and the user can't see which service starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call {@link android.content.Context#bindService bindService()} with an implicit intent.

          @@ -147,7 +156,7 @@ with an implicit intent.

          -

          Building an Intent

          +

          Building an intent

          An {@link android.content.Intent} object carries information that the Android system uses to determine which component to start (such as the exact component name or component @@ -163,22 +172,23 @@ order to properly perform the action (such as the action to take and the data to

          The name of the component to start.

          This is optional, but it's the critical piece of information that makes an intent -explicit, meaning that the intent should be delivered only to the app component -defined by the component name. Without a component name, the intent is implicit and the +explicit, meaning that the intent should be delivered only to the app component +defined by the component name. Without a component name, the intent is implicit and the system decides which component should receive the intent based on the other intent information -(such as the action, data, and category—described below). So if you need to start a specific +(such as the action, data, and category—described below). If you need to start a specific component in your app, you should specify the component name.

          -

          Note: When starting a {@link android.app.Service}, you should -always specify the component name. Otherwise, you cannot be certain what service +

          Note: When starting a {@link android.app.Service}, + always specify the component name. Otherwise, you cannot be certain what service will respond to the intent, and the user cannot see which service starts.

          This field of the {@link android.content.Intent} is a {@link android.content.ComponentName} object, which you can specify using a fully -qualified class name of the target component, including the package name of the app. For example, +qualified class name of the target component, including the package name of the app, for example, {@code com.example.ExampleActivity}. You can set the component name with {@link android.content.Intent#setComponent setComponent()}, {@link android.content.Intent#setClass -setClass()}, {@link android.content.Intent#setClassName(String, String) setClassName()}, or with the +setClass()}, {@link android.content.Intent#setClassName(String, String) setClassName()}, + or with the {@link android.content.Intent} constructor.

          @@ -188,10 +198,10 @@ setClass()}, {@link android.content.Intent#setClassName(String, String) setClass

          In the case of a broadcast intent, this is the action that took place and is being reported. The action largely determines how the rest of the intent is structured—particularly -what is contained in the data and extras. +the information that is contained in the data and extras.

          You can specify your own actions for use by intents within your app (or for use by other -apps to invoke components in your app), but you should usually use action constants +apps to invoke components in your app), but you usually specify action constants defined by the {@link android.content.Intent} class or other framework classes. Here are some common actions for starting an activity:

          @@ -203,7 +213,7 @@ common actions for starting an activity:

          view in a map app.
    {@link android.content.Intent#ACTION_SEND}
    -
    Also known as the "share" intent, you should use this in an intent with {@link +
    Also known as the share intent, you should use this in an intent with {@link android.content.Context#startActivity startActivity()} when you have some data that the user can share through another app, such as an email app or social sharing app.
    @@ -217,12 +227,13 @@ that open specific screens in the system's Settings app.

    setAction()} or with an {@link android.content.Intent} constructor.

    If you define your own actions, be sure to include your app's package name -as a prefix. For example:

    +as a prefix, as shown in the following example:

    static final String ACTION_TIMETRAVEL = "com.example.action.TIMETRAVEL";
    Data
    -
    The URI (a {@link android.net.Uri} object) that references the data to be acted on and/or the +
    The URI (a {@link android.net.Uri} object) that references the data to + be acted on and/or the MIME type of that data. The type of data supplied is generally dictated by the intent's action. For example, if the action is {@link android.content.Intent#ACTION_EDIT}, the data should contain the URI of the document to edit. @@ -231,10 +242,11 @@ URI of the document to edit. it's often important to specify the type of data (its MIME type) in addition to its URI. For example, an activity that's able to display images probably won't be able to play an audio file, even though the URI formats could be similar. -So specifying the MIME type of your data helps the Android +Specifying the MIME type of your data helps the Android system find the best component to receive your intent. However, the MIME type can sometimes be inferred from the URI—particularly when the data is a -{@code content:} URI, which indicates the data is located on the device and controlled by a +{@code content:} URI. A {@code content:} URI indicates the data is located on the device + and controlled by a {@link android.content.ContentProvider}, which makes the data MIME type visible to the system.

    To set only the data URI, call {@link android.content.Intent#setData setData()}. @@ -243,7 +255,7 @@ can set both explicitly with {@link android.content.Intent#setDataAndType setDataAndType()}.

    Caution: If you want to set both the URI and MIME type, -do not call {@link android.content.Intent#setData setData()} and +don't call {@link android.content.Intent#setData setData()} and {@link android.content.Intent#setType setType()} because they each nullify the value of the other. Always use {@link android.content.Intent#setDataAndType setDataAndType()} to set both URI and MIME type.

    @@ -258,7 +270,7 @@ Here are some common categories:
    {@link android.content.Intent#CATEGORY_BROWSABLE}
    The target activity allows itself to be started by a web browser to display data - referenced by a link—such as an image or an e-mail message. + referenced by a link, such as an image or an e-mail message.
    {@link android.content.Intent#CATEGORY_LAUNCHER}
    The activity is the initial activity of a task and is listed in @@ -276,14 +288,14 @@ categories.

    These properties listed above (component name, action, data, and category) represent the defining characteristics of an intent. By reading these properties, the Android system -is able to resolve which app component it should start.

    - -

    However, an intent can carry additional information that does not affect -how it is resolved to an app component. An intent can also supply:

    +is able to resolve which app component it should start. However, an intent can carry + additional information that does not affect +how it is resolved to an app component. An intent can also supply the following information:

    Extras
    -
    Key-value pairs that carry additional information required to accomplish the requested action. +
    Key-value pairs that carry additional information required to accomplish + the requested action. Just as some actions use particular kinds of data URIs, some actions also use particular extras.

    You can add extra data with various {@link android.content.Intent#putExtra putExtra()} methods, @@ -293,21 +305,22 @@ the {@link android.os.Bundle} in the {@link android.content.Intent} with {@link android.content.Intent#putExtras putExtras()}.

    For example, when creating an intent to send an email with -{@link android.content.Intent#ACTION_SEND}, you can specify the "to" recipient with the -{@link android.content.Intent#EXTRA_EMAIL} key, and specify the "subject" with the +{@link android.content.Intent#ACTION_SEND}, you can specify the to recipient with the +{@link android.content.Intent#EXTRA_EMAIL} key, and specify the subject with the {@link android.content.Intent#EXTRA_SUBJECT} key.

    The {@link android.content.Intent} class specifies many {@code EXTRA_*} constants for standardized data types. If you need to declare your own extra keys (for intents that your app receives), be sure to include your app's package name -as a prefix. For example:

    +as a prefix, as shown in the following example:

    static final String EXTRA_GIGAWATTS = "com.example.EXTRA_GIGAWATTS";
    Flags
    -
    Flags defined in the {@link android.content.Intent} class that function as metadata for the +
    Flags are defined in the {@link android.content.Intent} class that function as metadata for the intent. The flags may instruct the Android system how to launch an activity (for example, which -task the activity should belong +task + the activity should belong to) and how to treat it after it's launched (for example, whether it belongs in the list of recent activities). @@ -354,7 +367,8 @@ this intent explicitly starts the {@code DownloadService} class in the app.

    to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can and you'd like the user to pick which app to use.

    -

    For example, if you have content you want the user to share with other people, create an intent +

    For example, if you have content that you want the user to share with other people, + create an intent with the {@link android.content.Intent#ACTION_SEND} action and add extras that specify the content to share. When you call {@link android.content.Context#startActivity startActivity()} with that intent, the user can @@ -362,13 +376,15 @@ pick an app through which to share the content.

    Caution: It's possible that a user won't have any apps that handle the implicit intent you send to {@link android.content.Context#startActivity -startActivity()}. If that happens, the call will fail and your app will crash. To verify +startActivity()}. If that happens, the call fails and your app crashes. To verify that an activity will receive the intent, call {@link android.content.Intent#resolveActivity resolveActivity()} on your {@link android.content.Intent} object. If the result is non-null, -then there is at least one app that can handle the intent and it's safe to call + there is at least one app that can handle the intent and it's safe to call {@link android.content.Context#startActivity startActivity()}. If the result is null, -you should not use the intent and, if possible, you should disable the feature that issues -the intent.

    + do not use the intent and, if possible, you should disable the feature that issues +the intent. The following example shows how to verify that the intent resolves +to an activity. This example doesn't use a URI, but the intent's data type +is declared to specify the content carried by the extras.

    @@ -384,8 +400,7 @@ if (sendIntent.resolveActivity(getPackageManager()) != null) {
     }
     
    -

    Note: In this case, a URI is not used, but the intent's data type -is declared to specify the content carried by the extras.

    +

    When {@link android.content.Context#startActivity startActivity()} is called, the system @@ -393,7 +408,7 @@ examines all of the installed apps to determine which ones can handle this kind intent with the {@link android.content.Intent#ACTION_SEND} action and that carries "text/plain" data). If there's only one app that can handle it, that app opens immediately and is given the intent. If multiple activities accept the intent, the system -displays a dialog so the user can pick which app to use..

    +displays a dialog such as the one shown in Figure 2, so the user can pick which app to use.

    @@ -405,23 +420,26 @@ displays a dialog so the user can pick which app to use..

    When there is more than one app that responds to your implicit intent, the user can select which app to use and make that app the default choice for the -action. This is nice when performing an action for which the user -probably wants to use the same app from now on, such as when opening a web page (users -often prefer just one web browser) .

    +action. The ability to select a default is helpful when performing an action for which the user +probably wants to use the same app every time, such as when opening a web page (users +often prefer just one web browser).

    However, if multiple apps can respond to the intent and the user might want to use a different app each time, you should explicitly show a chooser dialog. The chooser dialog asks the -user to select which app to use for the action every time (the user cannot select a default app for +user to select which app to use for the action (the user cannot select a default app for the action). For example, when your app performs "share" with the {@link android.content.Intent#ACTION_SEND} action, users may want to share using a different app depending -on their current situation, so you should always use the chooser dialog, as shown in figure 2.

    +on their current situation, so you should always use the chooser dialog, as shown in Figure 2.

    To show the chooser, create an {@link android.content.Intent} using {@link android.content.Intent#createChooser createChooser()} and pass it to {@link -android.app.Activity#startActivity startActivity()}. For example:

    +android.app.Activity#startActivity startActivity()}, as shown in the following example. + This example displays a dialog with a list of apps that respond to the intent passed to the {@link +android.content.Intent#createChooser createChooser()} method and uses the supplied text as the +dialog title.

     Intent sendIntent = new Intent(Intent.ACTION_SEND);
    @@ -439,26 +457,16 @@ if (sendIntent.resolveActivity(getPackageManager()) != null) {
     }
     
    -

    This displays a dialog with a list of apps that respond to the intent passed to the {@link -android.content.Intent#createChooser createChooser()} method and uses the supplied text as the -dialog title.

    - - - - - - - -

    Receiving an Implicit Intent

    +

    Receiving an implicit intent

    To advertise which implicit intents your app can receive, declare one or more intent filters for each of your app components with an {@code } +"{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code <intent-filter>} element in your manifest file. Each intent filter specifies the type of intents it accepts based on the intent's action, -data, and category. The system will deliver an implicit intent to your app component only if the +data, and category. The system delivers an implicit intent to your app component only if the intent can pass through one of your intent filters.

    Note: An explicit intent is always delivered to its target, @@ -471,28 +479,28 @@ it inspects the {@link android.content.Intent} and decides how to behave based o in the {@link android.content.Intent} (such as to show the editor controls or not).

    Each intent filter is defined by an {@code } +href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code <intent-filter>} element in the app's manifest file, nested in the corresponding app component (such -as an {@code } +as an {@code <activity>} element). Inside the {@code }, +href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code <intent-filter>}, you can specify the type of intents to accept using one or more of these three elements:

    -
    {@code }
    +
    {@code <action>}
    Declares the intent action accepted, in the {@code name} attribute. The value must be the literal string value of an action, not the class constant.
    -
    {@code }
    +
    {@code <data>}
    Declares the type of data accepted, using one or more attributes that specify various aspects of the data URI (scheme, host, port, - path, etc.) and MIME type.
    -
    {@code }
    + path) and MIME type.
    +
    {@code <category>}
    Declares the intent category accepted, in the {@code name} attribute. The value must be the literal string value of an action, not the class constant. -

    Note: In order to receive implicit intents, you - must include the +

    Note: To receive implicit intents, you + must include the {@link android.content.Intent#CATEGORY_DEFAULT} category in the intent filter. The methods {@link android.app.Activity#startActivity startActivity()} and {@link android.app.Activity#startActivityForResult startActivityForResult()} treat all intents @@ -515,12 +523,12 @@ of these three elements:

    </activity>
  6. -

    It's okay to create a filter that includes more than one instance of -{@code }, -{@code }, or -{@code }. -If you do, you simply need to be certain that the component can handle any and all combinations -of those filter elements.

    +

    You can create a filter that includes more than one instance of +{@code <action>}, +{@code <data>}, or +{@code <category>}. +If you do, you need to be certain that the component can handle any and all +combinations of those filter elements.

    When you want to handle multiple kinds of intents, but only in specific combinations of action, data, and category type, then you need to create multiple intent filters.

    @@ -569,8 +577,8 @@ is running.

    Example filters

    -

    To better understand some of the intent filter behaviors, look at the following snippet -from the manifest file of a social-sharing app.

    +

    To demonstrate some of the intent filter behaviors, here is an example +from the manifest file of a social-sharing app:

     <activity android:name="MainActivity">
    @@ -607,9 +615,9 @@ opens when the user initially launches the app with the launcher icon:

    indicates this is the main entry point and does not expect any intent data.
  7. The {@link android.content.Intent#CATEGORY_LAUNCHER} category indicates that this activity's icon should be placed in the system's app launcher. If the {@code } element + href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>} element does not specify an icon with {@code icon}, then the system uses the icon from the {@code } + href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>} element.
  8. These two must be paired together in order for the activity to appear in the app launcher.

    @@ -620,7 +628,7 @@ they can also enter {@code ShareActivity} directly from another app that issues intent matching one of the two intent filters.

    Note: The MIME type, -{@code +{@code application/vnd.google.panorama360+jpg}, is a special data type that specifies panoramic photos, which you can handle with the Google @@ -638,7 +646,7 @@ panorama APIs.

    -

    Using a Pending Intent

    +

    Using a pending intent

    A {@link android.app.PendingIntent} object is a wrapper around an {@link android.content.Intent} object. The primary purpose of a {@link android.app.PendingIntent} @@ -646,25 +654,25 @@ is to grant permission to a foreign application to use the contained {@link android.content.Intent} as if it were executed from your app's own process.

    -

    Major use cases for a pending intent include:

    +

    Major use cases for a pending intent include the following:

      -
    • Declare an intent to be executed when the user performs an action with your Declaring an intent to be executed when the user performs an action with your Notification (the Android system's {@link android.app.NotificationManager} executes the {@link android.content.Intent}). -
    • Declare an intent to be executed when the user performs an action with your +
    • Declaring an intent to be executed when the user performs an action with your App Widget (the Home screen app executes the {@link android.content.Intent}). -
    • Declare an intent to be executed at a specified time in the future (the Android +
    • Declaring an intent to be executed at a specified future time (the Android system's {@link android.app.AlarmManager} executes the {@link android.content.Intent}).
    -

    Because each {@link android.content.Intent} object is designed to be handled by a specific +

    Just as each {@link android.content.Intent} object is designed to be handled by a specific type of app component (either an {@link android.app.Activity}, a {@link android.app.Service}, or a {@link android.content.BroadcastReceiver}), so too must a {@link android.app.PendingIntent} be -created with the same consideration. When using a pending intent, your app will not +created with the same consideration. When using a pending intent, your app doesn't execute the intent with a call such as {@link android.content.Context#startActivity -startActivity()}. You must instead declare the intended component type when you create the +startActivity()}. Instead, you must declare the intended component type when you create the {@link android.app.PendingIntent} by calling the respective creator method:

      @@ -677,14 +685,14 @@ startActivity()}. You must instead declare the intended component type when you

    Unless your app is receiving pending intents from other apps, -the above methods to create a {@link android.app.PendingIntent} are the only -{@link android.app.PendingIntent} methods you'll probably ever need.

    +the above methods to create a {@link android.app.PendingIntent} are probably the only +{@link android.app.PendingIntent} methods you'll ever need.

    Each method takes the current app {@link android.content.Context}, the {@link android.content.Intent} you want to wrap, and one or more flags that specify how the intent should be used (such as whether the intent can be used more than once).

    -

    More information about using pending intents is provided with the documentation for each +

    For more information about using pending intents, see the documentation for each of the respective use cases, such as in the Notifications and App Widgets API guides.

    @@ -695,27 +703,27 @@ and App Widgets API g -

    Intent Resolution

    +

    Intent resolution

    When the system receives an implicit intent to start an activity, it searches for the -best activity for the intent by comparing the intent to intent filters based on three aspects:

    +best activity for the intent by comparing the it to intent filters based on three aspects:

      -
    • The intent action -
    • The intent data (both URI and data type) -
    • The intent category +
    • Action. +
    • Data (both URI and data type). +
    • Category.
    -

    The following sections describe how intents are matched to the appropriate component(s) -in terms of how the intent filter is declared in an app's manifest file.

    +

    The following sections describe how intents are matched to the appropriate components +according to the intent filter declaration in an app's manifest file.

    Action test

    To specify accepted intent actions, an intent filter can declare zero or more {@code -} elements. For example:

    +<action>} elements, as shown in the following example:

     <intent-filter>
    @@ -725,13 +733,13 @@ in terms of how the intent filter is declared in an app's manifest file.

    </intent-filter>
    -

    To get through this filter, the action specified in the {@link android.content.Intent} +

    To pass this filter, the action specified in the {@link android.content.Intent} must match one of the actions listed in the filter.

    If the filter does not list any actions, there is nothing for an intent to match, so all intents fail the test. However, if an {@link android.content.Intent} -does not specify an action, it will pass the test (as long as the filter -contains at least one action).

    +does not specify an action, it passes the test as long as the filter +contains at least one action.

    @@ -739,7 +747,7 @@ contains at least one action).

    To specify accepted intent categories, an intent filter can declare zero or more {@code -} elements. For example:

    +} elements, as shown in the following example:

     <intent-filter>
    @@ -752,17 +760,17 @@ contains at least one action).

    For an intent to pass the category test, every category in the {@link android.content.Intent} must match a category in the filter. The reverse is not necessary—the intent filter may declare more categories than are specified in the {@link android.content.Intent} and the -{@link android.content.Intent} will still pass. Therefore, an intent with no categories should -always pass this test, regardless of what categories are declared in the filter.

    +{@link android.content.Intent} still passes. Therefore, an intent with no categories +always passes this test, regardless of what categories are declared in the filter.

    Note: -Android automatically applies the the {@link android.content.Intent#CATEGORY_DEFAULT} category +Android automatically applies the {@link android.content.Intent#CATEGORY_DEFAULT} category to all implicit intents passed to {@link android.content.Context#startActivity startActivity()} and {@link android.app.Activity#startActivityForResult startActivityForResult()}. -So if you want your activity to receive implicit intents, it must -include a category for {@code "android.intent.category.DEFAULT"} in its intent filters (as -shown in the previous {@code } example.

    +If you want your activity to receive implicit intents, it must +include a category for {@code "android.intent.category.DEFAULT"} in its intent filters, as +shown in the previous {@code <intent-filter>} example.

    @@ -770,7 +778,7 @@ shown in the previous {@code } example.

    To specify accepted intent data, an intent filter can declare zero or more {@code -} elements. For example:

    +<data>} elements, as shown in the following example:

     <intent-filter>
    @@ -781,15 +789,16 @@ shown in the previous {@code } example.

    Each <data> -element can specify a URI structure and a data type (MIME media type). There are separate -attributes — {@code scheme}, {@code host}, {@code port}, -and {@code path} — for each part of the URI: +element can specify a URI structure and a data type (MIME media type). + Each part of the URI is a separate +attribute: {@code scheme}, {@code host}, {@code port}, +and {@code path}:

    -

    {@code ://:/}

    +

    {@code <scheme>://<host>:<port>/<path>}

    -For example: +The following example shows possible values for these attributes:

    {@code content://com.example.project:200/folder/subfolder/etc}

    @@ -799,7 +808,7 @@ the port is {@code 200}, and the path is {@code folder/subfolder/etc}.

    Each of these attributes is optional in a {@code } element, +href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>} element, but there are linear dependencies:

    • If a scheme is not specified, the host is ignored.
    • @@ -842,17 +851,17 @@ type matches a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a {@code content:} or {@code file:} URI and the filter does not specify a URI. In other words, a component is presumed to support {@code content:} and {@code file:} data if -its filter lists only a MIME type.

      +its filter lists only a MIME type.

This last rule, rule (d), reflects the expectation that components are able to get local data from a file or content provider. -Therefore, their filters can list just a data type and do not need to explicitly +Therefore, their filters can list just a data type and don't need to explicitly name the {@code content:} and {@code file:} schemes. -This is a typical case. A {@code } element -like the following, for example, tells Android that the component can get image data from a content +The following example shows a typical case in which a {@code <data>} element + tells Android that the component can get image data from a content provider and display it:

@@ -863,14 +872,15 @@ provider and display it: </intent-filter>

-Because most available data is dispensed by content providers, filters that -specify a data type but not a URI are perhaps the most common. +Filters that +specify a data type but not a URI are perhaps the most common because most available + data is dispensed by content providers.

-Another common configuration is filters with a scheme and a data type. For +Another common configuration is a filter with a scheme and a data type. For example, a {@code } +href="{@docRoot}guide/topics/manifest/data-element.html">{@code <data>} element like the following tells Android that the component can retrieve video data from the network in order to perform the action:

@@ -894,7 +904,7 @@ by finding all the activities with intent filters that specify the

Your application can use intent matching in a similar way. The {@link android.content.pm.PackageManager} has a set of {@code query...()} -methods that return all components that can accept a particular intent, and +methods that return all components that can accept a particular intent and a similar series of {@code resolve...()} methods that determine the best component to respond to an intent. For example, {@link android.content.pm.PackageManager#queryIntentActivities @@ -907,7 +917,3 @@ can respond. There's a similar method, {@link android.content.pm.PackageManager#queryBroadcastReceivers queryBroadcastReceivers()}, for broadcast receivers.

- - - - diff --git a/docs/html/guide/components/services.jd b/docs/html/guide/components/services.jd index e646a17a18a7..a7ed7186e1fb 100644 --- a/docs/html/guide/components/services.jd +++ b/docs/html/guide/components/services.jd @@ -5,11 +5,11 @@ page.title=Services

    In this document

      -
    1. The Basics
    2. +
    3. The basics
      1. Declaring a service in the manifest
      -
    4. Creating a Started Service +
    5. Creating a started service
      1. Extending the IntentService class
      2. Extending the Service class
      3. @@ -17,10 +17,10 @@ page.title=Services
      4. Stopping a service
    6. -
    7. Creating a Bound Service
    8. -
    9. Sending Notifications to the User
    10. -
    11. Running a Service in the Foreground
    12. -
    13. Managing the Lifecycle of a Service +
    14. Creating a bound service
    15. +
    16. Sending notifications to the user
    17. +
    18. Running a service in the foreground
    19. +
    20. Managing the lifecycle of a service
      1. Implementing the lifecycle callbacks
      @@ -48,70 +48,80 @@ page.title=Services -

      A {@link android.app.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 +long-running operations in the background, and it does not provide a user interface. Another +application component can start a service, and it continues 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 +interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

      -

      A service can essentially take two forms:

      +

      These are the three different types of services:

      +
      Scheduled
      +
      A service is scheduled when an API such as the {@link android.app.job.JobScheduler}, + introduced in Android 5.0 (API level 21), launches the service. You can use the + {@link android.app.job.JobScheduler} by registering jobs and specifying their requirements for + network and timing. The system then gracefully schedules the jobs for execution at the + appropriate times. The {@link android.app.job.JobScheduler} provides many methods to define + service-execution conditions. +

      Note: If your app targets Android 5.0 (API level 21), Google + recommends that you use the {@link android.app.job.JobScheduler} to execute background + services. For more information about using this class, see the + {@link android.app.job.JobScheduler} reference documentation.

      Started
      -
      A service is "started" when an application component (such as an activity) starts it by -calling {@link android.content.Context#startService 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.
      +
      A service is started when an application component (such as an activity) + calls {@link android.content.Context#startService startService()}. After it's 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 can download or upload a file over the network. When the operation is + complete, the service should stop itself.
      Bound
      -
      A service is "bound" when an application component binds to it by calling {@link -android.content.Context#bindService 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.
      +
      A service is bound when an application component binds to it by calling {@link + android.content.Context#bindService bindService()}. A bound service offers a client-server + interface that allows components to interact with the service, send requests, receive 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.
      -

      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: {@link +

      Although this documentation generally discusses started and bound 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 of callback methods: {@link android.app.Service#onStartCommand onStartCommand()} to allow components to start it and {@link android.app.Service#onBind onBind()} to allow binding.

      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 +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 {@link android.content.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 +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.

      - +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. If +your service is going to perform any CPU-intensive work or blocking operations, such as MP3 +playback or networking, you should create a new thread within the service to complete that work. +By using a separate thread, you can reduce the risk of Application Not Responding (ANR) errors, +and the application's main thread can remain dedicated to user interaction with your +activities.

      -

      The Basics

      +

      The basics

      -

      To create a service, you must create a subclass of {@link android.app.Service} (or one -of its existing subclasses). In your implementation, you need to override some callback methods that -handle key aspects of the service lifecycle and provide a mechanism for components to bind to -the service, if appropriate. The most important callback methods you should override are:

      +

      To create a service, you must create a subclass of {@link android.app.Service} or use one +of its existing subclasses. In your implementation, you must override some callback methods that +handle key aspects of the service lifecycle and provide a mechanism that allows the components to +bind to the service, if appropriate. These are the most important callback methods that you should +override:

      {@link android.app.Service#onStartCommand onStartCommand()}
      -
      The system calls this method when another component, such as an activity, -requests that the service be started, by calling {@link android.content.Context#startService -startService()}. Once this method executes, the service is started and can run in the +
      The system invokes this method by calling {@link android.content.Context#startService +startService()} when another component (such as an activity) requests that the service be started. +When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when -its work is done, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link -android.content.Context#stopService stopService()}. (If you only want to provide binding, you don't -need to implement this method.)
      +its work is complete by calling {@link android.app.Service#stopSelf stopSelf()} or {@link +android.content.Context#stopService stopService()}. If you only want to provide binding, you don't +need to implement this method.
      {@link android.app.Service#onBind onBind()}
      -
      The system calls this method when another component wants to bind with the -service (such as to perform RPC), by calling {@link android.content.Context#bindService -bindService()}. In your implementation of this method, you must provide an interface that clients -use to communicate with the service, by returning an {@link android.os.IBinder}. You must always -implement this method, but if you don't want to allow binding, then you should return null.
      +
      The system invokes this method by calling {@link android.content.Context#bindService +bindService()} when another component wants to bind with the service (such as to perform RPC). +In your implementation of this method, you must provide an interface that clients +use to communicate with the service by returning an {@link android.os.IBinder}. You must always +implement this method; however, if you don't want to allow binding, you should return +null.
      {@link android.app.Service#onCreate()}
      -
      The system calls this method when the service is first created, to perform one-time setup -procedures (before it calls either {@link android.app.Service#onStartCommand onStartCommand()} or +
      The system invokes this method to perform one-time setup procedures when the service is +initially created (before it calls either +{@link android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}). If the service is already running, this method is not called.
      {@link android.app.Service#onDestroy()}
      -
      The system calls this method when the service is no longer used and is being destroyed. +
      The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered -listeners, receivers, etc. This is the last call the service receives.
      +listeners, or receivers. This is the last call that the service receives.

      If a component starts the service by calling {@link android.content.Context#startService startService()} (which results in a call to {@link -android.app.Service#onStartCommand onStartCommand()}), then the service -remains running until it stops itself with {@link android.app.Service#stopSelf()} or another +android.app.Service#onStartCommand onStartCommand()}), the service +continues to run until it stops itself with {@link android.app.Service#stopSelf()} or another component stops it by calling {@link android.content.Context#stopService stopService()}.

      If a component calls -{@link android.content.Context#bindService bindService()} to create the service (and {@link -android.app.Service#onStartCommand onStartCommand()} is not called), then the service runs -only as long as the component is bound to it. Once the service is unbound from all clients, the -system destroys it.

      +{@link android.content.Context#bindService bindService()} to create the service and {@link +android.app.Service#onStartCommand onStartCommand()} is not called, the service runs +only as long as the component is bound to it. After the service is unbound from all of its clients, +the system destroys it.

      -

      The Android system will force-stop a service only when memory is low and it must recover system +

      The Android system force-stops 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 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 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 +focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed. +If the service is started and is long-running, the system lowers its position +in the list of background tasks over time, and the service becomes highly susceptible to +killing—if your service is started, 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 from {@link -android.app.Service#onStartCommand onStartCommand()}, as discussed later). For more information +available, but this also depends on the value that you return from {@link +android.app.Service#onStartCommand onStartCommand()}. For more information about when the system might destroy a service, see the Processes and Threading document.

      -

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

      - - +

      In the following sections, you'll see how you can create the +{@link android.content.Context#startService startService()} and +{@link android.content.Context#bindService bindService()} service methods, as well as how to use +them from other application components.

      Declaring a service in the manifest

      -

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

      +

      You must declare all services in your application's +manifest file, just as you do for activities and other components.

      To declare your service, add a {@code } element +href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>} element as a child of the {@code } -element. For example:

      +href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>} +element. Here is an example:

       <manifest ... >
      @@ -205,48 +218,44 @@ element. For example:

      See the {@code } element +href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>} element reference for more information about declaring your service in the manifest.

      -

      There are other attributes you can include in the {@code } element to -define properties such as permissions required to start the service and the process in +

      There are other attributes that you can include in the {@code <service>} element to +define properties such as the permissions that are required to start the service and the process in which the service should run. The {@code android:name} -attribute is the only required attribute—it specifies the class name of the service. Once -you publish your application, you should not change this name, because if you do, you risk breaking +attribute is the only required attribute—it specifies the class name of the service. After +you publish your application, leave this name unchanged to avoid the risk of breaking code due to dependence on explicit intents to start or bind the service (read the blog post, Things That Cannot Change). -

      To ensure your app is secure, always use an explicit intent when starting or binding -your {@link android.app.Service} and do not declare intent filters for the service. If -it's critical that you allow for some amount of ambiguity as to which service starts, you can -supply intent filters for your services and exclude the component name from the {@link -android.content.Intent}, but you then must set the package for the intent with {@link -android.content.Intent#setPackage setPackage()}, which provides sufficient disambiguation for the -target service.

      +

      Caution: To ensure that your app is secure, always use an +explicit intent when starting a {@link android.app.Service} and do not declare intent filters for +your services. Using an implicit intent to start a service is a security hazard because you cannot +be certain of the service that will respond to the intent, and the user cannot see which service +starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call +{@link android.content.Context#bindService bindService()} with an implicit intent.

      -

      Additionally, you can ensure that your service is available to only your app by +

      You can ensure that your service is available to only your app by including the {@code android:exported} -attribute and setting it to {@code "false"}. This effectively stops other apps from starting your +attribute and setting it to {@code false}. This effectively stops other apps from starting your service, even when using an explicit intent.

      - - - -

      Creating a Started Service

      +

      Creating a started service

      A started service is one that another component starts by calling {@link -android.content.Context#startService startService()}, resulting in a call to the service's +android.content.Context#startService startService()}, which results in a call to the service's {@link android.app.Service#onStartCommand onStartCommand()} method.

      When a service is started, it has a lifecycle that's independent of the -component that started it and the service can run in the background indefinitely, even if +component that started it. The service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job -is done by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it -by calling {@link android.content.Context#stopService stopService()}.

      +is complete by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can +stop it by calling {@link android.content.Context#stopService stopService()}.

      An application component such as an activity can start the service by calling {@link android.content.Context#startService startService()} and passing an {@link android.content.Intent} @@ -254,65 +263,65 @@ that specifies the service and includes any data for the service to use. The ser this {@link android.content.Intent} in the {@link android.app.Service#onStartCommand onStartCommand()} method.

      -

      For instance, suppose an activity needs to save some data to an online database. The activity can -start a companion service and deliver it the data to save by passing an intent to {@link +

      For instance, suppose an activity needs to save some data to an online database. The activity +can start a companion service and deliver it the data to save by passing an intent to {@link android.content.Context#startService startService()}. The service receives the intent in {@link -android.app.Service#onStartCommand onStartCommand()}, connects to the Internet and performs the -database transaction. When the transaction is done, the service stops itself and it is +android.app.Service#onStartCommand onStartCommand()}, connects to the Internet, and performs the +database transaction. When the transaction is complete, the service stops itself and is destroyed.

      Caution: A service runs in the same process as the application -in which it is declared and in the main thread of that application, by default. So, if your service +in which it is declared and in the main thread of that application by default. 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.

      +application, the service slows down activity performance. To avoid impacting application +performance, start a new thread inside the service.

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

      +
      {@link android.app.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 +
      This is the base class for all services. When you extend this class, it's important to +create a new thread in which the service can complete all of its work; the service uses your +application's main thread by default, which can slow the performance of any activity that your application is running.
      {@link android.app.IntentService}
      -
      This is a subclass of {@link android.app.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 {@link +
      This is a subclass of {@link android.app.Service} that uses a worker thread to handle all of +the start requests, one at a time. This is the best option if you don't require that your service +handle multiple requests simultaneously. Implement {@link android.app.IntentService#onHandleIntent onHandleIntent()}, which receives the intent for each -start request so you can do the background work.
      +start request so that you can complete the background work.

      The following sections describe how you can implement your service using either one for these classes.

      -

      Extending the IntentService class

      -

      Because most 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 +

      Because most of the started services don't need to handle multiple requests simultaneously +(which can actually be a dangerous multi-threading scenario), it's best that you implement your service using the {@link android.app.IntentService} class.

      -

      The {@link android.app.IntentService} does the following:

      +

      The {@link android.app.IntentService} class does the following:

        -
      • Creates a default worker thread that executes all intents delivered to {@link -android.app.Service#onStartCommand onStartCommand()} separate from your application's main +
      • It creates a default worker thread that executes all of the intents that are delivered to +{@link android.app.Service#onStartCommand onStartCommand()}, separate from your application's main thread.
      • Creates a work queue that passes one intent at a time to your {@link android.app.IntentService#onHandleIntent 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 +
      • Stops the service after all of the start requests are handled, so you never have to call {@link android.app.Service#stopSelf}.
      • -
      • Provides default implementation of {@link android.app.IntentService#onBind onBind()} that -returns null.
      • +
      • Provides a default implementation of {@link android.app.IntentService#onBind onBind()} + that returns null.
      • Provides a default implementation of {@link android.app.IntentService#onStartCommand onStartCommand()} that sends the intent to the work queue and then to your {@link android.app.IntentService#onHandleIntent onHandleIntent()} implementation.
      -

      All this adds up to the fact that all you need to do is implement {@link -android.app.IntentService#onHandleIntent onHandleIntent()} to do the work provided by the -client. (Though, you also need to provide a small constructor for the service.)

      +

      To complete the work that is provided by the client, implement {@link +android.app.IntentService#onHandleIntent onHandleIntent()}. +However, you also need to provide a small constructor for the service.

      Here's an example implementation of {@link android.app.IntentService}:

      @@ -352,12 +361,12 @@ android.app.IntentService#onHandleIntent onHandleIntent()}.

      If you decide to also override other callback methods, such as {@link android.app.IntentService#onCreate onCreate()}, {@link android.app.IntentService#onStartCommand onStartCommand()}, or {@link -android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation, so +android.app.IntentService#onDestroy onDestroy()}, be sure to call the super implementation so that the {@link android.app.IntentService} can properly handle the life of the worker thread.

      For example, {@link android.app.IntentService#onStartCommand onStartCommand()} must return -the default implementation (which is how the intent gets delivered to {@link -android.app.IntentService#onHandleIntent onHandleIntent()}):

      +the default implementation, which is how the intent is delivered to {@link +android.app.IntentService#onHandleIntent onHandleIntent()}:

       @Override
      @@ -369,22 +378,21 @@ public int onStartCommand(Intent intent, int flags, int startId) {
       
       

      Besides {@link android.app.IntentService#onHandleIntent onHandleIntent()}, the only method from which you don't need to call the super class is {@link android.app.IntentService#onBind -onBind()} (but you only need to implement that if your service allows binding).

      +onBind()}. You need to implement this only if your service allows binding.

      In the next section, you'll see how the same kind of service is implemented when extending -the base {@link android.app.Service} class, which is a lot more code, but which might be +the base {@link android.app.Service} class, which uses more code, but might be appropriate if you need to handle simultaneous start requests.

      -

      Extending the Service class

      -

      As you saw in the previous section, using {@link android.app.IntentService} makes your +

      Using {@link android.app.IntentService} makes your implementation of a started service very simple. If, however, you require your service to -perform multi-threading (instead of processing start requests through a work queue), then you +perform multi-threading (instead of processing start requests through a work queue), you can extend the {@link android.app.Service} class to handle each intent.

      -

      For comparison, the following example code is an implementation of the {@link -android.app.Service} class that performs the exact same work as the example above using {@link +

      For comparison, the following example code shows an implementation of the {@link +android.app.Service} class that performs the same work as the previous example using {@link android.app.IntentService}. That is, for each start request, it uses a worker thread to perform the job and processes only one request at a time.

      @@ -460,20 +468,20 @@ public class HelloService extends Service {

      However, because you handle each call to {@link android.app.Service#onStartCommand onStartCommand()} yourself, you can perform 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 -request and run them right away (instead of waiting for the previous request to finish).

      +this example does, but if that's what you want, you can create a new thread for each +request and run them right away instead of waiting for the previous request to finish.

      Notice that the {@link android.app.Service#onStartCommand 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 {@link -android.app.IntentService} handles this for you, though you are able to modify it). The return value +event that the system kills it. The default implementation for {@link +android.app.IntentService} handles this for you, but you are able to modify it. The return value from {@link android.app.Service#onStartCommand onStartCommand()} must be one of the following constants:

      {@link android.app.Service#START_NOT_STICKY}
      If the system kills the service after {@link android.app.Service#onStartCommand -onStartCommand()} returns, do not recreate the service, unless there are pending +onStartCommand()} returns, do not recreate the service unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.
      {@link android.app.Service#START_STICKY}
      @@ -481,9 +489,9 @@ and when your application can simply restart any unfinished jobs. onStartCommand()} returns, recreate the service and call {@link android.app.Service#onStartCommand onStartCommand()}, but do not redeliver the last intent. Instead, the system calls {@link android.app.Service#onStartCommand onStartCommand()} with a -null intent, unless there were pending intents to start the service, in which case, +null intent unless there are pending intents to start the service. In that case, those intents are delivered. This is suitable for media players (or similar services) that are not -executing commands, but running indefinitely and waiting for a job. +executing commands but are running indefinitely and waiting for a job.
      {@link android.app.Service#START_REDELIVER_INTENT}
      If the system kills the service after {@link android.app.Service#onStartCommand onStartCommand()} returns, recreate the service and call {@link @@ -494,35 +502,35 @@ actively performing a job that should be immediately resumed, such as downloadin

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

      - - -

      Starting a Service

      +

      Starting a service

      You can start a service from an activity or other application component by passing an {@link android.content.Intent} (specifying the service to start) to {@link android.content.Context#startService startService()}. The Android system calls the service's {@link android.app.Service#onStartCommand onStartCommand()} method and passes it the {@link -android.content.Intent}. (You should never call {@link android.app.Service#onStartCommand -onStartCommand()} directly.)

      +android.content.Intent}. + +

      Note: Never call +{@link android.app.Service#onStartCommand onStartCommand()} directly.

      For example, an activity can start the example service in the previous section ({@code HelloService}) using an explicit intent with {@link android.content.Context#startService -startService()}:

      +startService()}, as shown here:

       Intent intent = new Intent(this, HelloService.class);
       startService(intent);
       
      -

      The {@link android.content.Context#startService startService()} method returns immediately and +

      The {@link android.content.Context#startService startService()} method returns immediately, and the Android system calls the service's {@link android.app.Service#onStartCommand onStartCommand()} method. If the service is not already running, the system first calls {@link -android.app.Service#onCreate onCreate()}, then calls {@link android.app.Service#onStartCommand -onStartCommand()}.

      +android.app.Service#onCreate onCreate()}, and then it calls +{@link android.app.Service#onStartCommand onStartCommand()}.

      -

      If the service does not also provide binding, the intent delivered with {@link +

      If the service does not also provide binding, the intent that is delivered with {@link android.content.Context#startService startService()} is the only mode of communication between the -application component and the service. However, if you want the service to send a result back, then +application component and the service. However, if you want the service to send a result back, the client that starts the service can create a {@link android.app.PendingIntent} for a broadcast (with {@link android.app.PendingIntent#getBroadcast getBroadcast()}) and deliver it to the service in the {@link android.content.Intent} that starts the service. The service can then use the @@ -533,109 +541,102 @@ broadcast to deliver a result.

      the service (with {@link android.app.Service#stopSelf stopSelf()} or {@link android.content.Context#stopService stopService()}) is required to stop it.

      -

      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 after {@link android.app.Service#onStartCommand onStartCommand()} returns. So, -the service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()} or another +continues to run after {@link android.app.Service#onStartCommand onStartCommand()} returns. The +service must stop itself by calling {@link android.app.Service#stopSelf stopSelf()}, or another component can stop it by calling {@link android.content.Context#stopService stopService()}.

      Once requested to stop with {@link android.app.Service#stopSelf stopSelf()} or {@link android.content.Context#stopService stopService()}, the system destroys the service as soon as possible.

      -

      However, if your service handles multiple requests to {@link -android.app.Service#onStartCommand onStartCommand()} concurrently, then you shouldn't stop the -service when you're done processing a start request, because you might have since received a new +

      If your service handles multiple requests to {@link +android.app.Service#onStartCommand onStartCommand()} concurrently, you shouldn't stop the +service when you're done processing a start request, as you might have received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use {@link android.app.Service#stopSelf(int)} to ensure that your request to stop the service is always based on the most recent start request. That is, when you call {@link android.app.Service#stopSelf(int)}, you pass the ID of the start request (the startId delivered to {@link android.app.Service#onStartCommand onStartCommand()}) to which your stop request -corresponds. Then if the service received a new start request before you were able to call {@link -android.app.Service#stopSelf(int)}, then the ID will not match and the service will not stop.

      +corresponds. Then, if the service receives a new start request before you are able to call {@link +android.app.Service#stopSelf(int)}, the ID does not match and the service does not stop.

      -

      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 calling {@link +

      Caution: To avoid wasting system resources and consuming +battery power, ensure that your application stops its services when it's done working. +If necessary, other components can stop the service by calling {@link android.content.Context#stopService stopService()}. Even if you enable binding for the service, -you must always stop the service yourself if it ever received a call to {@link +you must always stop the service yourself if it ever receives a call to {@link android.app.Service#onStartCommand onStartCommand()}.

      For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.

      - - -

      Creating a Bound Service

      +

      Creating a bound service

      A bound service is one that allows application components to bind to it by calling {@link -android.content.Context#bindService bindService()} in order to create a long-standing connection -(and generally does not allow components to start it by calling {@link -android.content.Context#startService startService()}).

      +android.content.Context#bindService bindService()} to create a long-standing connection. +It generally doesn't allow components to start it by calling {@link +android.content.Context#startService startService()}.

      -

      You should create a bound service when you want to interact with the service from activities +

      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).

      +other applications through interprocess communication (IPC).

      -

      To create a bound service, you must implement the {@link +

      To create a bound service, implement the {@link android.app.Service#onBind onBind()} callback method to return an {@link android.os.IBinder} that defines the interface for communication with the service. Other application components can then call {@link android.content.Context#bindService 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 {@link android.app.Service#onStartCommand onStartCommand()}).

      +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 same way that you must when the service is +started through {@link android.app.Service#onStartCommand onStartCommand()}.

      -

      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 +

      To create a bound service, you must 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 {@link android.os.IBinder} and is what your service must return from the {@link android.app.Service#onBind -onBind()} callback method. Once the client receives the {@link android.os.IBinder}, it can begin +onBind()} callback method. After the client receives the {@link android.os.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 {@link android.content.Context#unbindService unbindService()} to unbind. Once -there are no clients bound to the service, the system destroys the service.

      +

      Multiple clients can bind to the service simultaneously. When a client is done interacting with +the service, it calls {@link android.content.Context#unbindService unbindService()} to unbind. +When 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 There are multiple ways to implement a bound service, and the implementation is more +complicated than a started service. For these reasons, the bound service discussion appears in a +separate document about Bound Services.

      +

      Sending notifications to the user

      - -

      Sending Notifications to the User

      - -

      Once running, a service can notify the user of events using When a service is running, it can notify the user of events using Toast Notifications or Status Bar Notifications.

      -

      A toast notification is a message that appears on the surface of the current window for a -moment then disappears, while a status bar notification provides an icon in the status bar with a +

      A toast notification is a message that appears on the surface of the current window for only a +moment before disappearing. A status bar notification provides an icon in the status bar with a message, which the user can select in order to take an action (such as start an activity).

      -

      Usually, a status bar notification is the best technique when some background work has completed -(such as a file completed -downloading) and the user can now act on it. When the user selects the notification from the -expanded view, the notification can start an activity (such as to view the downloaded file).

      +

      Usually, a status bar notification is the best technique to use when background work such as +a file download has completed, and the user can now act on it. When the user +selects the notification from the expanded view, the notification can start an activity +(such as to display the downloaded file).

      See the Toast Notifications or Status Bar Notifications developer guides for more information.

      +

      Running a service in the foreground

      - -

      Running a Service in the Foreground

      - -

      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 +

      A foreground service is a service that the +user is actively aware of and is 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.

      +Ongoing heading. This means that the notification cannot be dismissed unless the service +is either stopped or removed from the foreground.

      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 @@ -643,9 +644,9 @@ of its operation. The notification in the status bar might indicate the current the user to launch an activity to interact with the music player.

      To request that your service run in the foreground, call {@link -android.app.Service#startForeground startForeground()}. This method takes two parameters: an integer -that uniquely identifies the notification and the {@link -android.app.Notification} for the status bar. For example:

      +android.app.Service#startForeground startForeground()}. This method takes two parameters: an +integer that uniquely identifies the notification and the {@link +android.app.Notification} for the status bar. Here is an example:

       Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
      @@ -657,30 +658,27 @@ notification.setLatestEventInfo(this, getText(R.string.notification_title),
       startForeground(ONGOING_NOTIFICATION_ID, notification);
       
      -

      Caution: The integer ID you give to {@link +

      Caution: The integer ID that you give to {@link android.app.Service#startForeground startForeground()} must not be 0.

      -

      To remove the service from the foreground, call {@link -android.app.Service#stopForeground stopForeground()}. This method takes a boolean, indicating +android.app.Service#stopForeground stopForeground()}. This method takes a boolean, which indicates 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 +service. However, if you stop the service while it's still running in the foreground, the notification is also removed.

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

      +

      Managing the lifecycle of a service

      +

      The lifecycle of a service is much simpler than that of an activity. However, it's even more +important that you pay close attention to how your service is created and destroyed because a +service can run in the background without the user being aware.

      -

      Managing the Lifecycle of a Service

      - -

      The lifecycle of a service is much simpler than that of an activity. However, it's even more important -that you pay close attention to how your service is created and destroyed, because a service -can run in the background without the user being aware.

      - -

      The service lifecycle—from when it's created to when it's destroyed—can follow two -different paths:

      +

      The service lifecycle—from when it's created to when it's destroyed—can follow +either of these two paths:

      • A started service @@ -689,27 +687,26 @@ android.content.Context#startService startService()}. The service then runs inde stop itself by calling {@link android.app.Service#stopSelf() stopSelf()}. Another component can also stop the service by calling {@link android.content.Context#stopService -stopService()}. When the service is stopped, the system destroys it..

      • +stopService()}. When the service is stopped, the system destroys it.

      • A bound service

        The service is created when another component (a client) calls {@link android.content.Context#bindService bindService()}. The client then communicates with the service through an {@link android.os.IBinder} interface. The client can close the connection by calling {@link android.content.Context#unbindService unbindService()}. Multiple clients can bind to -the same service and when all of them unbind, the system destroys the service. (The service -does not need to stop itself.)

      • +the same service and when all of them unbind, the system destroys the service. The service +does not need to stop itself.

      -

      These two paths are not entirely separate. That is, you can bind to a service that was already -started with {@link android.content.Context#startService startService()}. For example, a background -music service could be started by calling {@link android.content.Context#startService +

      These two paths are not entirely separate. You can bind to a service that is already +started with {@link android.content.Context#startService startService()}. For example, you can +start a background music service by calling {@link android.content.Context#startService startService()} with an {@link android.content.Intent} that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling {@link -android.content.Context#bindService bindService()}. In cases like this, {@link +android.content.Context#bindService bindService()}. In cases such as this, {@link android.content.Context#stopService stopService()} or {@link android.app.Service#stopSelf -stopSelf()} does not actually stop the service until all clients unbind.

      - +stopSelf()} doesn't actually stop the service until all of the clients unbind.

      Implementing the lifecycle callbacks

      @@ -763,20 +760,30 @@ shows the lifecycle when the service is created with {@link android.content.Cont startService()} and the diagram on the right shows the lifecycle when the service is created with {@link android.content.Context#bindService bindService()}.

      -

      By implementing these methods, you can monitor two nested loops of the service's lifecycle:

      +

      Figure 2 illustrates the typical callback methods for a service. Although the figure separates +services that are created by {@link android.content.Context#startService startService()} from those +created by {@link android.content.Context#bindService bindService()}, keep +in mind that any service, no matter how it's started, can potentially allow clients to bind to it. +A service that was initially started with {@link android.app.Service#onStartCommand +onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) +can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls +{@link android.content.Context#bindService bindService()}).

      + +

      By implementing these methods, you can monitor these two nested loops of the service's +lifecycle:

        -
      • The entire lifetime of a service happens between the time {@link -android.app.Service#onCreate onCreate()} is called and the time {@link +
      • The entire lifetime of a service occurs between the time that {@link +android.app.Service#onCreate onCreate()} is called and the time that {@link android.app.Service#onDestroy} returns. Like an activity, a service does its initial setup in {@link android.app.Service#onCreate onCreate()} and releases all remaining resources in {@link -android.app.Service#onDestroy onDestroy()}. For example, a -music playback service could create the thread where the music will be played in {@link -android.app.Service#onCreate onCreate()}, then stop the thread in {@link +android.app.Service#onDestroy onDestroy()}. For example, a +music playback service can create the thread where the music is played in {@link +android.app.Service#onCreate onCreate()}, and then it can stop the thread in {@link android.app.Service#onDestroy onDestroy()}. -

        The {@link android.app.Service#onCreate onCreate()} and {@link android.app.Service#onDestroy -onDestroy()} methods are called for all services, whether +

        Note: The {@link android.app.Service#onCreate onCreate()} +and {@link android.app.Service#onDestroy onDestroy()} methods are called for all services, whether they're created by {@link android.content.Context#startService startService()} or {@link android.content.Context#bindService bindService()}.

      • @@ -784,8 +791,8 @@ android.content.Context#bindService bindService()}.

        android.app.Service#onStartCommand onStartCommand()} or {@link android.app.Service#onBind onBind()}. Each method is handed the {@link android.content.Intent} that was passed to either {@link android.content.Context#startService -startService()} or {@link android.content.Context#bindService bindService()}, respectively. -

        If the service is started, the active lifetime ends the same time that the entire lifetime +startService()} or {@link android.content.Context#bindService bindService()}. +

        If the service is started, the active lifetime ends at the same time that the entire lifetime ends (the service is still active even after {@link android.app.Service#onStartCommand onStartCommand()} returns). If the service is bound, the active lifetime ends when {@link android.app.Service#onUnbind onUnbind()} returns.

        @@ -795,26 +802,16 @@ android.app.Service#onUnbind onUnbind()} returns.

        Note: Although a started service is stopped by a call to either {@link android.app.Service#stopSelf stopSelf()} or {@link android.content.Context#stopService stopService()}, there is not a respective callback for the -service (there's no {@code onStop()} callback). So, unless the service is bound to a client, +service (there's no {@code onStop()} callback). Unless the service is bound to a client, the system destroys it when the service is stopped—{@link android.app.Service#onDestroy onDestroy()} is the only callback received.

        -

        Figure 2 illustrates the typical callback methods for a service. Although the figure separates -services that are created by {@link android.content.Context#startService startService()} from those -created by {@link android.content.Context#bindService bindService()}, keep -in mind that any service, no matter how it's started, can potentially allow clients to bind to it. -So, a service that was initially started with {@link android.app.Service#onStartCommand -onStartCommand()} (by a client calling {@link android.content.Context#startService startService()}) -can still receive a call to {@link android.app.Service#onBind onBind()} (when a client calls -{@link android.content.Context#bindService bindService()}).

        -

        For more information about creating a service that provides binding, see the Bound Services document, which includes more information about the {@link android.app.Service#onRebind onRebind()} callback method in the section about Managing the Lifecycle of -a Bound Service.

        - +href="{@docRoot}guide/components/bound-services.html#Lifecycle">Managing the lifecycle of +a bound service.

        Unless you specify otherwise, most of the operations you do in an app run in the foreground on - a special thread called the UI thread. This can cause problems, because long-running operations - will interfere with the responsiveness of your user interface. This annoys your users, and can + a special thread called the UI thread. Long-running foreground operations can cause problems + and interfere with the responsiveness of your user interface, which annoys your users and can even cause system errors. To avoid this, the Android framework offers several classes that - help you off-load operations onto a separate thread running in the background. The most useful - of these is {@link android.app.IntentService}. + help you off-load operations onto a separate thread that runs in the background. The most + useful of these is {@link android.app.IntentService}.

        This class describes how to implement an {@link android.app.IntentService}, send it work requests, and report its results to other components.

        + +

        Note: If your app targets Android 5.0 (API level 21), + you should use {@link android.app.job.JobScheduler} to execute background + services. For more information about this class, + see the {@link android.app.job.JobScheduler} reference documentation.

        +

        Lessons

        -- 2.11.0