Features and APIs Overview | Android 12 Beta | Android Developers
source link: https://developer.android.com/about/versions/12/features
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Features and APIs Overviewbookmark_border
Android 12 introduces great new features and APIs for developers. The sections below help you learn about features for your apps and get started with the related APIs.
For a detailed list of new, modified, and removed APIs, read the API diff report. For details on new APIs visit the Android API reference — new APIs are highlighted for visibility. Also, to learn about areas where platform changes may affect your apps, be sure to check out Android 12 behavior changes for apps that target Android 12 and for all apps.
New experiences
Widgets improvements
Android 12 revamps the existing Widgets API to improve the user and developer experience in the platform and launchers. We've created a guide to help you ensure your widget is compatible with Android 12 and to refresh it with new features.
See Android 12 widgets improvements for more information.
Audio-coupled haptic effect
Android 12 apps can generate haptic feedback derived from an audio session using the phone's vibrator. This provides an opportunity for more immersive game and audio experiences. For example, haptic-enhanced ringtones can help identify callers, or a driving game could simulate the feeling of rough terrain.
See the HapticGenerator reference documentation for more information.
Splash screen API
Android 12 introduces a new app launch animation for all apps that includes an into-app motion from the point of launch, a splash screen showing the app icon, and a transition to the app itself. See Splash screen API for more details.
New phone call notifications allowing for ranking importance of incoming calls
Android 12 adds the new notification style
Notification.CallStyle
for phone calls. Using this template lets your app indicate the importance of
active calls by displaying a prominent chip that shows the time of the call in
the status bar; the user can tap this chip to return to their call.
Because incoming and ongoing calls are the most critical to users, these notifications are given top ranking in the shade. This ranking also allows the system to potentially forward these prioritized calls to other devices.
Implement the following code for all types of calls.
// Create a new call with the user as caller.
val incoming_caller = Person.Builder()
.setName("Jane Doe")
.setImportant(true)
.build()
Use forIncomingCall()
to create a call style notification for an incoming call.
// Create a call style notification for an incoming call.
val builder = Notification.Builder(context, CHANNEL_ID)
.setContentIntent(contentIntent)
.setSmallIcon(smallIcon)
.setStyle(
Notification.CallStyle.forIncomingCall(caller, declineIntent, answerIntent))
.addPerson(incoming_caller)
Use forOngoingCall()
to create a call style notification for an ongoing call.
// Create a call style notification for an ongoing call.
val builder = Notification.Builder(context, CHANNEL_ID)
.setContentIntent(contentIntent)
.setSmallIcon(smallIcon)
.setStyle(
Notification.CallStyle.forOnGoingCall(caller, hangupIntent))
.addPerson(second_caller)
Use forScreeningCall()
to create a call style notification for screening a call.
// Create a call style notification for screening a call.
val builder = Notification.Builder(context, CHANNEL_ID)
.setContentIntent(contentIntent)
.setSmallIcon(smallIcon)
.setStyle(
Notification.CallStyle.forScreeningCall(caller, hangupIntent, answerIntent))
.addPerson(second_caller)
Enriched image support for notifications
In Android 12, you can now enrich your app’s notification experience by
providing animated images in MessagingStyle()
and BigPictureStyle()
notifications. Also, your app can now enable users to send image messages when
they reply to messages from the notification shade.
Rounded corner APIs
Android 12 introduces RoundedCorner
and WindowInsets.getRoundedCorner(int
position)
,
which provide the radius and center point for rounded corners. With these APIs,
your app can avoid UI elements being truncated on screens with rounded corners.
When implemented in your app, these APIs have no effect on devices with non-rounded screens.
To implement this feature, get the RoundedCorner
info through
WindowInsets.getRoundedCorner(int position)
relative to the bounds of the
application. If the app doesn’t take up the whole screen, the API applies the
rounded corner by basing the center point of the rounded corner on the window
bounds of the app.
The following code snippet shows a simple example for an app to avoid UI
truncations by setting a margin of the view based on the info from
RoundedCorner
. In this case, it is the top right rounded corner.
// Get the top-right rounded corner from WindowInsets.
final WindowInsets insets = getRootWindowInsets();
final RoundedCorner topRight = insets.getRoundedCorner(POSITION_TOP_RIGHT);
if (topRight == null) {
return;
}
// Get the location of the close button in window coordinates.
int [] location = new int[2];
closeButton.getLocationInWindow(location);
final int buttonRightInWindow = location[0] + closeButton.getWidth();
final int buttonTopInWindow = location[1];
// Find the point on the quarter circle with a 45 degree angle.
final int offset = (int) (topRight.getRadius() * Math.sin(Math.toRadians(45)));
final int topBoundary = topRight.getCenter().y - offset;
final int rightBoundary = topRight.getCenter().x + offset;
// Check whether the close button exceeds the boundary.
if (buttonRightInWindow < rightBoundary && buttonTopInWindow > topBoundary) {
return;
}
// Set the margin to avoid truncating.
int [] parentLocation = new int[2];
getLocationInWindow(parentLocation);
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) closeButton.getLayoutParams();
lp.rightMargin = Math.max(buttonRightInWindow - rightBoundary, 0);
lp.topMargin = Math.max(topBoundary - buttonTopInWindow, 0);
closeButton.setLayoutParams(lp);
Picture in Picture (PiP) improvements
Android 12 introduces new features for picture-in-picture (PiP) mode. See Picture-in-picture improvements for more information.
Immersive mode improvements for gesture navigation
Android 12 simplifies immersive mode to make gesture navigation easier and more consistent with the rest of the experience of activities such as watching a video and reading a book. Apps can still protect from accidental gestures in full-screen gaming experiences so users don't accidentally quit out of their games while playing; all other full-screen or immersive experiences now allow users to navigate their phone with one swipe.
To make this possible, the existing behaviors for non-sticky immersive
experiences (BEHAVIOR_SHOW_BARS_BY_TOUCH
,
BEHAVIOR_SHOW_BARS_BY_SWIPE
)
are deprecated starting in Android 12. They have been replaced with default
behavior (BEHAVIOR_DEFAULT
)
that allows gestures with one swipe when hiding system bars. This flag exhibits
different visual and functional behavior depending on the mode:
- In three-button mode, visual and functional behavior is the same as immersive mode in versions of Android prior to 12.
- In gestural navigation mode, the behavior is as follows:
- Visually, it’s the same as immersive mode in Android 11 and lower.
- Functionally, gestures are allowed even when the bar is hidden; system back requires only one swipe to invoke instead of the two swipes required for Android 11. No additional swipes are needed to pull down the notification bar or start going Home.
Sticky immersive mode (BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
)
has not changed for Android 12. Note the following backward-compatibility for
this feature:
- For apps running on Android 12 that target Android 11 and lower:
BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
behaves the same functionally and visually.- The default is mapped to
BEHAVIOR_SHOW_BARS_BY_SWIPE
.
- For apps running on Android 11 (API level 30) and lower that target Android
12:
- The same behavior is expected, except
BEHAVIOR_SHOW_BARS_BY_TOUCH
is mapped toBEHAVIOR_SHOW_BARS_BY_SWIPE
. - Make sure to update your SDK level to have the new default (
BEHAVIOR_SHOW_BARS_BY_SWIPE
). Otherwise,BEHAVIOR_SHOW_BARS_BY_TOUCH
remains the default.
- The same behavior is expected, except
Rich content insertion
Android 12 introduces a new unified API that lets you receive rich content from any available source: clipboard, keyboard, or drag and drop.
For more information, see Unified API for receiving content.
Camera
Quad bayer camera sensor support
Many Android devices today ship with ultra high-resolution camera sensors, typically with Quad / Nona Bayer patterns, and these offer great flexibility in terms of image quality and low-light performance. Android 12 introduces new platform APIs that let third-party apps take full advantage of these versatile sensors. The new APIs support the unique behavior of these sensors and take into account that they might support different stream configurations and combinations when operating in full resolution or ‘maximum resolution’ mode vs ‘default’ mode.
Graphics and images
Provide apps direct access to tombstone traces
Starting in Android 12, you can access your app's native crash tombstone as a
protocol buffer through the
ApplicationExitInfo.getTraceInputStream()
method. The protocol buffer is serialized using this schema.
Previously, the only way to get access to this information was through the
Android Debug Bridge (adb).
Here’s one example of how to implement this in your app:
ActivityManager activityManager: ActivityManager = getSystemService(Context.ACTIVITY_SERVICE);
MutableList<ApplicationExitInfo> exitReasons = activityManager.getHistoricalProcessExitReasons(/* packageName = */ null, /* pid = */ 0, /* maxNum = */ 5);
for ( ApplicationExitInfo aei: exitReasons ) {
if ( aei.getReason() == REASON_CRASH_NATIVE ) {
// Get the tombstone input stream.
InputStream tombstoneInputStream = aei.getTraceInputStream();
// The tombstone parser built with protoc uses the tombstone schema, then parses the trace.
Tombstone tombstone = Tombstone.parseFrom(trace);
}
}
AVIF image support
Android 12 introduces support for images that use the AV1 Image File Format (AVIF). AVIF is a container format for images and sequences of images encoded using AV1. It takes advantage of the intra-frame encoded content from video compression. This dramatically improves image quality for the same file size when compared to older image formats, such as JPEG. For an in depth look at the advantages of this format, see Jake Archibald's blog post.
Easier blurs, color filters, and other effects
Android 12 adds the new RenderEffect
that applies common graphics effects such as blurs, color filters, Android shader
effects, and more to View
s
and rendering hierarchies. Effects can be combined as either chain effects
(which compose an inner and outer effect) or blended effects. Different Android
devices may or may not support the feature due to limited processing power.
Effects can also be applied to the underlying RenderNode
for View
s by calling View.setRenderEffect(RenderEffect)
.
To implement a RenderEffect
:
view.setRenderEffect(RenderEffect.createBlurEffect(radiusX, radiusY, SHADER_TILE_MODE))
Native animated image decoding
In Android 12, the NDK
ImageDecoder
API has been expanded
to decode all frames and timing data from images
that use the animated GIF and
animated WebP file formats. When it
was introduced in Android 11, this API decoded only the first image from
animations in these formats.
Use ImageDecoder
instead of third-party libraries to further decrease APK
size
and benefit from future updates related to security and performance.
For more details on the API, refer to the API reference and the sample on GitHub.
Media
Compatible media transcoding
Android 12 can automatically transcode HEVC(H.265) and HDR (HDR10 and HDR10+) videos recorded on the device to AVC (H.264), a format which is widely compatible with standard players. This takes advantage of modern codecs when they are available without sacrificing compatibility with older applications.
See compatible media transcoding for more details.
Performance class
Starting with Android 12, Android introduces a standard called performance class. A performance class specifies hardware capabilities beyond Android's baseline requirements. Each Android device declares the performance class that it supports. Developers can check the device's performance class at runtime and provide upgraded experiences that take full advantage of the device’s capabilities.
See Performance class for more details.
Video encoding improvements
Android 12 defines a standard set of keys for controlling the quantization parameter (QP) value for video encoding, allowing developers to avoid vendor-specific code.
The new keys are available in the
MediaFormat
API
and also in the
NDK Media library.
Starting with Android 12 video encoders enforce a minimum quality threshold. This guarantees that users don't experience extremely low quality when encoding videos with high scene complexity.
Audio focus
Starting with Android 12, when an app requests audio focus while another app has the focus and is playing, the framework fades out the playing app.
See audio focus improvements for more details.
MediaDrm updates
In order to determine whether a secure decoder component is required with the
current MediaDrm
APIs, you must follow these steps:
- Create a
MediaDrm
. - Open a session to obtain a session id.
- Create a
MediaCrypto
using the session id. - Call
MediaCrypto.requiresSecureDecoderComponent(mimeType)
.
With the new methods requiresSecureDecoder(@NonNull String mime)
and
requiresSecureDecoder(@NonNull String mime, @SecurityLevel int level)
you can determine this as soon as you create a MediaDrm
.
Security and privacy
Bluetooth permissions
Android 12 introduces the
BLUETOOTH_SCAN
,
BLUETOOTH_ADVERTISE
,
and
BLUETOOTH_CONNECT
permissions. These permissions make it easier for apps that target
Android 12 to interact with Bluetooth
devices, especially for apps that don't
require access to device location.
Learn more in the guide about the new Bluetooth permissions.
Privacy Dashboard
On supported devices that run Android 12, a Privacy Dashboard screen appears in system settings. On this screen, users can access separate screens that show when apps access location, camera, and microphone information. Each screen shows a timeline of when different apps have accessed a particular type of data. Figure 1 shows the data access timeline for location information.
Your app can provide a rationale for users, to help them understand why your app accesses location, camera, or microphone information. This rationale can appear on the new Privacy Dashboard screen, your app's permissions screen, or both.
Show rationale for data access
To explain why your app accesses location, camera, and microphone information, complete the following steps:
- Declare the
START_VIEW_PERMISSION_USAGE
permission. Add an activity that, when started, provides some rationale for why your app performs a particular type of data access action.
Note: If your app targets Android 12, you must explicitly define a value for theandroid:exported
attribute.Add the following intent filter to the newly-added activity:
<!-- android:exported required if you target Android 12. -->
<activity android:name=".DataAccessRationaleActivity"
android:permission="android.permission.START_VIEW_PERMISSION_USAGE"
android:exported="true">
<!-- VIEW_PERMISSION_USAGE shows a selectable information icon on
your app permission's page in system settings.
VIEW_PERMISSION_USAGE_FOR_PERIOD shows a selectable information
icon on the Privacy Dashboard screen. -->
<intent-filter
android:action="android.intent.action.VIEW_PERMISSION_USAGE"
android:action="android.intent.action.VIEW_PERMISSION_USAGE_FOR_PERIOD" ... >
</intent-filter>
</activity>Decide what your data access rationale activity should show. For example, you might show your app's website or a help center article. To provide a more detailed explanation about the types of data that your app accesses, as well as when the access occurred, handle the extras that the system includes when it invokes the permission usage intent:
- If the system invokes
ACTION_VIEW_PERMISSION_USAGE
, your app can retrieve a value forEXTRA_PERMISSION_GROUP_NAME
. - If the system invokes
ACTION_VIEW_PERMISSION_USAGE_FOR_PERIOD
, your app can retrieve values forEXTRA_PERMISSION_GROUP_NAME
,EXTRA_ATTRIBUTION_TAGS
,EXTRA_START_TIME
, andEXTRA_END_TIME
.
- If the system invokes
Depending on which intent filters you add, users see an information icon next to your app's name on certain screens:
- If you add the intent filter that contains the
VIEW_PERMISSION_USAGE
action, users see the icon on your app's permissions page in system settings. - If you add the intent filter that contains the
VIEW_PERMISSION_USAGE_FOR_PERIOD
action, users see the icon next to your app's name whenever your app appears in the Privacy Dashboard screen.
When users select that icon, your app's rationale activity is started.
Hide application overlay windows
To give developers more control over what users see when they interact with the
developer's app, Android 12 introduces the ability to hide
overlay windows that are drawn by apps that have the
SYSTEM_ALERT_WINDOW
permission.
After declaring the
HIDE_OVERLAY_WINDOWS
permission, an app can call
setHideOverlayWindows()
to indicate that all windows of type
TYPE_APPLICATION_OVERLAY
should be hidden when the app's own window is visible. Apps might choose to do
this when displaying sensitive screens, such as transaction confirmation flows.
Apps that show windows of type TYPE_APPLICATION_OVERLAY
should consider
alternatives that may be more appropriate for their use case, such as
picture-in-picture or
bubbles.
Known signers permission protection flag
Android 12 introduces the
knownCerts
attribute for
signature-level permissions.
This attribute allows you to refer to the digests of known signing
certificates at declaration time.
Your app can declare this attribute and use the new knownSigner
flag in the
protectionLevel
attribute for a
given signature-level permission. When your app does this, the system grants the
permission to a requesting app if any signer in the requesting app's signing
lineage, including the current signer, matches one of the digests that's
declared with the permission in the knownCerts
attribute.
The knownSigner
flag allows devices and apps to grant signature permissions to
other apps without having to sign the apps at the time of device manufacturing
and shipment.
Device properties attestation
Android 12 expands the set of apps that can verify the device properties that are in an attestation certificate when these apps generate a new key.
As of Android 9 (API level 28), device policy
owners (DPOs) that use
Keymaster 4.0 or higher can
verify the device properties in these attestation certificates. Starting in
Android 12, any app that targets Android 12 can perform this verification using
the
setDevicePropertiesAttestationIncluded()
method.
The generated device properties include the following
Build
fields:
BRAND
DEVICE
MANUFACTURER
MODEL
PRODUCT
Secure lockscreen notification actions
Android 12 adds the new setAuthenticationRequired
flag to Notification.Action.Builder
. This flag lets you add an extra layer of
security to notifications on locked devices.
When this flag is applied with a value of true
to a given notification action, a user invoking that action
on a locked device always results in an authentication request. Previously, the
system requested authentication on locked devices only if the user’s invoking of
a notification action launched an activity or was a direct reply.
To implement this feature, add setAuthenticationRequired
to a notification
action:
Notification n1 = new Notification.Builder(context, NotificationListenerVerifierActivity.TAG)
...
.addAction(new Notification.Action.Builder(R.drawable.ic_stat_charlie,
context.getString(R.string.action_test_title), makeBroadcastIntent(context))
// Make sure this notification action will always request authentication when
// invoked from a lock screen
.setAuthenticationRequired(true).build())
.build();
Connectivity
Bandwidth estimation improvements
In Android 12, the bandwidth estimation capabilities provided by
getLinkDownstreamBandwidthKbps()
and
getLinkUpstreamBandwidthKbps()
are improved for both Wi-Fi and cellular connectivity. The values returned now
represent the user’s all-time weighted average throughput per carrier or WiFi
SSID, network type, and signal level, across all applications on the device.
This can return a more-accurate and realistic estimate of expected throughput,
provide estimates on a cold start of your application, and requires fewer cycles
when compared to using other throughput estimation methods.
Keeping companion apps awake
To support the need of companion apps to stay running to manage the device, Android 12 introduces APIs that do the following:
- Enable you to wake an app when a companion device is within range.
- Guarantee that the process will continue running while the device stays within range.
To use the APIs, your devices must be connected using Companion Device
Manager. For more
information, see
CompanionDeviceManager.startObservingDevicePresence()
and
CompanionDeviceService.onDeviceAppeared()
.
Companion Device Manager profiles
Partner apps that target Android 12 and higher can now use companion device profiles when connecting to a watch. Using a profile simplifies the enrollment process by bundling the granting of a device-type-specific set of permissions into one step.
The bundled permissions are granted to the companion app once the device connects, and last only while the device is associated. Deleting the app or removing the association removes the permissions.
For more information, see
AssociationRequest.Builder.setDeviceProfile()
.
Wi-Fi Aware (NAN) enhancements
Android 12 adds some enhancements to Wi-Fi Aware:
- On devices running Android 12 and higher, you can use the
onServiceLost()
callback to be alerted when your app has lost a discovered service due to the service stopping or moving out of range. - The way that multiple data-paths (NAN Data Paths) are set up is changing to be more efficient. Earlier versions used L2 messaging to exchange peer information of the initiators, which introduced latency. On devices running Android 12 and higher, the responder (server) can be configured to accept any peer—that is, it doesn’t need to know the initiator information upfront. This speeds up datapath bringup and enables multiple point-to-point links with only one network request.
- To prevent the framework from rejecting discovery or connection requests due
to running out of resources, on devices running Android 12 and
higher, you can call
WifiAwareManager.getAvailableAwareResources()
. This method's return value lets you get the number of available data paths, the number of available publish sessions, and the number of available subscribe sessions.
Concurrent Peer-to-Peer + Internet Connection
When devices targeting Android 12 and higher run on devices with
hardware support, using Peer-to-peer
connections will not disconnect your
existing Wi-Fi connection when creating the connection to the peer device. To
check for support for this feature, use
WifiManager.isMultiStaConcurrencySupported()
.
Storage
Android 12 introduces several changes to storage management APIs, which the following sections describe.
New directory for voice recordings
The system recognizes the audio files that are stored in the new
Environment.DIRECTORY_RECORDINGS
folder as recordings. When your app performs queries on the system's media
store, you can retrieve recordings by using the
IS_RECORDING
flag.
Media management access
Users might trust a particular app to perform media management, such as making frequent edits to media files. If your app targets Android 11 (API level 30) or higher and isn’t the device's default gallery app, you must show a confirmation dialog to the user each time your app attempts to modify or delete a file.
If your app targets Android 12, you can request users to give your app permission to do each of the following without needing to prompt the user for each file operation:
- Modify files, using
createWriteRequest()
. - Move files into and out of the trash, using
createTrashRequest()
. - Delete files, using
createDeleteRequest()
.
To do so, complete the following steps:
Declare the new
MANAGE_MEDIA
permission and theREAD_EXTERNAL_STORAGE
permission in your app's manifest file.In order to call
createWriteRequest()
without showing a confirmation dialog, declare theACCESS_MEDIA_LOCATION
permission as well.In your app, show a UI to the user to explain why they might want to grant media management access to your app.
Invoke the
ACTION_REQUEST_MANAGE_MEDIA
intent action. This takes users to the Media management apps screen in system settings. From here, users can grant the special app access.
App storage access
An app can declare and create a custom activity that, when launched, allows the
user to manage the data that the app has stored on the user's device. Apps
declare this custom "manage space" activity using the
android:manageSpaceActivity
attribute in the manifest file. File manager apps can launch this "manage space"
activity even when the app doesn't export the activity; that is, when the
activity sets
android:exported
to
false
.
On Android 12, apps that have both the
MANAGE_EXTERNAL_STORAGE
permission and the
QUERY_ALL_PACKAGES
permission—such as file management apps—can use the new
getManageSpaceActivityIntent()
to send users to another app's custom "manage space" activity, if one is defined
for that other app.
The getManageSpaceActivityIntent()
method takes in a package name and a
request code, and it returns one of the following:
- A
PendingIntent
, if the app with the specified package name has defined a custom "manage space" activity. The app that called thegetManageSpaceActivityIntent()
method can then invoke the returned intent to send users to the custom activity. null
, if the app with the specified package name doesn't define a "manage space" activity.
Extended file access support
The getMediaUri()
method now supports MediaDocumentsProvider
URIs, in addition to the existing
support for ExternalStorageProvider
URIs. The system now grants these URIs to
the caller before returning them.
Additionally, the media URIs that are granted by
createWriteRequest()
now support the APIs in the File
class. These APIs
provide the ability to read, write, rename, and delete files.
Core functionality
Automatic app updates
Android 12 introduces the
setRequireUserAction()
method for apps that use the
PackageInstaller
API.
This method allows installer apps to perform app updates without requiring the
user to confirm the action.
Device chipset information
Android 12 adds two constants to android.os.Build
that expose
the SoC chipset vendor and model information via the SDK. You can retrieve this
information by calling Build.SOC_MANUFACTURER
and Build.SOC_MODEL
respectively.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK