From 9748d76be90a90c112874fc7ce46e5ca279488eb Mon Sep 17 00:00:00 2001
From: George French In this document
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.
- 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:
{@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:
The {@code IInAppBillingService.aidl} file will be installed to {@code
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:
IInAppBillingService.java
file gets generated.
+ IInAppBillingService.java
file is generated.
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 tocom.android.vending
â the + Intent's target package name tocom.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
-
- The Basics
-- Creating a Bound Service +
- The basics
+- Creating a bound service
-- Binding to a Service +
- Binding to a service
-- Managing the Lifecycle of a Bound Service
+- Managing the lifecycle of a bound service
Key classes
@@ -32,9 +32,13 @@ parent.link=services.htmlSamples
@@ -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.
--Binding to a Started Service
+Binding to a started service
As discussed in the Services -document, you can create a service that is both started and bound. That is, the service can be -started by calling {@link android.content.Context#startService startService()}, which allows the -service to run indefinitely, and also allow a client to bind to the service by calling {@link +document, you can create a service that is both started and bound. That is, you can start a + service by calling {@link android.content.Context#startService startService()}, which allows the +service to run indefinitely, and you can also allow a client to bind to the service by + calling {@link android.content.Context#bindService bindService()}.
If you do allow your service to be started and bound, then when the service has been -started, the system does not destroy the service when all clients unbind. Instead, you must -explicitly stop the service, by calling {@link android.app.Service#stopSelf stopSelf()} or {@link +started, the system does not destroy the service when all clients unbind. + Instead, you must +explicitly stop the service by calling {@link android.app.Service#stopSelf stopSelf()} or {@link android.content.Context#stopService stopService()}.
-Although you should usually implement either {@link android.app.Service#onBind onBind()} -or {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes necessary to +
Although you usually implement either {@link android.app.Service#onBind onBind()} +or {@link android.app.Service#onStartCommand onStartCommand()}, it's sometimes + necessary to implement both. For example, a music player might find it useful to allow its service to run indefinitely and also provide binding. This way, an activity can start the service to play some music and the music continues to play even if the user leaves the application. Then, when the user -returns to the application, the activity can bind to the service to regain control of playback.
+returns to the application, the activity can bind to the service to regain control of + playback. -Be sure to read the section about Managing the Lifecycle of a Bound -Service, for more information about the service lifecycle when adding binding to a -started service.
+For more information about the service lifecycle when adding binding to a started service, + see Managing the lifecycle of a bound 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:
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.
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.
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.
- - -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:
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}: -Compared to AIDL
When you need to perform IPC, using a {@link android.os.Messenger} for your interface is -simpler than implementing it with AIDL, because {@link android.os.Messenger} queues -all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the +simpler than using AIDL, because {@link android.os.Messenger} queues +all calls to the service. A pure AIDL interface sends simultaneous requests to the service, which must then handle multi-threading.
For most applications, the service doesn't need to perform multi-threading, so using a {@link android.os.Messenger} allows the service to handle one call at a time. If it's important -that your service be multi-threaded, then you should use AIDL to define your interface.
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.
- - - - -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:
Your implementation must override two callback methods:
@@ -533,7 +549,8 @@ the service's {@link android.app.Service#onBind onBind()} method.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);
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.
+ +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.
- - - - -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 FundamentalsAndroid 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:
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:
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:
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: +
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 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.
Content providers are also useful for reading and writing data that is private to your
app and not shared. For example, the
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).
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.
-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:
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. -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:You must declare all app components this way:
+You must declare all app components using the following elements:
<activity>
elements
-for activities<service>
elements for
-services<receiver>
elements
-for broadcast receivers<provider>
elements
-for content providersActivities, 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.
+As discussed above, in Activating components, you can use an +{@link android.content.Intent} to start activities, services, and broadcast receivers. -
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 {@codeFor 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 FilterThere 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.
-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, readAn {@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: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.
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.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()}.
-There are two types of intents:
@@ -97,7 +104,7 @@ android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.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. -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
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.
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.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";
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: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: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";
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.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.
- - - - - - - -To advertise which implicit intents your app can receive, declare one or more intent filters for
each of your app components with an {@code
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
scheme
, host
, port
,
- path
, etc.) and MIME type.path
) and MIME type.
+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> -It's okay to create a filter that includes more than one instance of
-{@code
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.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.
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.
-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:
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:
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 -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 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.
To specify accepted intent actions, an intent filter can declare zero or more
{@code
-
<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
-
<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
+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. } 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 theYour 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=ServicesA {@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:
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.
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. -A service is simply a component that can run in the background even when the user is not -interacting with your application. Thus, you should create a service only if that is what you +
A service is simply a component that can run in the background, even when the user is not +interacting with your application, so you should create a service only if that is what you need.
-If you need to perform work outside your main thread, but only while the user is interacting -with your application, then you should probably instead create a new thread and not a service. For -example, if you want to play some music, but only while your activity is running, you might create +
If you must perform work outside of your main thread, but only while the user is interacting +with your application, you should instead create a new thread. For example, if you want to +play some music, but only while your activity is running, you might create a thread in {@link android.app.Activity#onCreate onCreate()}, start running it in {@link -android.app.Activity#onStart onStart()}, then stop it in {@link android.app.Activity#onStop -onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread}, +android.app.Activity#onStart onStart()}, and stop it in {@link android.app.Activity#onStop +onStop()}. Also consider using {@link android.os.AsyncTask} or {@link android.os.HandlerThread} instead of the traditional {@link java.lang.Thread} class. See the Processes and Threading document for more information about threads.
@@ -121,78 +131,81 @@ blocking operations.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:
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.
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
<manifest ... > @@ -205,48 +218,44 @@ element. For example:
See the {@code
There are other attributes you can include in the {@code
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.
- - - -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:
+The following sections describe how you can implement your service using either one for these classes.
-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:
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:
For more details about these return values, see the linked reference documentation for each constant.
- - -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. -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.
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.
- - -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.
+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.
+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.
+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 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:
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.)
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.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 {@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()}.
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.
+