page.title=Android 5.0 APIs excludeFromSuggestions=true sdk.platform.version=5.0 sdk.platform.apiLevel=21 @jd:body
API Level: {@sdkPlatformApiLevel}
Android 5.0 (LOLLIPOP) offers new features for users and app developers. This document provides an introduction to the most notable new APIs.
If you have a published app, make sure to check out the Android 5.0 Behavior Changes that you should account for in your app. These behavior changes may affect your app on Android 5.0 devices, even if you are not using new APIs or targeting new functionality.
For a high-level look at the new platform features, instead see the Android Lollipop highlights.
To start building apps for Android 5.0, you must first get the Android SDK. Then use the SDK Manager to download the Android 5.0 SDK Platform and System Images.
To better optimize your app for devices running Android {@sdkPlatformVersion},
set your {@code targetSdkVersion} to
"{@sdkPlatformApiLevel}"
, install your app on an Android
{@sdkPlatformVersion} system image, test it, then publish the updated app with
this change.
You can use Android {@sdkPlatformVersion} APIs while also supporting older versions by adding conditions to your code that check for the system API level before executing APIs not supported by your {@code minSdkVersion}. To learn more about maintaining backward compatibility, read Supporting Different Platform Versions.
For more information about how API levels work, read What is API Level?
If you have previously published an app for Android, be aware that your app might be affected by changes in Android 5.0.
Please see Android 5.0 Changes for complete information.
Android 5.0 adds support for Android's new material design style. You can create apps with material design that are visually dynamic and have UI element transitions that feel natural to users. This support includes:
To learn more about adding material design functionality to your app, see Material Design.
In previous releases, the recents screen could only display only one task for each app that the user interacted with most recently. Now your app can open more tasks as needed for additional concurrent activities for documents. This feature facilitates multitasking by letting users quickly switch between individual activities and documents from the recents screen, with a consistent switching experience across all apps. Examples of such concurrent tasks might include open tabs in a web browser app, documents in a productivity app, concurrent matches in a game, or chats in a messaging app. Your app can manage its tasks through the {@link android.app.ActivityManager.AppTask} class.
To insert a logical break so that the system treats your activity as a new task, use {@link android.content.Intent#FLAG_ACTIVITY_NEW_DOCUMENT} when launching the activity with {@link android.app.Activity#startActivity(android.content.Intent) startActivity()}. You can also get this behavior by setting the <activity> element's {@code documentLaunchMode} attribute to {@code "intoExisting"} or {@code "always"} in your manifest.
To avoid cluttering the recents screen, you can set the maximum number of tasks from your app that can appear in that screen. To do this, set the <application> attribute {@link android.R.attr#maxRecents android:maxRecents}. The current maximum that can be specified is 50 tasks per user (25 for low RAM devices).
Tasks in the recents screen can be set to persist across reboots. To control the persistence behavior, use the android:persistableMode attribute. You can also change the visual properties of an activity in the recents screen, such as the activity’s color, label, and icon, by calling the {@link android.app.Activity#setTaskDescription(android.app.ActivityManager.TaskDescription) setTaskDescription()} method.
Android 5.0 updates the {@link android.webkit.WebView} implementation to Chromium M37, bringing security and stability enhancements, as well as bug fixes. The default user-agent string for a {@link android.webkit.WebView} running on Android 5.0 has been updated to incorporate 37.0.0.0 as the version number.
This release introduces the {@link android.webkit.PermissionRequest} class, which allows your app to grant the {@link android.webkit.WebView} permission to access protected resources like the camera and microphone, through web APIs such as getUserMedia(). Your app must have the appropriate Android permissions for these resources in order to grant the permissions to the {@link android.webkit.WebView}.
With the new onShowFileChooser()
method,
you can now use an input form field in the {@link android.webkit.WebView},
and launch a file chooser to select images and files from the Android device.
Additionally, this release brings support for the WebAudio, WebGL, and WebRTC open standards. To learn more about the new features included in this release, see WebView for Android.
Android 5.0 lets you add screen capturing and screen sharing capabilities to your app with the new {@link android.media.projection} APIs. This functionality is useful, for example, if you want to enable screen sharing in a video conferencing app.
The new {@link android.media.projection.MediaProjection#createVirtualDisplay(java.lang.String, int, int, int, int, android.view.Surface, android.hardware.display.VirtualDisplay.Callback, android.os.Handler) createVirtualDisplay()} method allows your app to capture the contents of the main screen (the default display) into a {@link android.view.Surface} object, which your app can then send across the network. The API only allows capturing non-secure screen content, and not system audio. To begin screen capturing, your app must first request the user’s permission by launching a screen capture dialog using an {@link android.content.Intent} obtained through the {@link android.media.projection.MediaProjectionManager#createScreenCaptureIntent()} method.
For an example of how to use the new APIs, see the {@code MediaProjectionDemo} class in the sample project.
Lock screens in Android 5.0 have the ability to present notifications. Users can choose via Settings whether to allow sensitive notification content to be shown over a secure lock screen.
Your app can control the level of detail visible when its notifications are displayed over the secure lock screen. To control the visibility level, call {@link android.app.Notification.Builder#setVisibility(int) setVisibility()} and specify one of these values:
When the visibility level is {@link android.app.Notification#VISIBILITY_PRIVATE VISIBILITY_PRIVATE}, you can also provide a redacted version of the notification content that hides personal details. For example, an SMS app might display a notification that shows "You have 3 new text messages" but hides the message content and senders. To provide this alternative notification, first create the replacement notification using {@link android.app.Notification.Builder}. When you create the private notification object, attach the replacement notification to it through the {@link android.app.Notification.Builder#setPublicVersion(android.app.Notification) setPublicVersion()} method.
Android 5.0 uses metadata associated with your app notifications to sort the notifications more intelligently. To set the metadata, call the following methods in {@link android.app.Notification.Builder} when you construct the notification:
Android 5.0 adds Java interfaces and native support for OpenGL ES 3.1. Key new functionality provided in OpenGL ES 3.1 includes:
The Java interface for OpenGL ES 3.1 on Android is provided with
{@link android.opengl.GLES31}. When using OpenGL ES 3.1, be sure that you
declare it in your manifest file with the
{@code
<manifest> <uses-feature android:glEsVersion="0x00030001" /> ... </manifest>
For more information about using OpenGL ES, including how to check the device’s supported OpenGL ES version at runtime, see the OpenGL ES API guide.
In addition to OpenGL ES 3.1, this release provides an extension pack with Java interfaces and native support for advanced graphics functionality. These extensions are treated as a single package by Android. (If the {@code ANDROID_extension_pack_es31a} extension is present, your app can assume all extensions in the package are present and enable the shading language features with a single {@code #extension} statement.)
The extension pack supports:
The Java interface for the extension pack is provided with {@link android.opengl.GLES31Ext}. In your app manifest, you can declare that your app must be installed only on devices that support the extension pack. For example:
<manifest> <uses-feature android:name=“android.hardware.opengles.aep” android:required="true" /> ... </manifest>
Android 5.0 introduces the new android.hardware.camera2 API to facilitate fine-grain photo capture and image processing. You can now programmatically access the camera devices available to the system with {@link android.hardware.camera2.CameraManager#getCameraIdList() getCameraIdList()} and connect to a specific device with {@link android.hardware.camera2.CameraManager#openCamera(java.lang.String, android.hardware.camera2.CameraDevice.StateCallback, android.os.Handler) openCamera()}. To start capturing images, create a {@link android.hardware.camera2.CameraCaptureSession} and specify the {@link android.view.Surface} objects to send captured images. The {@link android.hardware.camera2.CameraCaptureSession} can be configured to take single shots or multiple images in a burst.
To be notified when new images are captured, implement the {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} listener and set it in your capture request. Now when the system completes the image capture request, your {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback} listener receives a call to {@link android.hardware.camera2.CameraCaptureSession.CaptureCallback#onCaptureCompleted(android.hardware.camera2.CameraCaptureSession, android.hardware.camera2.CaptureRequest, android.hardware.camera2.TotalCaptureResult) onCaptureCompleted()}, providing you with the image capture metadata in a {@link android.hardware.camera2.CaptureResult}.
The {@link android.hardware.camera2.CameraCharacteristics} class lets your app detect what camera features are available on a device. The object's {@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL INFO_SUPPORTED_HARDWARE_LEVEL} property represents the camera's level of functionality.
To see how to use the updated Camera API, refer to the {@code Camera2Basic} and {@code Camera2Video} implementation samples in this release.
This release includes the following changes to {@link android.media.AudioTrack}:
Use the new notification and media APIs to ensure that the system UI knows about your media playback and can extract and show album art. Controlling media playback across a UI and a service is now easier with the new {@link android.media.session.MediaSession} and {@link android.media.session.MediaController} classes.
The new {@link android.media.session.MediaSession} class replaces the deprecated {@link android.media.RemoteControlClient} class and provides a single set of callback methods for handling transport controls and media buttons. If your app provides media playback and runs on the Android TV or Wear platform, use the {@link android.media.session.MediaSession} class to handle your transport controls using the same callback methods.
You can now build your own media controller app with the new {@link android.media.session.MediaController} class. This class provides a thread-safe way to monitor and control media playback from your app's UI process. When creating a controller, specify a {@link android.media.session.MediaSession.Token} object so that your app can interact with the given {@link android.media.session.MediaSession}. By using the {@link android.media.session.MediaController.TransportControls} methods, you can send commands such as {@link android.media.session.MediaController.TransportControls#play() play()}, {@link android.media.session.MediaController.TransportControls#stop() stop()}, {@link android.media.session.MediaController.TransportControls#skipToNext() skipToNext()}, and {@link android.media.session.MediaController.TransportControls#setRating(android.media.Rating) setRating()} to control media playback on that session. With the controller, you can also register a {@link android.media.session.MediaController.Callback} object to listen for metadata and state changes on the session.
In addition, you can create rich notifications that allow playback control tied to a media session with the new {@link android.app.Notification.MediaStyle} class.
Android 5.0 introduces the ability for apps to browse the media content library of another app, through the new android.media.browse API. To expose the media content in your app, extend the {@link android.service.media.MediaBrowserService} class. Your implementation of {@link android.service.media.MediaBrowserService} should provide access to a {@link android.media.session.MediaSession.Token} so that apps can play media content provided through your service.
To interact with a media browser service, use the {@link android.media.browse.MediaBrowser} class. Specify the component name for a {@link android.media.session.MediaSession} when you create an {@link android.media.browse.MediaBrowser} instance. Using that browser instance, your app can then connect to the associated service and obtain a {@link android.media.session.MediaSession.Token} object to play content exposed through that service.
Android 5.0 extends the Storage Access Framework to let users select an entire directory subtree, giving apps read/write access to all contained documents without requiring user confirmation for each item.
To select a directory subtree, build and send an {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE OPEN_DOCUMENT_TREE} intent. The system displays all {@link android.provider.DocumentsProvider} instances that support subtree selection, letting the user browse and select a directory. The returned URI represents access to the selected subtree. You can then use {@link android.provider.DocumentsContract#buildChildDocumentsUriUsingTree(android.net.Uri, java.lang.String) buildChildDocumentsUriUsingTree()} and {@link android.provider.DocumentsContract#buildDocumentUriUsingTree(android.net.Uri, java.lang.String) buildDocumentUriUsingTree()} along with {@link android.content.ContentResolver#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String) query()} to explore the subtree.
The new {@link android.provider.DocumentsContract#createDocument(android.content.ContentResolver, android.net.Uri, java.lang.String, java.lang.String) createDocument()} method lets you create new documents or directories anywhere under the subtree. To manage existing documents, use {@link android.provider.DocumentsContract#renameDocument(android.content.ContentResolver, android.net.Uri, java.lang.String) renameDocument()} and {@link android.provider.DocumentsProvider#deleteDocument(java.lang.String) deleteDocument()}. Check {@link android.provider.DocumentsContract.Document#COLUMN_FLAGS COLUMN_FLAGS} to verify provider support for these calls before issuing them.
If you're implementing a {@link android.provider.DocumentsProvider} and want to support subtree selection, implement {@link android.provider.DocumentsProvider#isChildDocument(java.lang.String, java.lang.String) isChildDocument()} and include {@link android.provider.DocumentsContract.Root#FLAG_SUPPORTS_IS_CHILD FLAG_SUPPORTS_IS_CHILD} in your {@link android.provider.DocumentsContract.Root#COLUMN_FLAGS COLUMN_FLAGS}.
Android 5.0 also introduces new package-specific directories on shared storage where your app can place media files for inclusion in {@link android.provider.MediaStore}. The new {@link android.content.Context#getExternalMediaDirs()} returns paths to these directories on all shared storage devices. Similarly to {@link android.content.Context#getExternalFilesDir(java.lang.String) getExternalFilesDir()}, no additional permissions are needed by your app to access the returned paths. The platform periodically scans for new media in these directories, but you can also use {@link android.media.MediaScannerConnection} to explicitly scan for new content.
Android 5.0 provides new multi-networking APIs that let your app dynamically scan for available networks with specific capabilities, and establish a connection to them. This functionality is useful when your app requires a specialized network, such as an SUPL, MMS, or carrier-billing network, or if you want to send data using a particular type of transport protocol.
To select and connect to a network dynamically from your app, follow these steps:
When the system detects a suitable network, it connects to the network and invokes the {@link android.net.ConnectivityManager.NetworkCallback#onAvailable(android.net.Network) onAvailable()} callback. You can use the {@link android.net.Network} object from the callback to get additional information about the network, or to direct traffic to use the selected network.
Android 4.3 introduced platform support for Bluetooth Low Energy (Bluetooth LE) in the central role. In Android 5.0, an Android device can now act as a Bluetooth LE peripheral device. Apps can use this capability to make their presence known to nearby devices. For instance, you can build apps that allow a device to function as a pedometer or health monitor and communicate its data with another Bluetooth LE device.
The new {@link android.bluetooth.le} APIs enable your apps to broadcast advertisements, scan for responses, and form connections with nearby Bluetooth LE devices. To use the new advertising and scanning features, add the {@link android.Manifest.permission#BLUETOOTH_ADMIN BLUETOOTH_ADMIN} permission in your manifest. When users update or download your app from the Play Store, they are asked to grant the following permission to your app: "Bluetooth connection information: Allows the app to control Bluetooth, including broadcasting to or getting information about nearby Bluetooth devices."
To begin Bluetooth LE advertising so that other devices can discover your app, call {@link android.bluetooth.le.BluetoothLeAdvertiser#startAdvertising(android.bluetooth.le.AdvertiseSettings, android.bluetooth.le.AdvertiseData, android.bluetooth.le.AdvertiseCallback) startAdvertising()} and pass in an implementation of the {@link android.bluetooth.le.AdvertiseCallback} class. The callback object receives a report of the success or failure of the advertising operation.
Android 5.0 introduces the {@link android.bluetooth.le.ScanFilter} class so that your app can scan for only the specific types of devices it is interested in. To begin scanning for Bluetooth LE devices, call {@link android.bluetooth.le.BluetoothLeScanner#startScan(android.bluetooth.le.ScanCallback) startScan()} and pass in a list of filters. In the method call, you must also provide an implementation of {@link android.bluetooth.le.ScanCallback} to report when a Bluetooth LE advertisement is found.
Android 5.0 adds these enhancements to enable wider and more flexible use of NFC:
registerAidsForService()
.
You can also use {@link android.nfc.cardemulation.CardEmulation#setPreferredService(android.app.Activity, android.content.ComponentName) setPreferredService()} to set the preferred card emulation service that should
be used when a specific activity is in the foreground.In addition to new features, Android 5.0 emphasizes improvements in battery life. Use the new APIs and tool to understand and optimize your app’s power consumption.
Android 5.0 provides a new {@link android.app.job.JobScheduler} API that lets you optimize battery life by defining jobs for the system to run asynchronously at a later time or under specified conditions (such as when the device is charging). Job scheduling is useful in such situations as:
A unit of work is encapsulated by a {@link android.app.job.JobInfo} object. This object specifies the scheduling criteria.
Use the {@link android.app.job.JobInfo.Builder} class to configure how the scheduled task should run. You can schedule the task to run under specific conditions, such as:
For example, you can add code like this to run your task on an unmetered network:
JobInfo uploadTask = new JobInfo.Builder(mJobId, mServiceComponent /* JobService component */) .setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED) .build(); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(uploadTask);
If the device has stable power (that is, it has been plugged in for more than 2 minutes and the battery is at a healthy level), the system will run any scheduled job that is ready to run, even if the job’s deadline has not expired.
To see an example of how to use the {@link android.app.job.JobScheduler} API, refer to the {@code JobSchedulerSample} implementation sample in this release.
The new {@code dumpsys batterystats} command generates interesting statistical data about battery usage on a device, organized by unique user ID (UID). The statistics include:
Use the {@code --help} option to learn about the various options for tailoring the output. For example, to print battery usage statistics for a given app package since the device was last charged, run this command:
$ adb shell dumpsys batterystats --charged <package-name>
You can use the Battery Historian tool on the output of the {@code dumpsys} command to generate an HTML visualization of power-related events from the logs. This information makes it easier for you to understand and diagnose any battery related issues.
Android 5.0 provides new functionality for running apps within an enterprise environment. A device administrator can initiate a managed provisioning process to add a copresent but separate managed profile to a device, if the user has an existing personal account. Apps that are associated with managed profiles appear alongside non-managed apps in the user’s Launcher, recents screen, and notifications.
To start the managed provisioning process, send {@link android.app.admin.DevicePolicyManager#ACTION_PROVISION_MANAGED_PROFILE ACTION_PROVISION_MANAGED_PROFILE} in an {@link android.content.Intent}. If the call is successful, the system triggers the {@link android.app.admin.DeviceAdminReceiver#onProfileProvisioningComplete(android.content.Context, android.content.Intent) onProfileProvisioningComplete()} callback. You can then call {@link android.app.admin.DevicePolicyManager#setProfileEnabled(android.content.ComponentName) setProfileEnabled()} to enable this managed profile.
By default, only a small subset of apps are enabled in the managed profile. You can install additional apps in the managed profile by calling {@link android.app.admin.DevicePolicyManager#enableSystemApp(android.content.ComponentName, android.content.Intent) enableSystemApp()}.
If you are developing a Launcher app, you can use the new {@link android.content.pm.LauncherApps} class to get a list of launchable activities for the current user and any associated managed profiles. Your Launcher can make the managed apps visually prominent by appending a work badge to the icon drawable. To retrieve the badged icon, call {@link android.content.pm.PackageManager#getUserBadgedIcon(android.graphics.drawable.Drawable, android.os.UserHandle) getUserBadgedIcon()}.
To see how to use the new functionality, refer to the {@code BasicManagedProfile} implementation sample in this release.
Android 5.0 introduces the ability to deploy a device owner app. A device owner is a specialized type of device administrator that has the additional ability to create and remove secondary users and to configure global settings on the device. Your device owner app can use the methods in the {@link android.app.admin.DevicePolicyManager} class to take fine-grain control of the configuration, security, and apps on managed devices. A device can have only one active device owner at a time.
To deploy and activate a device owner, you must perform an NFC data transfer from a programming app to the device while the device is in its unprovisioned state. This data transfer sends the same information as in the provisioning intent described in Managed provisioning.
Android 5.0 introduces a new screen pinning API that lets you temporarily restrict users from leaving your task or being interrupted by notifications. This could be used, for example, if you are developing an education app to support high stakes assessment requirements on Android, or a single-purpose or kiosk application. Once your app activates screen pinning, users cannot see notifications, access other apps, or return to the home screen, until your app exits the mode.
There are two ways to activate screen pinning:
When task locking is active, the following behavior happens:
You can now render PDF document pages into bitmap images for printing by using the new {@link android.graphics.pdf.PdfRenderer} class. You must specify a {@link android.os.ParcelFileDescriptor} that is seekable (that is, the content can be randomly accessed) on which the system writes the the printable content. Your app can obtain a page for rendering with {@link android.graphics.pdf.PdfRenderer#openPage(int) openPage()}, then call {@link android.graphics.pdf.PdfRenderer.Page#render(android.graphics.Bitmap, android.graphics.Rect, android.graphics.Matrix, int) render()} to turn the opened {@link android.graphics.pdf.PdfRenderer.Page} into a bitmap. You can also set additional parameters if you only want to convert a portion of the document into a bitmap image (for example, to implement tiled rendering to zoom in on the document).
For an example of how to use the new APIs, see the {@code PdfRendererBasic} sample.
You can now access app usage history on an Android device with the new {@link android.app.usage} API. This API provides more detailed usage information than the deprecated {@link android.app.ActivityManager#getRecentTasks(int, int) getRecentTasks()} method. To use this API, you must first declare the {@code "android.permission.PACKAGE_USAGE_STATS"} permission in your manifest. The user must also enable access for this app through Settings > Security > Apps with usage access.
The system collects the usage data on a per-app basis, aggregating the data over daily, weekly, monthly, and yearly intervals. The maximum duration that the system keeps this data is as follows:
For each app, the system records the following data:
Android 5.0 adds the following support for testing and accessibility:
Beginning in Android 5.0, users can more easily switch between all input method editors (IME) supported by the platform. Performing the designated switching action (usually touching a Globe icon on the soft keyboard) cycles through all such IMEs. This change in behavior is implemented by the {@link android.view.inputmethod.InputMethodManager#shouldOfferSwitchingToNextInputMethod(android.os.IBinder) shouldOfferSwitchingToNextInputMethod()} method.
In addition, the framework now checks whether the next IME includes a switching mechanism at all (and, thus, whether that IME supports switching to the IME after it). An IME with a switching mechanism will not cycle to an IME without one. This change in behavior is implemented by the {@link android.view.inputmethod.InputMethodManager#switchToNextInputMethod(android.os.IBinder, boolean) switchToNextInputMethod()} method.
To see an example of how to use the updated IME-switching APIs, refer to the updated soft-keyboard implementation sample in this release. To learn more about how to implement switching between IMEs, see Creating an Input Method.
The following values are now supported in the
{@code
The following permission is now supported in the
{@code