1page.title=Android 4.1 APIs 2sdk.platform.version=4.1 3sdk.platform.apiLevel=16 4@jd:body 5 6<div id="qv-wrapper"> 7<div id="qv"> 8 9 <h2>In this document</h2> 10<ol> 11 <li><a href="#AppComponents">App Components</a></li> 12 <li><a href="#Multimedia">Multimedia</a></li> 13 <li><a href="#Camera">Camera</a></li> 14 <li><a href="#Connectivity">Connectivity</a></li> 15 <li><a href="#A11y">Accessibility</a></li> 16 <li><a href="#CopyPaste">Copy and Paste</a></li> 17 <li><a href="#Renderscript">Renderscript</a></li> 18 <li><a href="#Animation">Animation</a></li> 19 <li><a href="#UI">User Interface</a></li> 20 <li><a href="#Input">Input Framework</a></li> 21 <li><a href="#Permissions">Permissions</a></li> 22 <li><a href="#DeviceFeatures">Device Features</a></li> 23</ol> 24 25<h2>See also</h2> 26<ol> 27<li><a 28href="{@docRoot}sdk/api_diff/16/changes.html">API 29Differences Report »</a> </li> 30</ol> 31 32</div> 33</div> 34 35 36<p>API Level: 16</p> 37 38<p>Android 4.1 ({@link android.os.Build.VERSION_CODES#JELLY_BEAN}) 39is a progression of the platform that offers improved 40performance and enhanced user experience. It adds new features for users and app 41developers. This document provides an introduction to the most notable and 42useful new APIs for app developers.</p> 43 44 45<div class="sidebox-wrapper"> 46<div class="sidebox"> 47 48<h3 id="ApiLevel">Declare your app API Level</h3> 49 50<p>To better optimize your app for devices running Android {@sdkPlatformVersion}, 51 you should set your <a 52href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> to 53<code>"{@sdkPlatformApiLevel}"</code>, install it on an Android {@sdkPlatformVersion} system image, 54test it, then publish an update with this change.</p> 55 56<p>You 57can use APIs in Android {@sdkPlatformVersion} while also supporting older versions by adding 58conditions to your code that check for the system API level before executing 59APIs not supported by your <a 60href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>. 61To learn more about 62maintaining backward-compatibility, read <a 63href="{@docRoot}training/backward-compatible-ui/index.html">Creating Backward-Compatible 64UIs</a>.</p> 65 66<p>More information about how API levels work is available in <a 67href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">What is API 68Level?</a></p> 69 70</div> 71</div> 72 73 74 75<p>As an app developer, Android 4.1 is available to you from the 76<a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a> as a system image you can 77run in the Android emulator and an SDK platform against which you can build your app. You should 78download the system image and platform as soon as possible to build and test your 79app on Android 4.1.</p> 80 81 82 83 84 85<h2 id="AppComponents">App Components</h2> 86 87 88 89<h3 id="Isolated">Isolated services</h3> 90 91<p>By specifying <a href="{@docRoot}guide/topics/manifest/service-element.html#isolated">{@code android:isolatedProcess="true"}</a> in the 92<a href="{@docRoot}guide/topics/manifest/service-element.html">{@code <service>}</a> tag, your {@link android.app.Service} will run under 93its own isolated user ID process that has no permissions of its own.</p> 94 95 96<h3 id="Memory">Memory management</h3> 97 98<p>New {@link android.content.ComponentCallbacks2} constants such as {@link 99android.content.ComponentCallbacks2#TRIM_MEMORY_RUNNING_LOW} and {@link 100android.content.ComponentCallbacks2#TRIM_MEMORY_RUNNING_CRITICAL} provide foreground 101processes more information about 102memory state before the system calls {@link android.app.Activity#onLowMemory()}.</p> 103 104<p>New {@link android.app.ActivityManager#getMyMemoryState} method allows you to 105retrieve the general memory state.</p> 106 107 108<h3 id="ContentProvider">Content providers</h3> 109 110<p>A new method, {@link android.content.ContentResolver#acquireUnstableContentProviderClient 111acquireUnstableContentProviderClient()}, allows you to access a {@link 112android.content.ContentProviderClient} that may be "unstable" such that your app will not crash if 113the content provider does. It's useful when you are interacting with content providers in a separate 114app.</p> 115 116 117 118<h3 id="LiveWallpapers">Live Wallpapers</h3> 119 120<p>New intent protocol to directly launch the live wallpaper preview activity so you can help 121 users easily select your live wallpaper without forcing them to leave 122your app and navigate through the Home wallpaper picker.</p> 123 124<p>To launch the live wallpaper picker, call {@link android.content.Context#startActivity 125 startActivity()} with an {@link android.content.Intent} using 126{@link android.app.WallpaperManager#ACTION_CHANGE_LIVE_WALLPAPER} and an extra 127that specifies your live wallpaper {@link android.content.ComponentName} as a string in {@link 128android.app.WallpaperManager#EXTRA_LIVE_WALLPAPER_COMPONENT}.</p> 129 130 131 132 133<h3 id="StackNav">App stack navigation</h3> 134 135<p>Android 4.1 makes it much easier to implement the proper design patterns for Up navigation. 136All you need to do is add the <a 137href="{@docRoot}guide/topics/manifest/activity-element.html#parent">{@code 138android:parentActivityName}</a> to each <a 139href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element in 140your manifest file. The system uses this information to open the appropriate activity when the user 141presses the Up button in the action bar (while also finishing the current activity). So if you 142declare the <a href="{@docRoot}guide/topics/manifest/activity-element.html#parent">{@code 143android:parentActivityName}</a> for each activity, you don't need the {@link 144android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method to handle click 145events on the action bar's app icon—the system now handles that event and resumes or 146creates the appropriate activity.</p> 147 148<p>This is particularly powerful for scenarios in which the user enters one of your app's activities 149through a "deep dive" intent such as from a notification or an intent from 150different app (as described in the design guide for <a 151href="{@docRoot}design/patterns/navigation.html#between-apps">Navigating Between Apps</a>). When 152the user enters your activity this way, your app may not naturally have a back stack of 153activities that can be resumed as the user navigates up. However, when you supply the <a 154href="{@docRoot}guide/topics/manifest/activity-element.html#parent">{@code 155android:parentActivityName}</a> attribute for your activities, the system recognizes 156 whether or not your app already contains a back stack of parent activities and, if not, constructs 157a synthetic back stack that contains all parent activities.</p> 158 159<p class="note"><strong>Note:</strong> When the user enters a deep activity in your app and 160 it creates a new task for your app, the system actually inserts the stack of parent activities 161 into the task. As such, pressing the Back button also navigates back through the stack of parent 162 activities.</p> 163 164<p>When the system creates a synthetic back stack for your app, it builds a basic {@link 165 android.content.Intent} to create a new instance of each parent activity. So there's no 166 saved state for the parent activities the way you'd expect had the user naturally navigated 167through 168 each activity. If any of the parent activities normally show a UI that's dependent on 169 the user's context, that context information will be missing and you should deliver it when the 170user 171 navigates back through the stack. For example, if the user is viewing an album 172in a music app, navigating up might bring them to an activity that lists all albums in a chosen 173music genre. In this case, if the stack must be created, it's necessary that you inform the parent 174activity what genre the current album belongs to so that the parent can display the proper list as 175if the user actually came from that activity. To deliver such information to a synthetic parent 176activity, you must override the {@link 177android.app.Activity#onPrepareNavigateUpTaskStack onPrepareNavigateUpTaskStack()} method. This 178provides you with a {@link android.app.TaskStackBuilder} object that the system created in order to 179synthesize the parent activities. The {@link android.app.TaskStackBuilder} contains {@link 180android.content.Intent} objects that the system uses to create each parent activity. In your 181implementation of {@link android.app.Activity#onPrepareNavigateUpTaskStack 182onPrepareNavigateUpTaskStack()}, you can modify the appropriate {@link android.content.Intent} to 183add extra data that the parent activity can use to determine the appropriate context and display 184the appropriate UI.</p> 185 186<p>When the system creates the {@link android.app.TaskStackBuilder}, it adds the {@link 187android.content.Intent} objects that are used to create the parent activities in their logical 188order beginning from the top of the activity tree. So, the last {@link 189android.content.Intent} added to the internal array is the direct parent of the current activity. If 190you want to modify the {@link android.content.Intent} for the activity's parent, first determine 191the length of the array with {@link android.app.TaskStackBuilder#getIntentCount()} and pass that 192value to {@link android.app.TaskStackBuilder#editIntentAt editIntentAt()}.</p> 193 194<p>If your app structure is more complex, there are several other APIs 195 available that allow you to handle the behavior of Up navigation and 196 fully customize the synthetic back stack. Some of the APIs that give you additional 197 control include:</p> 198<dl> 199 <dt>{@link android.app.Activity#onNavigateUp}</dt> 200 <dd>Override this to perform a custom action when the user presses the Up button.</dd> 201 <dt>{@link android.app.Activity#navigateUpTo}</dt> 202 <dd>Call this to finish the current activity and go to the activity indicated by the 203 supplied {@link android.content.Intent}. If the activity exists in the back stack, but 204 is not the closest parent, then all other activities between the current activity and the 205 activity specified with the intent are finished as well.</dd> 206 <dt>{@link android.app.Activity#getParentActivityIntent}</dt> 207 <dd>Call this to get the {@link android.content.Intent} that will start the logical 208 parent for the current activity.</dd> 209 <dt>{@link android.app.Activity#shouldUpRecreateTask}</dt> 210 <dd>Call this to query whether a synthetic back stack must be created in order to navigate 211 up. Returns true if a synthetic stack must be created, false if the appropropriate stack 212 already exists.</dd> 213 <dt>{@link android.app.Activity#finishAffinity}</dt> 214 <dd>Call this to finish the current activity and all parent activities with the same 215 task affinity that are chained to the current activity. 216 If you override the default behaviors such as 217 {@link android.app.Activity#onNavigateUp}, you should call this method when you 218 create a synthetic back stack upon Up navigation.</dd> 219 <dt>{@link android.app.Activity#onCreateNavigateUpTaskStack onCreateNavigateUpTaskStack}</dt> 220 <dd>Override this if you need to fully control how the synthetic task stack is created. If you want to simply add some extra data to the intents for your back stack, you should instead override {@link android.app.Activity#onPrepareNavigateUpTaskStack 221onPrepareNavigateUpTaskStack()}</dd> 222</dl> 223 224<p>However, most apps don't need to use these APIs or implement {@link 225android.app.Activity#onPrepareNavigateUpTaskStack 226onPrepareNavigateUpTaskStack()}, but can can achieve the correct behavior simply by 227adding <a 228href="{@docRoot}guide/topics/manifest/activity-element.html#parent">{@code 229android:parentActivityName}</a> to each <a 230href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element.</p> 231 232 233 234 235 236 237 238 239 240 241 242<h2 id="Multimedia">Multimedia</h2> 243 244<h3 id="Codecs">Media codecs</h3> 245 246<p>The {@link android.media.MediaCodec} class provides access to low-level media codecs for encoding 247and decoding your media. You can instantiate a {@link android.media.MediaCodec} by calling {@link 248android.media.MediaCodec#createEncoderByType createEncoderByType()} to encode media or call {@link 249android.media.MediaCodec#createDecoderByType createDecoderByType()} to decode media. Each of these 250methods take a MIME type for the type of media you want to encode or decode, such as {@code 251"video/3gpp"} or {@code "audio/vorbis"}. </p> 252 253<p>With an instance of {@link android.media.MediaCodec} created, you can then call {@link 254android.media.MediaCodec#configure configure()} to specify properties such as the media format or 255whether or not the content is encrypted.</p> 256 257<p>Whether you're encoding or decoding your media, the rest of the process is the same after you 258create the {@link android.media.MediaCodec}. First call {@link 259android.media.MediaCodec#getInputBuffers()} to get an array of input {@link java.nio.ByteBuffer} 260objects and {@link android.media.MediaCodec#getOutputBuffers()} to get an array of output {@link 261java.nio.ByteBuffer} objects.</p> 262 263<p>When you're ready to encode or decode, call {@link android.media.MediaCodec#dequeueInputBuffer 264dequeueInputBuffer()} to get the index position of the {@link 265java.nio.ByteBuffer} (from the array of input buffers) that you should use to to feed in your source 266media. After you fill the {@link java.nio.ByteBuffer} with your source media, release ownership 267of the buffer by calling {@link android.media.MediaCodec#queueInputBuffer queueInputBuffer()}.</p> 268 269<p>Likewise for the output buffer, call {@link android.media.MediaCodec#dequeueOutputBuffer 270dequeueOutputBuffer()} to get the index position of the {@link java.nio.ByteBuffer} 271where you'll receive the results. After you read the output from the {@link java.nio.ByteBuffer}, 272release ownership by calling {@link android.media.MediaCodec#releaseOutputBuffer 273releaseOutputBuffer()}.</p> 274 275<p>You can handle encrypted media data in the codecs by calling {@link 276android.media.MediaCodec#queueSecureInputBuffer queueSecureInputBuffer()} in conjunction with 277 the {@link android.media.MediaCrypto} APIs, instead of the normal {@link 278android.media.MediaCodec#queueInputBuffer queueInputBuffer()}.</p> 279 280<p>For more information about how to use codecs, see the {@link android.media.MediaCodec} documentation.</p> 281 282<!-- 283<h3 id="Routing">Media routing</h3> 284 285<p>The new {@link android.media.MediaRouter} class allows you to route media channels and 286 streams from the current device to external speakers and other devices. You 287can acquire an instance of {@link android.media.MediaRouter} by calling {@link 288android.content.Context#getSystemService getSystemService(}{@link 289android.content.Context#MEDIA_ROUTER_SERVICE MEDIA_ROUTER_SERVICE)}.</p> 290--> 291 292 293<h3 id="AudioCue">Record audio on cue</h3> 294 295<p>New method {@link android.media.AudioRecord#startRecording startRecording()} allows 296you to begin audio recording based on a cue defined by a {@link android.media.MediaSyncEvent}. 297The {@link android.media.MediaSyncEvent} specifies an audio session 298(such as one defined by {@link android.media.MediaPlayer}), which when complete, triggers 299the audio recorder to begin recording. For example, you can use this functionality to 300play an audio tone that indicates the beginning of a recording session and recording 301automatically begins so you don't have to manually synchronize the tone and the beginning 302of recording.</p> 303 304 305<h3 id="TextTracks">Timed text tracks</h3> 306 307<p>The {@link android.media.MediaPlayer} now handles both in-band and out-of-band text tracks. 308In-band text tracks come as a text track within an MP4 or 3GPP media source. Out-of-band text 309tracks can be added as an external text source via {@link 310android.media.MediaPlayer#addTimedTextSource addTimedTextSource()} method. After all external text 311track sources are added, {@link android.media.MediaPlayer#getTrackInfo()} should be called to get 312the refreshed list of all available tracks in a data source.</p> 313 314<p>To set the track to use with the {@link android.media.MediaPlayer}, you must 315call {@link android.media.MediaPlayer#selectTrack selectTrack()}, using the index 316position for the track you want to use.</p> 317 318<p>To be notified when the text track is ready to play, implement the 319{@link android.media.MediaPlayer.OnTimedTextListener} interface and pass 320it to {@link android.media.MediaPlayer#setOnTimedTextListener setOnTimedTextListener()}.</p> 321 322 323<h3 id="AudioEffects">Audio effects</h3> 324 325<p>The {@link android.media.audiofx.AudioEffect} class now supports additional audio 326 pre-processing types when capturing audio:</p> 327<ul> 328 <li>Acoustic Echo Canceler (AEC) with {@link android.media.audiofx.AcousticEchoCanceler} 329 removes the contribution of the signal received from the remote party from the captured audio signal.</li> 330 <li>Automatic Gain Control (AGC) with {@link android.media.audiofx.AutomaticGainControl} 331 automatically normalizes the output of the captured signal.</li> 332 <li>Noise Suppressor (NS) with {@link android.media.audiofx.NoiseSuppressor} 333 removes background noise from the captured signal.</li> 334</ul> 335 336<p>You can apply these pre-processor effects on audio captured with an {@link 337android.media.AudioRecord} using one of the {@link android.media.audiofx.AudioEffect} 338subclasses.</p> 339 340<p class="note"><strong>Note:</strong> It's not guaranteed that all devices support these 341effects, so you should always first check availability by calling {@link 342android.media.audiofx.AcousticEchoCanceler#isAvailable isAvailable()} on the corresponding 343audio effect class.</p> 344 345 346<h3 id="Gapless">Gapless playback</h3> 347 348<p>You can now perform gapless playback between two separate 349{@link android.media.MediaPlayer} objects. At any time before your first {@link android.media.MediaPlayer} finishes, 350call {@link android.media.MediaPlayer#setNextMediaPlayer setNextMediaPlayer()} and Android 351attempts to start the second player the moment that the first one stops.</p> 352 353 354Media router. The new APIs MediaRouter, MediaRouteActionProvider, and MediaRouteButton provide 355standard mechanisms and UI for choosing where to play media. 356 357 358<h2 id="Camera">Camera</h2> 359 360<h3 id="AutoFocus">Auto focus movement</h3> 361 362<p>The new interface {@link android.hardware.Camera.AutoFocusMoveCallback} allows you to listen 363for changes to the auto focus movement. You can register your interface with {@link 364android.hardware.Camera#setAutoFocusMoveCallback setAutoFocusMoveCallback()}. Then when the camera 365is in a continuous autofocus mode ({@link 366android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO} or 367{@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE}), you'll receive a call 368to {@link android.hardware.Camera.AutoFocusMoveCallback#onAutoFocusMoving onAutoFocusMoving()}, 369which tells you whether auto focus has started moving or has stopped moving.</p> 370 371<h3 id="CameraSounds">Camera sounds</h3> 372 373<p>The {@link android.media.MediaActionSound} class provides a simple set of APIs to produce 374standard sounds made by the camera or other media actions. You should use these APIs to play 375the appropriate sound when building a custom still or video camera.</p> 376 377<p>To play a sound, simply instantiate a {@link android.media.MediaActionSound} object, call 378{@link android.media.MediaActionSound#load load()} to pre-load the desired sound, then at the 379appropriate time, call {@link android.media.MediaActionSound#play play()}.</p> 380 381 382 383<h2 id="Connectivity">Connectivity</h2> 384 385 386<h3 id="AndroidBeam">Android Beam</h3> 387 388<p>Android Beam™ now supports large payload transfers over Bluetooth. When you define the data 389to transfer with either the new {@link android.nfc.NfcAdapter#setBeamPushUris setBeamPushUris()} 390method or the new callback interface {@link android.nfc.NfcAdapter.CreateBeamUrisCallback}, Android 391hands off the data transfer to Bluetooth or another alternate transport to 392achieve faster transfer speeds. This is especially useful for large payloads such as image and 393audio files and requires no visible pairing between the devices. No additional work is required by 394your app to take advantage of transfers over Bluetooth.</p> 395 396<p>The {@link android.nfc.NfcAdapter#setBeamPushUris setBeamPushUris()} method takes an array of 397{@link android.net.Uri} objects that specify the data you want to transfer from your app. 398Alternatively, you can implement the {@link android.nfc.NfcAdapter.CreateBeamUrisCallback} 399interface, which you can specify for your activity by calling {@link 400android.nfc.NfcAdapter#setBeamPushUrisCallback setBeamPushUrisCallback()}.</p> 401 402<p>When using the 403callback interface, the system calls the interface's {@link 404android.nfc.NfcAdapter.CreateBeamUrisCallback#createBeamUris createBeamUris()} method when the 405user executes a share with Android Beam so that you can define the URIs to share at share-time. 406This is useful if the URIs to share might vary depending on the user context within the 407activity, whereas calling {@link android.nfc.NfcAdapter#setBeamPushUris setBeamPushUris()} is 408useful when the URIs to share are unchanging and you can safely define them ahead of time.</p> 409 410 411 412 413 414<h3 id="LocalNsd">Network service discovery</h3> 415 416<p>Android 4.1 adds support for multicast DNS-based service discovery, which allows you to 417find and connect to services offered by peer devices over Wi-Fi, such as mobile devices, 418printers, cameras, media players, and others that are registered on the local network.</p> 419 420<p>The new package {@link android.net.nsd} contains the new APIs that allow you to 421broadcast your services on the local network, discover local devices on the network, and 422connect to devices.</p> 423 424<p>To register your service, you must first create an {@link android.net.nsd.NsdServiceInfo} 425 object and define the various properties of your service with methods such as 426 {@link android.net.nsd.NsdServiceInfo#setServiceName setServiceName()}, 427 {@link android.net.nsd.NsdServiceInfo#setServiceType setServiceType()}, and 428 {@link android.net.nsd.NsdServiceInfo#setPort setPort()}. 429</p> 430 431<p>Then you need to implement {@link android.net.nsd.NsdManager.RegistrationListener} 432and pass it to {@link android.net.nsd.NsdManager#registerService registerService()} 433with your {@link android.net.nsd.NsdServiceInfo}.</p> 434 435<p>To discover services on the network, implement {@link 436 android.net.nsd.NsdManager.DiscoveryListener} and pass it to {@link 437 android.net.nsd.NsdManager#discoverServices discoverServices()}.</p> 438 439<p>When your {@link 440 android.net.nsd.NsdManager.DiscoveryListener} receives callbacks about services 441found, you need to resolve the service by calling 442{@link android.net.nsd.NsdManager#resolveService resolveService()}, passing it an 443implementation of {@link android.net.nsd.NsdManager.ResolveListener} that receives 444an {@link android.net.nsd.NsdServiceInfo} object that contains information about the 445discovered service, allowing you to initiate the connection.</p> 446 447 448 449<h3 id="WiFiNsd">Wi-Fi Direct service discovery</h3> 450 451<p>The Wi-Fi Direct APIs are enhanced in Android 4.1 to support pre-association service discovery in 452the {@link android.net.wifi.p2p.WifiP2pManager}. This allows you to discover and filter nearby 453devices by services using Wi-Fi Direct before connecting to one, while Network Service 454Discovery allows you to discover a service on an existing connected network (such as a local Wi-Fi 455network).</p> 456 457<p>To broadcast your app as a service over Wi-Fi so that other devices can discover 458 your app and connect to it, call {@link 459 android.net.wifi.p2p.WifiP2pManager#addLocalService addLocalService()} with a 460 {@link android.net.wifi.p2p.nsd.WifiP2pServiceInfo} object that describes your app services.</p> 461 462<p>To initiate discover of nearby devices over Wi-Fi, you need to first decide whether you'll 463 communicate using Bonjour or Upnp. To use Bonjour, first set up some callback listeners with 464 {@link android.net.wifi.p2p.WifiP2pManager#setDnsSdResponseListeners setDnsSdResponseListeners()}, which takes both a {@link android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener} and {@link android.net.wifi.p2p.WifiP2pManager.DnsSdTxtRecordListener}. To use Upnp, call 465 {@link android.net.wifi.p2p.WifiP2pManager#setUpnpServiceResponseListener setUpnpServiceResponseListener()}, which takes a {@link android.net.wifi.p2p.WifiP2pManager.UpnpServiceResponseListener}.</p> 466 467<p>Before you can start discovering services on local devices, you also need to call {@link android.net.wifi.p2p.WifiP2pManager#addServiceRequest addServiceRequest()}. When the {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} you pass to this method receives a 468successful callback, you can then begin discovering services on local devices by calling {@link 469android.net.wifi.p2p.WifiP2pManager#discoverServices discoverServices()}.</p> 470 471<p>When local services are discovered, you'll receive a callback to either the {@link 472android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener} or {@link 473android.net.wifi.p2p.WifiP2pManager.UpnpServiceResponseListener}, depending on whether you 474registered to use Bonjour or Upnp. The callback received in either case contains a 475{@link android.net.wifi.p2p.WifiP2pDevice} object representing the peer device.</p> 476 477 478 479 480<h3 id="NetworkUsage">Network usage</h3> 481 482<p>The new method {@link android.net.ConnectivityManager#isActiveNetworkMetered} allows you to 483check whether the device is currently connected to a metered network. By checking this state 484before performing intensive network transactions, you can help manage the data usage that may cost your users money and make 485informed decisions about whether to perform the transactions now or later (such as when the 486device becomes connected to Wi-Fi).</p> 487 488 489 490 491 492<h2 id="A11y">Accessibility</h2> 493 494<h3 id="">Accessibility service APIs</h3> 495 496<p>The reach of accessibility service APIs has been significantly increased in Android 4.1. It now 497allows you to build services that monitor and respond to more input events, such as complex gestures 498using {@link android.accessibilityservice.AccessibilityService#onGesture onGesture()} and other 499input events through additions to the {@link android.view.accessibility.AccessibilityEvent}, {@link 500android.view.accessibility.AccessibilityNodeInfo} and {@link 501android.view.accessibility.AccessibilityRecord} classes.</p> 502 503<p>Accessibility services can also perform actions on behalf of the user, including clicking, 504scrolling and stepping through text using {@link 505android.view.accessibility.AccessibilityNodeInfo#performAction performAction} and {@link 506android.view.accessibility.AccessibilityNodeInfo#setMovementGranularities 507setMovementGranularities}. The {@link 508android.accessibilityservice.AccessibilityService#performGlobalAction performGlobalAction()} method 509also allows services to perform actions such as Back, Home, and open Recent 510Apps and Notifications.</p> 511 512 513<h3 id="A11yCustomNav">Customizable app navigation</h3> 514 515<p>When building an Android app, you can now customize navigation schemes by finding focusable 516elements and input widgets using {@link 517android.view.accessibility.AccessibilityNodeInfo#findFocus findFocus()} and {@link 518android.view.accessibility.AccessibilityNodeInfo#focusSearch focusSearch()}, and set focus 519using {@link android.view.accessibility.AccessibilityNodeInfo#setAccessibilityFocused 520setAccessibilityFocused()}.</p> 521 522 523<h3 id="A11yStructure">More accessible widgets</h3> 524 525<p>The new {@code android.view.accessibility.AccessibilityNodeProvider} class allows you to 526surface complex custom views to accessibility services so they can present the information in a 527more accessible way. The {@code android.view.accessibility.AccessibilityNodeProvider} allows a user 528widget with advanced content, such as a calendar grid, to present a logical semantic structure for 529accessibility services that is completely separate from the widget’s layout structure. This semantic 530structure allows accessibility services to present a more useful interaction model for users who are 531visually impaired.</p> 532 533 534 535<h2 id="CopyPaste">Copy and Paste</h2> 536 537<h3 id="CopyIntent">Copy and paste with intents</h3> 538 539<p>You can now associate a {@link android.content.ClipData} object with an {@link 540android.content.Intent} using the {@link android.content.Intent#setClipData setClipData()} method. 541This is especially useful when using an intent to transfer multiple {@code content:} URIs to another 542application, such as when sharing multiple documents. The {@code content:} URIs supplied 543this way will also respect the intent's flags to offer read or write access, allowing you to grant 544access to multiple URIs in an the intent. When starting an {@link 545android.content.Intent#ACTION_SEND} or {@link 546android.content.Intent#ACTION_SEND_MULTIPLE} intent, the URIs supplied in the intent are now 547automatically propagated to the {@link android.content.ClipData} so that the receiver can have 548access granted to them.</p> 549 550 551<h5>Support for HTML and string styles</h5> 552 553<p>The {@link android.content.ClipData} class now supports styled text (either as HTML or 554Android <a 555href="{@docRoot}guide/topics/resources/string-resource.html#FormattingAndStyling">styled 556strings</a>). You can add HTML styled text to the {@link android.content.ClipData} with {@link 557android.content.ClipData#newHtmlText newHtmlText()}.</p> 558 559 560 561<h2 id="Renderscript">Renderscript</h2> 562 563<p>Renderscript computation functionality has been enhanced with the following features:</p> 564<ul> 565 <li>Support for multiple kernels within one script.</li> 566 <li>Support for reading from allocation with filtered samplers from compute in a new script API 567{@code rsSample}.</li> 568 <li>Support for different levels of FP precision in {@code #pragma}.</li> 569 <li>Support for querying additional information from RS objects from a compute script.</li> 570 <li>Numerous performance improvements.</li> 571</ul> 572 573<p>New pragmas are also available to define the floating point precision required by your 574compute Renderscripts. This lets you enable NEON like operations such as fast vector math operations 575on the CPU path that wouldn’t otherwise be possible with full IEEE 754-2008 standard.</p> 576 577<p class="note"><strong>Note:</strong> The experimental Renderscript graphics engine is now 578deprecated.</p> 579 580 581 582<h2 id="Animation">Animation</h2> 583 584<h3 id="ActivityOptions">Activity launch animations</h3> 585 586<p>You can now launch an {@link android.app.Activity} using zoom animations or 587your own custom animations. To specify the animation you want, use the {@link 588android.app.ActivityOptions} APIs to build a {@link android.os.Bundle} that you can 589then pass to any of the 590methods that start an activity, such as {@link 591android.app.Activity#startActivity(Intent,Bundle) startActivity()}.</p> 592 593<p>The {@link android.app.ActivityOptions} class includes a different method for each 594type of animation you may want to show as your activity opens:</p> 595<dl> 596 <dt>{@link android.app.ActivityOptions#makeScaleUpAnimation makeScaleUpAnimation()}</dt> 597 <dd>Creates an animation that scales up the activity window from a specified starting 598 position on the screen and a specified starting size. For example, the home screen in 599 Android 4.1 uses this when opening an app.</dd> 600 <dt>{@link android.app.ActivityOptions#makeThumbnailScaleUpAnimation 601 makeThumbnailScaleUpAnimation()}</dt> 602 <dd>Creates an animation that scales up the activity window starting from a specified 603 position and a provided thumbnail image. For example, the Recent Apps window in 604 Android 4.1 uses this when returning to an app.</dd> 605 <dt>{@link android.app.ActivityOptions#makeCustomAnimation 606 makeCustomAnimation()}</dt> 607 <dd>Creates an animation defined by your own resources: one that defines the animation for 608 the activity opening and another for the activity being stopped.</dd> 609</dl> 610 611 612 613<h3 id="TimeAnimator">Time animator</h3> 614 615<p>The new {@link android.animation.TimeAnimator} provides a simple callback 616 mechanism with the {@link android.animation.TimeAnimator.TimeListener} that notifies 617 you upon every frame of the animation. There is no duration, interpolation, or object value-setting with this Animator. The listener's callback receives information for each frame including 618 total elapsed time and the elapsed time since the previous animation frame.</p> 619 620 621 622 623<h2 id="UI">User Interface</h2> 624 625 626<h3 id="Notifications">Notifications</h3> 627 628<p>In Android 4.1, you can create notifications with larger content regions, big image previews, 629 multiple action buttons, and configurable priority.</p> 630 631<h5>Notification styles</h5> 632 633<p>The new method {@link android.app.Notification.Builder#setStyle setStyle()} allows you to specify 634 one of three new styles for your notification that each offer a larger content region. To 635specify the style for your large content region, pass {@link 636android.app.Notification.Builder#setStyle setStyle()} one of the following objects:</p> 637<dl> 638 <dt>{@link android.app.Notification.BigPictureStyle}</dt> 639 <dd>For notifications that includes a large image attachment.</dd> 640 <dt>{@link android.app.Notification.BigTextStyle}</dt> 641 <dd>For notifications that includes a lot of text, such as a single email.</dd> 642 <dt>{@link android.app.Notification.InboxStyle}</dt> 643 <dd>For notifications that include a list of strings, such as snippets from multiple emails.</dd> 644</dl> 645 646<h5>Notification actions</h5> 647 648<p>There's now support for up to two action buttons that appear at the bottom of the 649 notification message, whether your notification uses the normal or larger style.</p> 650 651<p>To add an action button, call {@link android.app.Notification.Builder#addAction 652 addAction()}. This method takes three arguments: a drawable resource for an icon, 653 text for the button, and a {@link android.app.PendingIntent} that defines the action 654 to perfrom.</p> 655 656 657<h5>Priorities</h5> 658 659<p>You can now hint to the system how important your notification is to affect the 660 order of your notification in the list by setting 661the priority with {@link android.app.Notification.Builder#setPriority setPriority()}. You 662can pass this one of five different priority levels defined by {@code PRIORITY_*} constants 663in the {@link android.app.Notification} class. The default is {@link 664android.app.Notification#PRIORITY_DEFAULT}, and there's two levels higher and two levels lower.</p> 665 666<p>High priority notifications are things that users generally want to respond to quickly, 667such as a new instant message, text message, or impending event reminder. Low priority 668notifications are things like expired calendar events or app promotions.</p> 669 670<h3 id="SystemUI">Controls for system UI</h3> 671 672<p>Android 4.0 (Ice Cream Sandwich) added new flags to control the visibility of the system UI 673elements, such as to dim the appearance of the system bar or make it disappear completely on handsets. 674Android 4.1 adds a few more flags that allow you to further control the appearance of system 675UI elements and your activity layout in relation to them by calling {@link 676android.view.View#setSystemUiVisibility setSystemUiVisibility()} 677and passing the following flags:</p> 678 679<dl> 680 <dt>{@link android.view.View#SYSTEM_UI_FLAG_FULLSCREEN}</dt> 681 <dd>Hides non-critical system UI (such as the status bar). 682 If your activity uses the action bar in overlay mode (by 683 enabling <a href="{@docRoot}reference/android/R.attr.html#windowActionBarOverlay">{@code 684 android:windowActionBarOverlay}</a>), then this flag also hides the action bar and does 685 so with a coordinated animation when both hiding and showing the two.</dd> 686 687 <dt>{@link android.view.View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}</dt> 688 <dd>Sets your activity layout to use the same screen area that's available when you've 689 enabled {@link android.view.View#SYSTEM_UI_FLAG_FULLSCREEN} even if the system UI elements 690 are still visible. Although parts of your layout will be overlayed by the 691 system UI, this is useful if your app often hides and shows the system UI with 692 {@link android.view.View#SYSTEM_UI_FLAG_FULLSCREEN}, because it avoids your layout from 693 adjusting to the new layout bounds each time the system UI hides or appears.</dd> 694 695 <dt>{@link android.view.View#SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}</dt> 696 <dd>Sets your activity layout to use the same screen area that's available when you've 697 enabled {@link android.view.View#SYSTEM_UI_FLAG_HIDE_NAVIGATION} (added in Android 4.0) 698 even if the system UI elements are still visible. Although parts of your layout will be 699 overlayed by the 700 navigation bar, this is useful if your app often hides and shows the navigation bar 701 with {@link android.view.View#SYSTEM_UI_FLAG_HIDE_NAVIGATION}, because it avoids your layout from 702 adjusting to the new layout bounds each time the navigation bar hides or appears.</dd> 703 704 <dt>{@link android.view.View#SYSTEM_UI_FLAG_LAYOUT_STABLE}</dt> 705 <dd>You might want to add this flag if you're using {@link 706 android.view.View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and/or {@link 707 android.view.View#SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} to ensure that when you call 708 {@link android.view.View#fitSystemWindows fitSystemWindows()} on a view that the 709 bounds defined remain consistent with regard to the available screen space. 710 That is, with this flag set, {@link android.view.View#fitSystemWindows 711 fitSystemWindows()} will behave as if the visibility of system UI elements is unchanged 712 even after you hide all system UI.</dd> 713 <dd></dd> 714</dl> 715 716<p>For more discussion about the other related system UI flags, read about 717 those added in <a href="{@docRoot}about/versions/android-4.0.html#SystemUI">Android 4.0</a>.</p> 718 719 720<h3 id="RemoteViews">Remote views</h3> 721 722<p>{@link android.widget.GridLayout} and {@link android.view.ViewStub} 723 are now remotable views so you can use them in layouts for your 724 app widgets and notification custom layouts.</p> 725 726 727 728<h3 id="Fonts">Font families</h3> 729 730<p>Android 4.1 adds several more variants of the Roboto font style for a total of 10 variants, 731 and they're all usable by apps. Your apps now have access to the full set of both light and 732condensed variants.</p> 733 734<p>The complete set of Roboto font variants available is:</p> 735 736<ul> 737 <li>Regular</li> 738 <li>Italic</li> 739 <li>Bold</li> 740 <li>Bold-italic</li> 741 <li>Light</li> 742 <li>Light-italic</li> 743 <li>Condensed regular</li> 744 <li>Condensed italic</li> 745 <li>Condensed bold</li> 746 <li>Condensed bold-italic</li> 747</ul> 748 749<p>You can apply any one of these with the new {@link android.R.attr#fontFamily} 750 attribute in combination with the {@link android.R.attr#textStyle} attribute.</p> 751 752<p>Supported values for {@link android.R.attr#fontFamily} are:</p> 753<ul> 754 <li>{@code "sans-serif"} for regular Roboto</li> 755 <li>{@code "sans-serif-light"} for Roboto Light</li> 756 <li>{@code "sans-serif-condensed"} for Roboto Condensed</li> 757</ul> 758 759<p>You can then apply bold and/or italic with {@link android.R.attr#textStyle} values 760{@code "bold"} and {@code "italic"}. You can apply both like so: {@code 761android:textStyle="bold|italic"}.</p> 762 763<p>You can also use {@link android.graphics.Typeface#create Typeface.create()}. 764 For example, {@code Typeface.create("sans-serif-light", Typeface.NORMAL)}.</p> 765 766 767 768 769 770 771<h2 id="Input">Input Framework</h2> 772 773 774<h3 id="InputDevice">Multiple input devices</h3> 775 776<p>The new {@link android.hardware.input.InputManager} class allows you to query the 777set of input devices current connected and register to be notified when a new device 778is added, changed, or removed. This is particularly useful if you're building a game 779that supports multiple players and you want to detect how many controllers are connected 780and when there are changes to the number of controllers.</p> 781 782<p>You can query all input devices connected by calling 783{@link android.hardware.input.InputManager#getInputDeviceIds()}. This returns 784an array of integers, each of which is an ID for a different input device. You can then call 785{@link android.hardware.input.InputManager#getInputDevice getInputDevice()} to acquire 786an {@link android.view.InputDevice} for a specified input device ID.</p> 787 788<p>If you want to be informed when new input devices are connected, changed, or disconnected, 789implement the {@link android.hardware.input.InputManager.InputDeviceListener} interface and 790register it with {@link android.hardware.input.InputManager#registerInputDeviceListener 791registerInputDeviceListener()}.</p> 792 793<h3 id="Vibrate">Vibrate for input controllers</h3> 794 795<p>If connected input devices have their own vibrate capabilities, you can now control 796the vibration of those devices using the existing {@link android.os.Vibrator} APIs simply 797by calling {@link android.view.InputDevice#getVibrator()} on the {@link android.view.InputDevice}.</p> 798 799 800 801<h2 id="Permissions">Permissions</h2> 802 803<p>The following are new permissions:</p> 804 805<dl> 806 <dt>{@link android.Manifest.permission#READ_EXTERNAL_STORAGE}</dt> 807 <dd>Provides protected read access to external storage. In Android 4.1 by 808 default all applications still have read 809access. This will be changed in a future release to require that applications explicitly request 810read access using this permission. If your application already requests write access, it will 811automatically get read access as well. There is a new developer option to turn on read access 812restriction, for developers to test their applications against how Android will behave in the 813future.</dd> 814 <dt>{@link android.Manifest.permission#READ_USER_DICTIONARY}</dt> 815 <dd>Allows an application to read the user dictionary. This should only be required by an 816IME, or a dictionary editor like the Settings app.</dd> 817 <dt>{@link android.Manifest.permission#READ_CALL_LOG}</dt> 818 <dd>Allows an application to read the system's call log that contains information about 819 incoming and outgoing calls.</dd> 820 <dt>{@link android.Manifest.permission#WRITE_CALL_LOG}</dt> 821 <dd>Allows an application to modify the system's call log stored on your phone</dd> 822 <dt>{@link android.Manifest.permission#WRITE_USER_DICTIONARY}</dt> 823 <dd>Allows an application to write to the user's word dictionary.</dd> 824</dl> 825 826 827<h2 id="DeviceFeatures">Device Features</h2> 828 829<p>Android 4.1 includes a new feature declaration for devices that are dedicated 830to displaying the user interface on a television screen: {@link 831android.content.pm.PackageManager#FEATURE_TELEVISION}. To declare that your app requires 832a television interface, declare this feature in your manifest file with the <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a> element:</p> 833<pre> 834<manifest ... > 835 <uses-feature android:name="android.hardware.type.television" 836 android:required="true" /> 837 ... 838</manifest> 839</pre> 840 841<p>This feature defines "television" to be a typical living room television experience: 842 displayed on a big screen, where the user is sitting far away and the dominant form of 843 input is be something like a d-pad, and generally not through touch or a 844 mouse/pointer-device.</p> 845 846 847 848 849 850 851 852 853