OSDN Git Service

more details about account access in restricted profiles
[android-x86/frameworks-base.git] / docs / html / about / versions / android-4.3.jd
1 page.title=Android 4.3 APIs
2 excludeFromSuggestions=true
3 sdk.platform.version=4.3
4 sdk.platform.apiLevel=18
5 @jd:body
6
7
8 <div id="qv-wrapper">
9 <div id="qv">
10
11 <h2>In this document
12     <a href="#" onclick="hideNestedItems('#toc43',this);return false;" class="header-toggle">
13         <span class="more">show more</span>
14         <span class="less" style="display:none">show less</span></a></h2>
15
16 <ol id="toc43" class="hide-nested">
17   <li><a href="#ApiLevel">Update your target API level</a></li>
18   <li><a href="#Behaviors">Important Behavior Changes</a>
19     <ol>
20       <li><a href="#BehaviorsIntents">If your app uses implicit intents...</a></li>
21       <li><a href="#BehaviorsAccounts">If your app depends on accounts...</a></li>
22     </ol>
23   </li>
24   <li><a href="#RestrictedProfiles">Restricted Profiles</a>
25     <ol>
26       <li><a href="#AccountsInProfile">Supporting accounts in a restricted profile</a></li>
27     </ol>
28   </li>
29   <li><a href="#Wireless">Wireless and Connectivity</a>
30     <ol>
31       <li><a href="#BTLE">Bluetooth Low Energy (Smart Ready)</a></li>
32       <li><a href="#WiFiScan">Wi-Fi scan-only mode</a></li>
33       <li><a href="#WiFiConfig">Wi-Fi configuration</a></li>
34       <li><a href="#QuickResponse">Quick response for incoming calls</a></li>
35     </ol>
36   </li>
37   <li><a href="#Multimedia">Multimedia</a>
38     <ol>
39       <li><a href="#DASH">MPEG DASH support</a></li>
40       <li><a href="#DRM">Media DRM</a></li>
41       <li><a href="#EncodingSurface">Video encoding from a Surface</a></li>
42       <li><a href="#MediaMuxing">Media muxing</a></li>
43       <li><a href="#ProgressAndScrubbing">Playback progress and scrubbing for RemoteControlClient</a></li>
44     </ol>
45   </li>
46   <li><a href="#Graphics">Graphics</a>
47     <ol>
48       <li><a href="#OpenGL">Support for OpenGL ES 3.0</a></li>
49       <li><a href="#MipMap">Mipmapping for drawables</a></li>
50     </ol>
51   </li>
52   <li><a href="#UI">User Interface</a>
53     <ol>
54       <li><a href="#ViewOverlay">View overlays</a></li>
55       <li><a href="#OpticalBounds">Optical bounds layout</a></li>
56       <li><a href="#AnimationRect">Animation for Rect values</a></li>
57       <li><a href="#AttachFocus">Window attach and focus listener</a></li>
58       <li><a href="#Overscan">TV overscan support</a></li>
59       <li><a href="#Orientation">Screen orientation</a></li>
60       <li><a href="#RotationAnimation">Rotation animations</a></li>
61     </ol>
62   </li>
63   <li><a href="#UserInput">User Input</a>
64     <ol>
65       <li><a href="#SignificantMotion">Detect significant motion</a></li>
66       <li><a href="#Sensors">New sensor types</a></li>
67     </ol>
68   </li>
69   <li><a href="#NotificationListener">Notification Listener</a></li>
70   <li><a href="#Contacts">Contacts Provider</a>
71     <ol>
72       <li><a href="#Contactables">Query for "contactables"</a></li>
73       <li><a href="#ContactsDelta">Query for contacts deltas</a></li>
74     </ol>
75   </li>
76   <li><a href="#Localization">Localization</a>
77     <ol>
78       <li><a href="#BiDi">Improved support for bi-directional text</a></li>
79     </ol>
80   </li>
81   <li><a href="#A11yService">Accessibility Services</a>
82     <ol>
83       <li><a href="#A11yKeyEvents">Handle key events</a></li>
84       <li><a href="#A11yText">Select text and copy/paste</a></li>
85       <li><a href="#A11yFeatures">Declare accessibility features</a></li>
86     </ol>
87   </li>
88   <li><a href="#Testing">Testing and Debugging</a>
89     <ol>
90       <li><a href="#UiAutomation">Automated UI testing</a></li>
91       <li><a href="#Systrace">Systrace events for apps</a></li>
92     </ol>
93   </li>
94   <li><a href="#Security">Security</a>
95     <ol>
96       <li><a href="#KeyStore">Android key store for app-private keys</a></li>
97       <li><a href="#HardwareKeyChain">Hardware credential storage</a></li>
98     </ol>
99   </li>
100   <li><a href="#Manifest">Manifest Declarations</a>
101     <ol>
102       <li><a href="#ManifestFeatures">Declarable required features</a></li>
103       <li><a href="#ManifestPermissions">User permissions</a></li>
104     </ol>
105   </li>
106 </ol>
107
108 <h2>See also</h2>
109 <ol>
110 <li><a href="{@docRoot}sdk/api_diff/18/changes.html">API
111 Differences Report &raquo;</a> </li>
112 <li><a
113 href="{@docRoot}tools/extras/support-library.html">Support Library</a></li>
114 </ol>
115
116 </div>
117 </div>
118
119
120
121 <p>API Level: {@sdkPlatformApiLevel}</p>
122
123 <p>Android {@sdkPlatformVersion} ({@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2})
124 is an update to the Jelly Bean release that offers new features for users and app
125 developers. This document provides an introduction to the most notable
126 new APIs.</p>
127
128 <p>As an app developer, you should download the Android {@sdkPlatformVersion} system image
129 and SDK platform from the <a href="{@docRoot}tools/help/sdk-manager.html">SDK Manager</a> as
130 soon as possible. If you don't have a device running Android {@sdkPlatformVersion} on which to
131 test your app, use the Android {@sdkPlatformVersion} system
132 image to test your app on the <a href="{@docRoot}tools/devices/emulator.html">Android emulator</a>.
133 Then build your apps against the Android {@sdkPlatformVersion} platform to begin using the
134 latest APIs.</p>
135
136
137 <h3 id="ApiLevel">Update your target API level</h3>
138
139 <p>To better optimize your app for devices running Android {@sdkPlatformVersion},
140   you should set your <a
141 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> to
142 <code>"{@sdkPlatformApiLevel}"</code>, install it on an Android {@sdkPlatformVersion} system image,
143 test it, then publish an update with this change.</p>
144
145 <p>You can use APIs in Android {@sdkPlatformVersion} while also supporting older versions by adding
146 conditions to your code that check for the system API level before executing
147 APIs not supported by your <a
148 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>.
149 To learn more about maintaining backward compatibility, read <a
150 href="{@docRoot}training/basics/supporting-devices/platforms.html">Supporting Different
151 Platform Versions</a>.</p>
152
153 <p>Various APIs are also available in the Android <a
154 href="{@docRoot}tools/extras/support-library.html">Support Library</a> that allow you to implement
155 new features on older versions of the platform.</p>
156
157 <p>For more information about how API levels work, read <a
158 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#ApiLevels">What is API
159 Level?</a></p>
160
161
162
163
164
165 <h2 id="Behaviors">Important Behavior Changes</h2>
166
167 <p>If you have previously published an app for Android, be aware that your app might
168 be affected by changes in Android {@sdkPlatformVersion}.</p>
169
170
171 <h3 id="BehaviorsIntents">If your app uses implicit intents...</h3>
172
173 <p>Your app might misbehave in a restricted profile environment.</p>
174
175 <p>Users in a <a href="#RestrictedProfiles">restricted profile</a> environment might not
176 have all the standard Android apps available. For example, a restricted profile might have the
177 web browser and camera app disabled. So your app should not make assumptions about which apps are
178 available, because if you call {@link android.app.Activity#startActivity startActivity()} without
179 verifying whether an app is available to handle the {@link android.content.Intent},
180 your app might crash in a restricted profile.</p>
181
182 <p>When using an implicit intent, you should always verify that an app is available to handle the intent by calling {@link android.content.Intent#resolveActivity resolveActivity()} or {@link android.content.pm.PackageManager#queryIntentActivities queryIntentActivities()}. For example:</p>
183
184 <pre>
185 Intent intent = new Intent(Intent.ACTION_SEND);
186 ...
187 if (intent.resolveActivity(getPackageManager()) != null) {
188     startActivity(intent);
189 } else {
190     Toast.makeText(context, R.string.app_not_available, Toast.LENGTH_LONG).show();
191 }
192 </pre>
193
194
195 <h3 id="BehaviorsAccounts">If your app depends on accounts...</h3>
196
197 <p>Your app might misbehave in a restricted profile environment.</p>
198
199 <p>Users within a restricted profile environment do not have access to user accounts by default.
200 If your app depends on an {@link android.accounts.Account}, then your app might crash or behave
201 unexpectedly when used in a restricted profile.</p>
202
203 <p>If you'd like to prevent restricted profiles from using your app entirely because your
204 app depends on account information that's sensitive, specify the <a
205 href="{@docRoot}guide/topics/manifest/application-element.html#requiredAccountType">{@code
206 android:requiredAccountType}</a> attribute in your manifest's <a
207 href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application>}</a>
208 element.</p>
209
210 <p>If you’d like to allow restricted profiles to continue using your app even though they can’t
211 create their own accounts, then you can either disable your app features that require an account
212 or allow restricted profiles to access the accounts created by the primary user. For more
213 information, see the section
214 below about <a href="#AccountsInProfile">Supporting accounts in a restricted profile</a>.</p>
215
216
217
218
219 <h2 id="RestrictedProfiles">Restricted Profiles</h2>
220
221 <p>On Android tablets, users can now create restricted profiles based on the primary user.
222 When users create a restricted profile, they can enable restrictions such as which apps are
223 available to the profile. A new set of APIs in Android 4.3 also allow you to build fine-grain
224 restriction settings for the apps you develop. For example, by using the new APIs, you can
225 allow users to control what type of content is available within your app when running in a
226 restricted profile environment.</p>
227
228 <p>The UI for users to control the restrictions you've built is managed by the system's
229 Settings application. To make your app's restriction settings appear to the user,
230 you must declare the restrictions your app provides by creating a {@link
231 android.content.BroadcastReceiver} that receives the {@link android.content.Intent#ACTION_GET_RESTRICTION_ENTRIES} intent. The system invokes this intent to query
232 all apps for available restrictions, then builds the UI to allow the primary user to
233 manage restrictions for each restricted profile. </p>
234
235 <p>In the {@link android.content.BroadcastReceiver#onReceive onReceive()} method of
236 your {@link android.content.BroadcastReceiver}, you must create a {@link
237 android.content.RestrictionEntry} for each restriction your app provides. Each {@link
238 android.content.RestrictionEntry} defines a restriction title, description, and one of the
239 following data types:</p>
240
241 <ul>
242   <li>{@link android.content.RestrictionEntry#TYPE_BOOLEAN} for a restriction that is
243   either true or false.
244   <li>{@link android.content.RestrictionEntry#TYPE_CHOICE} for a restriction that has
245   multiple choices that are mutually exclusive (radio button choices).
246   <li>{@link android.content.RestrictionEntry#TYPE_MULTI_SELECT} for a restriction that
247   has multiple choices that are <em>not</em> mutually exclusive (checkbox choices).
248 </ul>
249
250 <p>You then put all the {@link android.content.RestrictionEntry} objects into an {@link
251 java.util.ArrayList} and put it into the broadcast receiver's result as the value for the
252 {@link android.content.Intent#EXTRA_RESTRICTIONS_LIST} extra.</p>
253
254 <p>The system creates the UI for your app's restrictions in the Settings app and saves each
255 restriction with the unique key you provided for each {@link android.content.RestrictionEntry}
256 object. When the user opens your app, you can query for any current restrictions by
257 calling {@link android.os.UserManager#getApplicationRestrictions getApplicationRestrictions()}.
258 This returns a {@link android.os.Bundle} containing the key-value pairs for each restriction
259 you defined with the {@link android.content.RestrictionEntry} objects.</p>
260
261 <p>If you want to provide more specific restrictions that can't be handled by boolean, single
262 choice, and multi-choice values, then you can create an activity where the user can specify the
263 restrictions and allow users to open that activity from the restriction settings. In your
264 broadcast receiver, include the {@link android.content.Intent#EXTRA_RESTRICTIONS_INTENT} extra
265 in the result {@link android.os.Bundle}. This extra must specify an {@link android.content.Intent}
266 indicating the {@link android.app.Activity} class to launch (use the
267 {@link android.os.Bundle#putParcelable putParcelable()} method to pass {@link
268 android.content.Intent#EXTRA_RESTRICTIONS_INTENT} with the intent).
269 When the primary user enters your activity to set custom restrictions, your
270 activity must then return a result containing the restriction values in an extra using either
271 the {@link android.content.Intent#EXTRA_RESTRICTIONS_LIST} or {@link
272 android.content.Intent#EXTRA_RESTRICTIONS_BUNDLE} key, depending on whether you specify
273 {@link android.content.RestrictionEntry} objects or key-value pairs, respectively.</p>
274
275
276 <h3 id="AccountsInProfile">Supporting accounts in a restricted profile</h3>
277
278 <p>Any accounts added to the primary user are available to a restricted profile, but the
279 accounts are not accessible from the {@link android.accounts.AccountManager} APIs by default.
280 If you attempt to add an account with {@link android.accounts.AccountManager} while in a restricted
281 profile, you will get a failure result. Due to these restrictions, you have the following
282 three options:</p>
283
284 <li><strong>Allow access to the owner’s accounts from a restricted profile.</strong>
285 <p>To get access to an account from a restricted profile, you must add the <a href="{@docRoot}guide/topics/manifest/application-element.html#restrictedAccountType">{@code android:restrictedAccountType}</a> attribute to the <a
286 href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application></a> tag:</p>
287 <pre>
288 &lt;application ...
289     android:restrictedAccountType="com.example.account.type" >
290 </pre>
291
292 <p class="caution"><strong>Caution:</strong> Enabling this attribute provides your
293 app access to the primary user's accounts from restricted profiles. So you should allow this
294 only if the information displayed by your app does not reveal personally identifiable
295 information (PII) that’s considered sensitive. The system settings will inform the primary
296 user that your app grants restricted profiles to their accounts, so it should be clear to the user
297 that account access is important for your app's functionality. If possible, you should also
298 provide adequate restriction controls for the primary user that define how much account access
299 is allowed in your app.</p>
300 </li>
301
302
303 <li><strong>Disable certain functionality when unable to modify accounts.</strong>
304 <p>If you want to use accounts, but don’t actually require them for your app’s primary
305 functionality, you can check for account availability and disable features when not available.
306 You should first check if there is an existing account available. If not, then query whether
307 it’s possible to create a new account by calling {@link
308 android.os.UserManager#getUserRestrictions()} and check the {@link
309 android.os.UserManager#DISALLOW_MODIFY_ACCOUNTS} extra in the result. If it is {@code true},
310 then you should disable whatever functionality of your app requires access to accounts.
311 For example:</p>
312 <pre>
313 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
314 Bundle restrictions = um.getUserRestrictions();
315 if (restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false)) {
316    // cannot add accounts, disable some functionality
317 }
318 </pre>
319 <p class="note"><strong>Note:</strong> In this scenario, you should <em>not</em> declare
320 any new attributes in your manifest file.</p>
321 </li>
322
323 <li><strong>Disable your app when unable to access private accounts.</strong>
324 <p>If it’s instead important that your app not be available to restricted profiles because
325 your app depends on sensitive personal information in an account (and because restricted profiles
326 currently cannot add new accounts), add
327 the <a href="{@docRoot}guide/topics/manifest/application-element.html#requiredAccountType">{@code
328 android:requiredAccountType}</a> attribute to the <a
329 href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application></a> tag:</p>
330 <pre>
331 &lt;application ...
332     android:requiredAccountType="com.example.account.type" >
333 </pre>
334 <p>For example, the Gmail app uses this attribute to disable itself for restricted profiles,
335 because the owner's personal email should not be available to restricted profiles.</p>
336 </li>
337
338
339
340 <h2 id="Wireless">Wireless and Connectivity</h2>
341
342
343 <h3 id="BTLE">Bluetooth Low Energy (Smart Ready)</h3>
344
345 <p>Android now supports Bluetooth Low Energy (LE) with new APIs in {@link android.bluetooth}.
346 With the new APIs, you can build Android apps that communicate with Bluetooth Low Energy
347 peripherals such as heart rate monitors and pedometers.</p>
348
349 <p>Because Bluetooth LE is a hardware feature that is not available on all
350 Android-powered devices, you must declare in your manifest file a <a
351 href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code &lt;uses-feature>}</a>
352 element for {@code "android.hardware.bluetooth_le"}:</p>
353 <pre>
354 &lt;uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
355 </pre>
356
357 <p>If you're already familiar with Android's Classic Bluetooth APIs, notice that using the
358 Bluetooth LE APIs has some differences. Most importantly is that there's now a {@link
359 android.bluetooth.BluetoothManager} class that you should use for some high level operations
360 such as acquiring a {@link android.bluetooth.BluetoothAdapter}, getting a list of connected
361 devices, and checking the state of a device. For example, here's how you should now get the
362 {@link android.bluetooth.BluetoothAdapter}:</p>
363 <pre>
364 final BluetoothManager bluetoothManager =
365         (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
366 mBluetoothAdapter = bluetoothManager.getAdapter();
367 </pre>
368
369 <p>To discover Bluetooth LE peripherals, call {@link android.bluetooth.BluetoothAdapter#startLeScan
370 startLeScan()} on the {@link android.bluetooth.BluetoothAdapter}, passing it an implementation
371 of the {@link android.bluetooth.BluetoothAdapter.LeScanCallback} interface. When the Bluetooth
372 adapter detects a Bluetooth LE peripheral, your {@link
373 android.bluetooth.BluetoothAdapter.LeScanCallback} implementation receives a call to the
374 {@link android.bluetooth.BluetoothAdapter.LeScanCallback#onLeScan onLeScan()} method. This
375 method provides you with a {@link android.bluetooth.BluetoothDevice} object representing the
376 detected device, the RSSI value for the device, and a byte array containing the device's
377 advertisement record.</p>
378
379 <p>If you want to scan for only specific types of peripherals, you can instead call {@link
380 android.bluetooth.BluetoothAdapter#startLeScan startLeScan()} and include an array of {@link
381 java.util.UUID} objects that specify the GATT services your app supports.</p>
382
383 <p class="note"><strong>Note:</strong> You can only scan for Bluetooth LE devices <em>or</em>
384 scan for Classic Bluetooth devices using previous APIs. You cannot scan for both LE and Classic
385 Bluetooth devices at once.</p>
386
387 <p>To then connect to a Bluetooth LE peripheral, call {@link
388 android.bluetooth.BluetoothDevice#connectGatt connectGatt()} on the corresponding
389 {@link android.bluetooth.BluetoothDevice} object, passing it an implementation of
390 {@link android.bluetooth.BluetoothGattCallback}. Your implementation of {@link
391 android.bluetooth.BluetoothGattCallback} receives callbacks regarding the connectivity
392 state with the device and other events. It's during the {@link
393 android.bluetooth.BluetoothGattCallback#onConnectionStateChange onConnectionStateChange()}
394 callback that you can begin communicating with the device if the method passes {@link
395 android.bluetooth.BluetoothProfile#STATE_CONNECTED} as the new state.</p>
396
397 <p>Accessing Bluetooth features on a device also requires that your app request certain
398 Bluetooth user permissions. For more information, see the <a
399 href="{@docRoot}guide/topics/connectivity/bluetooth-le.html">Bluetooth Low Energy</a> API guide.</p>
400
401
402 <h3 id="WiFiScan">Wi-Fi scan-only mode</h3>
403
404 <p>When attempting to identify the user's location, Android may use Wi-Fi to help determine
405 the location by scanning nearby access points. However, users often keep Wi-Fi turned off to
406 conserve battery, resulting in location data that's less accurate. Android now includes a
407 scan-only mode that allows the device Wi-Fi to scan access points to help obtain the location
408 without connecting to an access point, thus greatly reducing battery usage.</p>
409
410 <p>If you want to acquire the user's location but Wi-Fi is currently off, you can request the
411 user to enable Wi-Fi scan-only mode by calling {@link android.content.Context#startActivity
412 startActivity()} with the action {@link
413 android.net.wifi.WifiManager#ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE}.</p>
414
415
416 <h3 id="WiFiConfig">Wi-Fi configuration</h3>
417
418 <p>New {@link android.net.wifi.WifiEnterpriseConfig} APIs allow enterprise-oriented services to
419 automate Wi-Fi configuration for managed devices.</p>
420
421
422 <h3 id="QuickResponse">Quick response for incoming calls</h3>
423
424 <p>Since Android 4.0, a feature called "Quick response" allows users to respond to incoming
425 calls with an immediate text message without needing to pick up the call or unlock the device.
426 Until now, these quick messages were always handled by the default Messaging app. Now any app
427 can declare its capability to handle these messages by creating a {@link android.app.Service}
428 with an intent filter for {@link android.telephony.TelephonyManager#ACTION_RESPOND_VIA_MESSAGE}.</p>
429
430 <p>When the user responds to an incoming call with a quick response, the Phone app sends
431 the {@link android.telephony.TelephonyManager#ACTION_RESPOND_VIA_MESSAGE} intent with a URI
432 describing the recipient (the caller) and the {@link android.content.Intent#EXTRA_TEXT} extra
433 with the message the user wants to send. When your service receives the intent, it should deliver
434 the message and immediately stop itself (your app should not show an activity).</p>
435
436 <p>In order to receive this intent, you must declare the {@link
437 android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE} permission.</p>
438
439
440
441 <h2 id="Multimedia">Multimedia</h2>
442
443 <h3 id="DASH">MPEG DASH support</h3>
444
445 <p>Android now supports Dynamic Adaptive Streaming over HTTP (DASH) in accordance with the
446 ISO/IEC 23009-1 standard, using existing APIs in {@link android.media.MediaCodec} and {@link
447 android.media.MediaExtractor}. The framework underlying these APIs has been updated to support
448 parsing of fragmented MP4 files, but your app is still responsible for parsing the MPD metadata
449 and passing the individual streams to {@link android.media.MediaExtractor}.</p>
450
451 <p>If you want to use DASH with encrypted content, notice that the {@link android.media.MediaExtractor#getSampleCryptoInfo getSampleCryptoInfo()} method returns the {@link
452 android.media.MediaCodec.CryptoInfo} metadata describing the structure of each encrypted media
453 sample. Also, the {@link android.media.MediaExtractor#getPsshInfo()} method has been added to
454 {@link android.media.MediaExtractor} so you can access the PSSH metadata for your DASH media.
455 This method returns a map of {@link java.util.UUID} objects to bytes, with the
456 {@link java.util.UUID} specifying the crypto scheme, and the bytes being the data specific
457 to that scheme.</p>
458
459
460 <h3 id="DRM">Media DRM</h3>
461
462 <p>The new {@link android.media.MediaDrm} class provides a modular solution for digital rights
463 management (DRM) with your media content by separating DRM concerns from media playback. For
464 instance, this API separation allows you to play back Widevine-encrypted content without having
465 to use the Widevine media format. This DRM solution also supports DASH Common Encryption so you
466 can use a variety of DRM schemes with your streaming content.</p>
467
468 <p>You can use {@link android.media.MediaDrm} to obtain opaque key-request messages and process
469 key-response messages from the server for license acquisition and provisioning. Your app is
470 responsible for handling the network communication with the servers; the {@link
471 android.media.MediaDrm} class provides only the ability to generate and process the messages.</p>
472
473 <p>The {@link android.media.MediaDrm} APIs are  intended to be used in conjunction with the
474 {@link android.media.MediaCodec} APIs that were introduced in Android 4.1 (API level 16),
475 including {@link android.media.MediaCodec} for encoding and decoding your content, {@link
476 android.media.MediaCrypto} for handling encrypted content, and {@link android.media.MediaExtractor}
477 for extracting and demuxing your content.</p>
478
479 <p>You must first construct {@link android.media.MediaExtractor} and
480 {@link android.media.MediaCodec} objects. You can then access the DRM-scheme-identifying
481 {@link java.util.UUID}, typically from metadata in the content, and use it to construct an
482 instance of a {@link android.media.MediaDrm} object with its constructor.</p>
483
484
485 <h3 id="EncodingSurface">Video encoding from a Surface</h3>
486
487 <p>Android 4.1 (API level 16) added the {@link android.media.MediaCodec} class for low-level
488 encoding and decoding of media content. When encoding video, Android 4.1 required that you provide
489 the media with a {@link java.nio.ByteBuffer} array, but Android 4.3 now allows you to use a {@link
490 android.view.Surface} as the input to an encoder. For instance, this allows you to encode input
491 from an existing video file or using frames generated from OpenGL ES.</p>
492
493 <p>To use a {@link android.view.Surface} as the input to your encoder, first call {@link
494 android.media.MediaCodec#configure configure()} for your {@link android.media.MediaCodec}.
495 Then call {@link android.media.MediaCodec#createInputSurface()} to receive the {@link
496 android.view.Surface} upon which you can stream your media.</p>
497
498 <p>For example, you can use the given {@link android.view.Surface} as the window for an OpenGL
499 context by passing it to {@link android.opengl.EGL14#eglCreateWindowSurface
500 eglCreateWindowSurface()}. Then while rendering the surface, call {@link
501 android.opengl.EGL14#eglSwapBuffers eglSwapBuffers()} to pass the frame to the {@link
502 android.media.MediaCodec}.</p>
503
504 <p>To begin encoding, call {@link android.media.MediaCodec#start()} on the {@link
505 android.media.MediaCodec}. When done, call {@link android.media.MediaCodec#signalEndOfInputStream}
506 to terminate encoding, and call {@link android.view.Surface#release()} on the
507 {@link android.view.Surface}.</p>
508
509
510 <h3 id="MediaMuxing">Media muxing</h3>
511
512 <p>The new {@link android.media.MediaMuxer} class enables multiplexing between one audio stream
513 and one video stream. These APIs serve as a counterpart to the {@link android.media.MediaExtractor}
514 class added in Android 4.2 for de-multiplexing (demuxing) media.</p>
515
516 <p>Supported output formats are defined in {@link android.media.MediaMuxer.OutputFormat}. Currently,
517 MP4 is the only supported output format and {@link android.media.MediaMuxer} currently supports
518 only one audio stream and/or one video stream at a time.</p>
519
520 <p>{@link android.media.MediaMuxer} is mostly designed to work with {@link android.media.MediaCodec}
521 so you can perform video processing through {@link android.media.MediaCodec} then save the
522 output to an MP4 file through {@link android.media.MediaMuxer}. You can also use {@link
523 android.media.MediaMuxer} in combination with {@link android.media.MediaExtractor} to perform
524 media editing without the need to encode or decode.</p>
525
526
527 <h3 id="ProgressAndScrubbing">Playback progress and scrubbing for RemoteControlClient</h3>
528
529 <p>In Android 4.0 (API level 14), the {@link android.media.RemoteControlClient} was added to
530 enable media playback controls from remote control clients such as the controls available on the
531 lock screen. Android 4.3 now provides the ability for such controllers to display the playback
532 position and controls for scrubbing the playback. If you've enabled remote control for your
533 media app with the {@link android.media.RemoteControlClient} APIs, then you can allow playback
534 scrubbing by implementing two new interfaces.</p>
535
536 <p>First, you must enable the {@link
537 android.media.RemoteControlClient#FLAG_KEY_MEDIA_POSITION_UPDATE} flag by passing it to
538 {@link android.media.RemoteControlClient#setTransportControlFlags setTransportControlsFlags()}.</p>
539
540 <p>Then implement the following two new interfaces:</p>
541 <dl>
542   <dt>{@link android.media.RemoteControlClient.OnGetPlaybackPositionListener}</dt>
543   <dd>This includes the callback {@link android.media.RemoteControlClient.OnGetPlaybackPositionListener#onGetPlaybackPosition}, which requests the current position
544   of your media when the remote control needs to update the progress in its UI.</dd>
545
546   <dt>{@link android.media.RemoteControlClient.OnPlaybackPositionUpdateListener}</dt>
547   <dd>This includes the callback {@link android.media.RemoteControlClient.OnPlaybackPositionUpdateListener#onPlaybackPositionUpdate onPlaybackPositionUpdate()}, which
548   tells your app the new time code for your media when the user scrubs the playback with the
549   remote control UI.
550     <p>Once you update your playback with the new position, call {@link
551     android.media.RemoteControlClient#setPlaybackState setPlaybackState()} to indicate the
552     new playback state, position, and speed.</p>
553   </dd>
554 </dl>
555
556 <p>With these interfaces defined, you can set them for your {@link
557 android.media.RemoteControlClient} by calling {@link android.media.RemoteControlClient#setOnGetPlaybackPositionListener setOnGetPlaybackPositionListener()} and
558 {@link android.media.RemoteControlClient#setPlaybackPositionUpdateListener
559 setPlaybackPositionUpdateListener()}, respectively.</p>
560
561
562
563 <h2 id="Graphics">Graphics</h2>
564
565 <h3 id="OpenGL">Support for OpenGL ES 3.0</h3>
566
567 <p>Android 4.3 adds Java interfaces and native support for OpenGL ES 3.0. Key new functionality
568 provided in OpenGL ES 3.0 includes:</p>
569 <ul>
570   <li>Acceleration of advanced visual effects</li>
571   <li>High quality ETC2/EAC texture compression as a standard feature</li>
572   <li>A new version of the GLSL ES shading language with integer and 32-bit floating point support</li>
573   <li>Advanced texture rendering</li>
574   <li>Broader standardization of texture size and render-buffer formats</li>
575 </ul>
576
577 <p>The Java interface for OpenGL ES 3.0 on Android is provided with {@link android.opengl.GLES30}.
578 When using OpenGL ES 3.0, be sure that you declare it in your manifest file with the
579 <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature></a>
580 tag and the {@code android:glEsVersion} attribute. For example:</p>
581 <pre>
582 &lt;manifest>
583     &lt;uses-feature android:glEsVersion="0x00030000" />
584     ...
585 &lt;/manifest>
586 </pre>
587
588 <p>And remember to specify the OpenGL ES context by calling {@link android.opengl.GLSurfaceView#setEGLContextClientVersion setEGLContextClientVersion()}, passing {@code 3} as the version.</p>
589
590
591 <h3 id="MipMap">Mipmapping for drawables</h3>
592
593 <p>Using a mipmap as the source for your bitmap or drawable is a simple way to provide a
594 quality image and various image scales, which can be particularly useful if you expect your
595 image to be scaled during an animation.</p>
596
597 <p>Android 4.2 (API level 17) added support for mipmaps in the {@link android.graphics.Bitmap}
598 class&mdash;Android swaps the mip images in your {@link android.graphics.Bitmap} when you've
599 supplied a mipmap source and have enabled {@link android.graphics.Bitmap#setHasMipMap
600 setHasMipMap()}. Now in Android 4.3, you can enable mipmaps for a {@link
601 android.graphics.drawable.BitmapDrawable} object as well, by providing a mipmap asset and
602 setting the {@code android:mipMap} attribute in a bitmap resource file or by calling {@link
603 android.graphics.drawable.BitmapDrawable#hasMipMap hasMipMap()}.
604 </p>
605
606
607
608 <h2 id="UI">User Interface</h2>
609
610 <h3 id="ViewOverlay">View overlays</h3>
611
612 <p>The new {@link android.view.ViewOverlay} class provides a transparent layer on top of
613 a {@link android.view.View} on which you can add visual content and which does not affect
614 the layout hierarchy. You can get a {@link android.view.ViewOverlay} for any {@link
615 android.view.View} by calling {@link android.view.View#getOverlay}. The overlay
616 always has the same size and position as its host view (the view from which it was created),
617 allowing you to add content that appears in front of the host view, but which cannot extend
618 the bounds of that host view.
619 </p>
620
621 <p>Using a {@link android.view.ViewOverlay} is particularly useful when you want to create
622 animations such as sliding a view outside of its container or moving items around the screen
623 without affecting the view hierarchy. However, because the usable area of an overlay is
624 restricted to the same area as its host view, if you want to animate a view moving outside
625 its position in the layout, you must use an overlay from a parent view that has the desired
626 layout bounds.</p>
627
628 <p>When you create an overlay for a widget view such as a {@link android.widget.Button}, you
629 can add {@link android.graphics.drawable.Drawable} objects to the overlay by calling
630 {@link android.view.ViewOverlay#add(Drawable)}. If you call {@link
631 android.view.ViewGroup#getOverlay} for a layout view, such as {@link android.widget.RelativeLayout},
632 the object returned is a {@link android.view.ViewGroupOverlay}. The
633 {@link android.view.ViewGroupOverlay} class is a subclass
634 of {@link android.view.ViewOverlay} that  also allows you to add {@link android.view.View}
635 objects by calling {@link android.view.ViewGroupOverlay#add(View)}.
636 </p>
637
638 <p class="note"><strong>Note:</strong> All drawables and views that you add to an overlay
639 are visual only. They cannot receive focus or input events.</p>
640
641 <p>For example, the following code animates a view sliding to the right by placing the view
642 in the parent view's overlay, then performing a translation animation on that view:</p>
643 <pre>
644 View view = findViewById(R.id.view_to_remove);
645 ViewGroup container = (ViewGroup) view.getParent();
646 container.getOverlay().add(view);
647 ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationX", container.getRight());
648 anim.start();
649 </pre>
650
651
652 <h3 id="OpticalBounds">Optical bounds layout</h3>
653
654 <p>For views that contain nine-patch background images, you can now specify that they should
655 be aligned with neighboring views based on the "optical" bounds of the background image rather
656 than the "clip" bounds of the view.</p>
657
658 <p>For example, figures 1 and 2 each show the same layout, but the version in figure 1 is
659 using clip bounds (the default behavior), while figure 2 is using optical bounds. Because the
660 nine-patch images used for the button and the photo frame include padding around the edges,
661 they don’t appear to align with each other or the text when using clip bounds.</p>
662
663 <p class="note"><strong>Note:</strong> The screenshot in figures 1 and 2 have the "Show
664 layout bounds" developer setting enabled. For each view, red lines indicate the optical
665 bounds, blue lines indicate the clip bounds, and pink indicates margins.</p>
666
667 <script type="text/javascript">
668 function toggleOpticalImages(mouseover) {
669
670   $("img.optical-img").each(function() {
671     $img = $(this);
672     var index = $img.attr('src').lastIndexOf("/") + 1;
673     var path = $img.attr('src').substr(0,index);
674     var name = $img.attr('src').substr(index);
675     var splitname;
676     var highres = false;
677     if (name.indexOf("@2x") != -1) {
678       splitname = name.split("@2x.");
679       highres = true;
680     } else {
681       splitname = name.split(".");
682     }
683
684     var newname;
685     if (mouseover) {
686       if (highres) {
687         newname = splitname[0] + "-normal@2x.png";
688       } else {
689         newname = splitname[0] + "-normal.png";
690       }
691     } else {
692       if (highres) {
693         newname = splitname[0].split("-normal")[0] + "@2x.png";
694       } else {
695         newname = splitname[0].split("-normal")[0] + ".png";
696       }
697     }
698
699     $img.attr('src', path + newname);
700
701   });
702 }
703 </script>
704
705 <p class="table-caption"><em>Mouse over to hide the layout bounds.</em></p>
706 <div style="float:left;width:296px">
707 <img src="{@docRoot}images/tools/clipbounds@2x.png" width="296" alt="" class="optical-img"
708     onmouseover="toggleOpticalImages(true)" onmouseout="toggleOpticalImages(false)" />
709 <p class="img-caption"><strong>Figure 1.</strong> Layout using clip bounds (default).</p>
710 </div>
711 <div style="float:left;width:296px;margin-left:60px">
712 <img src="{@docRoot}images/tools/opticalbounds@2x.png" width="296" alt="" class="optical-img"
713     onmouseover="toggleOpticalImages(true)" onmouseout="toggleOpticalImages(false)" />
714 <p class="img-caption"><strong>Figure 2.</strong> Layout using optical bounds.</p>
715 </div>
716
717
718 <p style="clear:left">To align the views based on their optical bounds, set the {@code android:layoutMode} attribute to {@code "opticalBounds"} in one of the parent layouts. For example:</p>
719
720 <pre>
721 &lt;LinearLayout android:layoutMode="opticalBounds" ... >
722 </pre>
723
724
725 <div class="figure" style="width:155px">
726 <img src="{@docRoot}images/tools/ninepatch_opticalbounds@2x.png" width="121" alt="" />
727 <p class="img-caption"><strong>Figure 3.</strong> Zoomed view of the Holo button nine-patch with
728 optical bounds.
729 </p>
730 </div>
731
732 <p>For this to work, the nine-patch images applied to the background of your views must specify
733 the optical bounds using red lines along the bottom and right-side of the nine-patch file (as
734 shown in figure 3). The red lines indicate the region that should be subtracted from
735 the clip bounds, leaving the optical bounds of the image.</p>
736
737 <p>When you enable optical bounds for a {@link android.view.ViewGroup} in your layout, all
738 descendant views inherit the optical bounds layout mode unless you override it for a group by
739 setting {@code android:layoutMode} to {@code "clipBounds"}. All layout elements also honor the
740 optical bounds of their child views, adapting their own bounds based on the optical bounds of
741 the views within them. However, layout elements (subclasses of {@link android.view.ViewGroup})
742 currently do not support optical bounds for nine-patch images applied to their own background.</p>
743
744 <p>If you create a custom view by subclassing {@link android.view.View}, {@link android.view.ViewGroup}, or any subclasses thereof, your view will inherit these optical bound behaviors.</p>
745
746 <p class="note"><strong>Note:</strong> All widgets supported by the Holo theme have been updated
747 with optical bounds, including {@link android.widget.Button},  {@link android.widget.Spinner},
748 {@link android.widget.EditText}, and others. So you can immediately benefit by setting the
749 {@code android:layoutMode} attribute to {@code "opticalBounds"} if your app applies a Holo theme
750 ({@link android.R.style#Theme_Holo Theme.Holo}, {@link android.R.style#Theme_Holo_Light
751 Theme.Holo.Light}, etc.).
752 </p>
753
754 <p>To specify optical bounds for your own nine-patch images with the <a
755 href="{@docRoot}tools/help/draw9patch.html">Draw 9-patch</a> tool, hold CTRL when clicking on
756 the border pixels.</p>
757
758
759
760
761 <h3 id="AnimationRect">Animation for Rect values</h3>
762
763 <p>You can now animate between two {@link android.graphics.Rect} values with the new {@link
764 android.animation.RectEvaluator}. This new class is an implementation of {@link
765 android.animation.TypeEvaluator} that you can pass to {@link
766 android.animation.ValueAnimator#setEvaluator ValueAnimator.setEvaluator()}.
767 </p>
768
769 <h3 id="AttachFocus">Window attach and focus listener</h3>
770
771 <p>Previously, if you wanted to listen for when your view attached/detached to the window or
772 when its focus changed, you needed to override the {@link android.view.View} class to
773 implement {@link android.view.View#onAttachedToWindow onAttachedToWindow()} and {@link
774 android.view.View#onDetachedFromWindow onDetachedFromWindow()}, or  {@link
775 android.view.View#onWindowFocusChanged onWindowFocusChanged()}, respectively.
776 </p>
777
778 <p>Now, to receive attach and detach events you can instead implement {@link
779 android.view.ViewTreeObserver.OnWindowAttachListener} and set it on a view with
780 {@link android.view.ViewTreeObserver#addOnWindowAttachListener addOnWindowAttachListener()}.
781 And to receive focus events, you can implement {@link
782 android.view.ViewTreeObserver.OnWindowFocusChangeListener} and set it on a view with
783 {@link android.view.ViewTreeObserver#addOnWindowFocusChangeListener
784 addOnWindowFocusChangeListener()}.
785 </p>
786
787
788 <h3 id="Overscan">TV overscan support</h3>
789
790 <p>To be sure your app fills the entire screen on every television, you can now enable overscan
791 for you app layout. Overscan mode is determined by the {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_OVERSCAN} flag, which you can enable with platform themes such as
792 {@link android.R.style#Theme_DeviceDefault_NoActionBar_Overscan} or by enabling the
793 {@link android.R.attr#windowOverscan} style in a custom theme.</p>
794
795
796 <h3 id="Orientation">Screen orientation</h3>
797
798 <p>The <a
799 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity>}</a>
800 tag's <a
801 href="{@docRoot}guide/topics/manifest/activity-element.html#screen">{@code screenOrientation}</a>
802 attribute now supports additional values to honor the user's preference for auto-rotation:</p>
803 <dl>
804 <dt>{@code "userLandscape"}</dt>
805 <dd>Behaves the same as {@code "sensorLandscape"}, except if the user disables auto-rotate
806 then it locks in the normal landscape orientation and will not flip.
807 </dd>
808
809 <dt>{@code "userPortrait"}</dt>
810 <dd>Behaves the same as {@code "sensorPortrait"}, except if the user disables auto-rotate then
811 it locks in the normal portrait orientation and will not flip.
812 </dd>
813
814 <dt>{@code "fullUser"}</dt>
815 <dd>Behaves the same as {@code "fullSensor"} and allows rotation in all four directions, except
816 if the user disables auto-rotate then it locks in the user's preferred orientation.
817 </dd></dl>
818
819 <p>Additionally, you can now also declare {@code "locked"} to lock your app's orientation into
820 the screen's current orientation.</p>
821
822
823 <h3 id="RotationAnimation">Rotation animations</h3>
824
825 <p>The new {@link android.view.WindowManager.LayoutParams#rotationAnimation} field in
826 {@link android.view.WindowManager} allows you to select between one of three animations you
827 want to use when the system switches screen orientations. The three animations are:</p>
828 <ul>
829   <li>{@link android.view.WindowManager.LayoutParams#ROTATION_ANIMATION_CROSSFADE}</li>
830   <li>{@link android.view.WindowManager.LayoutParams#ROTATION_ANIMATION_JUMPCUT}</li>
831   <li>{@link android.view.WindowManager.LayoutParams#ROTATION_ANIMATION_ROTATE}</li>
832 </ul>
833
834 <p class="note"><strong>Note:</strong> These animations are available only if you've set your activity to use "fullscreen" mode, which you can enable with themes such as {@link android.R.style#Theme_Holo_NoActionBar_Fullscreen Theme.Holo.NoActionBar.Fullscreen}.</p>
835
836 <p>For example, here's how you can enable the "crossfade" animation:</p>
837 <pre>
838 protected void onCreate(Bundle savedInstanceState) {
839     super.onCreate(savedInstanceState);
840
841     WindowManager.LayoutParams params = getWindow().getAttributes();
842     params.rotationAnimation = WindowManager.LayoutParams.ROTATION_ANIMATION_CROSSFADE;
843     getWindow().setAttributes(params);
844     ...
845 }
846 </pre>
847
848
849 <h2 id="UserInput">User Input</h2>
850
851 <h3 id="SignificantMotion">Detect significant motion</h3>
852
853 <p>The {@link android.hardware.SensorManager} APIs now allow you to request a callback when the
854 device sensors detect "significant motion." For instance, this event may be triggered by new
855 motion such as when the user starts to walk.</p>
856
857 <p>To register a listener for significant motion, extend the {@link android.hardware.TriggerEventListener} class and implement the {@link android.hardware.TriggerEventListener#onTrigger onTrigger()} callback method. Then register your event listener with the {@link android.hardware.SensorManager} by passing it to {@link android.hardware.SensorManager#requestTriggerSensor requestTriggerSensor()}, passing it your {@link android.hardware.TriggerEventListener} and {@link android.hardware.Sensor#TYPE_SIGNIFICANT_MOTION}.</p>
858
859 <h3 id="Sensors">New sensor types</h3>
860 <p>The new {@link android.hardware.Sensor#TYPE_GAME_ROTATION_VECTOR} sensor allows you to detect the device's rotations without worrying about magnetic interferences. Unlike the {@link android.hardware.Sensor#TYPE_ROTATION_VECTOR} sensor, the {@link android.hardware.Sensor#TYPE_GAME_ROTATION_VECTOR} is not based on magnetic north.</p>
861
862 <p>The new {@link android.hardware.Sensor#TYPE_GYROSCOPE_UNCALIBRATED} and {@link
863 android.hardware.Sensor#TYPE_MAGNETIC_FIELD_UNCALIBRATED} sensors provide raw sensor data without
864 consideration for bias estimations. That is, the existing {@link
865 android.hardware.Sensor#TYPE_GYROSCOPE} and {@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD}
866 sensors provide sensor data that takes into account estimated bias from gyro-drift and hard iron
867 in the device, respectively. Whereas the new "uncalibrated" versions of these sensors instead provide
868 the raw sensor data and offer the estimated bias values separately. These sensors allow you to
869 provide your own custom calibration for the sensor data by enhancing the estimated bias with
870 external data.</p>
871
872
873
874 <h2 id="NotificationListener">Notification Listener</h2>
875
876 <p>Android 4.3 adds a new service class, {@link android.service.notification.NotificationListenerService}, that allows your app to receive information about new notifications as they are posted by the system. </p>
877
878 <p>If your app currently uses the accessibility service APIs to access system notifications, you should update your app to use these APIs instead.</p>
879
880
881
882
883 <h2 id="Contacts">Contacts Provider</h2>
884
885 <h3 id="Contactables">Query for "contactables"</h3>
886
887 <p>The new Contacts Provider query, {@link android.provider.ContactsContract.CommonDataKinds.Contactables#CONTENT_URI Contactables.CONTENT_URI}, provides an efficient way to get one {@link android.database.Cursor} that contains all email addresses and phone numbers belonging to all contacts matching the specified query.</p>
888
889
890 <h3 id="ContactsDelta">Query for contacts deltas</h3>
891
892 <p>New APIs have been added to Contacts Provider that allow you to efficiently query recent changes to the contacts data. Previously, your app could be notified when something in the contacts data changed, but you would not know exactly what changed and would need to retrieve all contacts then iterate through them to discover the change.</p>
893
894 <p>To track changes to inserts and updates, you can now include the {@link android.provider.ContactsContract.ContactsColumns#CONTACT_LAST_UPDATED_TIMESTAMP} parameter with your selection to query only the contacts that have changed since the last time you queried the provider.</p>
895
896 <p>To track which contacts have been deleted, the new table {@link android.provider.ContactsContract.DeletedContacts} provides a log of contacts that have been deleted (but each contact deleted is held in this table for a limited time). Similar to {@link android.provider.ContactsContract.ContactsColumns#CONTACT_LAST_UPDATED_TIMESTAMP}, you can use the new selection parameter, {@link android.provider.ContactsContract.DeletedContacts#CONTACT_DELETED_TIMESTAMP} to check which contacts have been deleted since the last time you queried the provider. The table also contains the constant {@link android.provider.ContactsContract.DeletedContacts#DAYS_KEPT_MILLISECONDS} containing the number of days (in milliseconds) that the log will be kept.</p>
897
898 <p>Additionally, the Contacts Provider now broadcasts the {@link
899 android.provider.ContactsContract.Intents#CONTACTS_DATABASE_CREATED} action when the user
900 clears the contacts storage through the system settings menu, effectively recreating the
901 Contacts Provider database. It’s intended to signal apps that they need to drop all the contact
902 information they’ve stored and reload it with a new query.</p>
903
904 <p>For sample code using these APIs to check for changes to the contacts, look in the ApiDemos
905 sample available in the <a href="{@docRoot}tools/samples/index.html">SDK Samples</a> download.</p>
906
907
908 <h2 id="Localization">Localization</h2>
909
910 <h3 id="BiDi">Improved support for bi-directional text</h3>
911
912 <p>Previous versions of Android support right-to-left (RTL) languages and layout,
913 but sometimes don't properly handle mixed-direction text. So Android 4.3 adds the {@link
914 android.text.BidiFormatter} APIs that help you properly format text with opposite-direction
915 content without garbling any parts of it.</p>
916
917 <p>For example, when you want to create a sentence with a string variable, such as "Did you mean
918 15 Bay Street, Laurel, CA?", you normally pass a localized string resource and the variable to
919 {@link java.lang.String#format String.format()}:</p>
920 <pre>
921 Resources res = getResources();
922 String suggestion = String.format(res.getString(R.string.did_you_mean), address);
923 </pre>
924
925 <p>However, if the locale is Hebrew, then the formatted string comes out like this:</p>
926
927 <p dir="rtl">האם התכוונת ל 15 Bay Street, Laurel, CA?</p>
928
929 <p>That's wrong because the "15" should be left of "Bay Street." The solution is to use {@link
930 android.text.BidiFormatter} and its {@link android.text.BidiFormatter#unicodeWrap(String)
931 unicodeWrap()} method. For example, the code above becomes:</p>
932 <pre>
933 Resources res = getResources();
934 BidiFormatter bidiFormatter = BidiFormatter.getInstance();
935 String suggestion = String.format(res.getString(R.string.did_you_mean),
936         bidiFormatter.unicodeWrap(address));
937 </pre>
938
939 <p>
940 By default, {@link android.text.BidiFormatter#unicodeWrap(String) unicodeWrap()} uses the
941 first-strong directionality estimation heuristic, which can get things wrong if the first
942 signal for text direction does not represent the appropriate direction for the content as a whole.
943 If necessary, you can specify a different heuristic by passing one of the {@link
944 android.text.TextDirectionHeuristic} constants from {@link android.text.TextDirectionHeuristics}
945 to {@link android.text.BidiFormatter#unicodeWrap(String,TextDirectionHeuristic) unicodeWrap()}.</p>
946
947 <p class="note"><strong>Note:</strong> These new APIs are also available for previous versions
948 of Android through the Android <a href="{@docRoot}tools/extras/support-library.html">Support
949 Library</a>, with the {@link android.support.v4.text.BidiFormatter} class and related APIs.</p>
950
951
952
953 <h2 id="A11yService">Accessibility Services</h2>
954
955 <h3 id="A11yKeyEvents">Handle key events</h3>
956
957 <p>An {@link android.accessibilityservice.AccessibilityService} can now receive a callback for
958 key input events with the {@link android.accessibilityservice.AccessibilityService#onKeyEvent
959 onKeyEvent()} callback method. This allows your accessibility service to handle input for
960 key-based input devices such as a keyboard and translate those events to special actions that
961 previously may have been possible only with touch input or the device's directional pad.</p>
962
963
964 <h3 id="A11yText">Select text and copy/paste</h3>
965
966 <p>The {@link android.view.accessibility.AccessibilityNodeInfo} now provides APIs that allow
967 an {@link android.accessibilityservice.AccessibilityService} to select, cut, copy, and paste
968 text in a node.</p>
969
970 <p>To specify the selection of text to cut or copy, your accessibility service can use the new
971 action, {@link android.view.accessibility.AccessibilityNodeInfo#ACTION_SET_SELECTION}, passing
972 with it the selection start and end position with {@link
973 android.view.accessibility.AccessibilityNodeInfo#ACTION_ARGUMENT_SELECTION_START_INT} and {@link
974 android.view.accessibility.AccessibilityNodeInfo#ACTION_ARGUMENT_SELECTION_END_INT}.
975 Alternatively you can select text by manipulating the cursor position using the existing
976 action, {@link android.view.accessibility.AccessibilityNodeInfo#ACTION_NEXT_AT_MOVEMENT_GRANULARITY}
977 (previously only for moving the cursor position), and adding the argument {@link
978 android.view.accessibility.AccessibilityNodeInfo#ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN}.</p>
979
980 <p>You can then cut or copy with {@link android.view.accessibility.AccessibilityNodeInfo#ACTION_CUT},
981 {@link android.view.accessibility.AccessibilityNodeInfo#ACTION_COPY}, then later paste with
982 {@link android.view.accessibility.AccessibilityNodeInfo#ACTION_PASTE}.</p>
983
984
985 <p class="note"><strong>Note:</strong> These new APIs are also available for previous versions
986 of Android through the Android <a href="{@docRoot}tools/extras/support-library.html">Support
987 Library</a>, with the {@link android.support.v4.view.accessibility.AccessibilityNodeInfoCompat}
988 class.</p>
989
990
991
992 <h3 id="A11yFeatures">Declare accessibility features</h3>
993
994 <p>Beginning with Android 4.3, an accessibility service must declare accessibility capabilities
995 in its metadata file in order to use certain accessibility features. If the capability is not
996 requested in the metadata file, then the feature will be a no-op. To declare your service's
997 accessibility capabilities, you must use XML attributes that correspond to the various
998 "capability" constants in the {@link android.accessibilityservice.AccessibilityServiceInfo}
999 class.</p>
1000
1001 <p>For example, if a service does not request the {@link android.R.styleable#AccessibilityService_canRequestFilterKeyEvents flagRequestFilterKeyEvents} capability,
1002 then it will not receive key events.</p>
1003
1004
1005 <h2 id="Testing">Testing and Debugging</h2>
1006
1007 <h3 id="UiAutomation">Automated UI testing</h3>
1008
1009 <p>The new {@link android.app.UiAutomation} class provides APIs that allow you to simulate user
1010 actions for test automation. By using the platform's {@link
1011 android.accessibilityservice.AccessibilityService} APIs, the {@link android.app.UiAutomation}
1012 APIs allow you to inspect the screen content and inject arbitrary keyboard and touch events.</p>
1013
1014 <p>To get an instance of {@link android.app.UiAutomation}, call {@link
1015 android.app.Instrumentation#getUiAutomation Instrumentation.getUiAutomation()}. In order
1016 for this to work, you must supply the {@code -w} option with the {@code instrument} command
1017 when running your {@link android.test.InstrumentationTestCase} from <a
1018 href="{@docRoot}tools/help/adb.html#am">{@code adb shell}</a>.</p>
1019
1020 <p>With the {@link android.app.UiAutomation} instance, you can execute arbitrary events to test
1021 your app by calling {@link android.app.UiAutomation#executeAndWaitForEvent
1022 executeAndWaitForEvent()}, passing it a {@link java.lang.Runnable} to perform, a timeout
1023 period for the operation, and an implementation of the {@link
1024 android.app.UiAutomation.AccessibilityEventFilter} interface. It's within your {@link
1025 android.app.UiAutomation.AccessibilityEventFilter} implementation that you'll receive a call
1026 that allows you to filter the events that you're interested in and determine the success or
1027 failure of a given test case.</p>
1028
1029 <p>To observe all the events during a test, create an implementation of {@link
1030 android.app.UiAutomation.OnAccessibilityEventListener} and pass it to {@link
1031 android.app.UiAutomation#setOnAccessibilityEventListener setOnAccessibilityEventListener()}.
1032 Your listener interface then receives a call to {@link
1033 android.app.UiAutomation.OnAccessibilityEventListener#onAccessibilityEvent onAccessibilityEvent()}
1034 each time an event occurs, receiving an {@link android.view.accessibility.AccessibilityEvent} object
1035 that describes the event.</p>
1036
1037 <p>There is a variety of other operations that the {@link android.app.UiAutomation} APIs expose
1038 at a very low level to encourage the development of UI test tools such as <a href="{@docRoot}tools/help/uiautomator/index.html">uiautomator</a>. For instance,
1039 {@link android.app.UiAutomation} can also:</p>
1040 <ul>
1041   <li>Inject input events
1042   <li>Change the orientation of the screen
1043   <li>Take screenshots
1044 </ul>
1045
1046 <p>And most importantly for UI test tools, the {@link android.app.UiAutomation} APIs work
1047 across application boundaries, unlike those in {@link android.app.Instrumentation}.</p>
1048
1049
1050 <h3 id="Systrace">Systrace events for apps</h3>
1051
1052 <p>Android 4.3 adds the {@link android.os.Trace} class with two static methods,
1053 {@link android.os.Trace#beginSection beginSection()} and {@link android.os.Trace#endSection()},
1054 which allow you to define blocks of code to include with the systrace report. By creating
1055 sections of traceable code in your app, the systrace logs provide you a much more detailed
1056 analysis of where slowdown occurs within your app.</p>
1057
1058 <p>For information about using the Systrace tool, read <a href="{@docRoot}tools/debugging/systrace.html">Analyzing Display and Performance with Systrace</a>.</p>
1059
1060
1061 <h2 id="Security">Security</h2>
1062
1063 <h3 id="KeyStore">Android key store for app-private keys</h3>
1064
1065 <p>Android now offers a custom Java Security Provider in the {@link java.security.KeyStore}
1066 facility, called Android Key Store, which allows you to generate and save private keys that
1067 may be seen and used by only your app. To load the Android Key Store, pass
1068 {@code "AndroidKeyStore"} to {@link java.security.KeyStore#getInstance(String)
1069 KeyStore.getInstance()}.</p>
1070
1071 <p>To manage your app's private credentials in the Android Key Store, generate a new key with
1072 {@link java.security.KeyPairGenerator} with {@link android.security.KeyPairGeneratorSpec}. First
1073 get an instance of {@link java.security.KeyPairGenerator} by calling {@link
1074 java.security.KeyPairGenerator#getInstance getInstance()}. Then call
1075 {@link java.security.KeyPairGenerator#initialize initialize()}, passing it an instance of
1076 {@link android.security.KeyPairGeneratorSpec}, which you can get using
1077 {@link android.security.KeyPairGeneratorSpec.Builder KeyPairGeneratorSpec.Builder}.
1078 Finally, get your {@link java.security.KeyPair} by calling {@link
1079 java.security.KeyPairGenerator#generateKeyPair generateKeyPair()}.</p>
1080
1081
1082 <h3 id="HardwareKeyChain">Hardware credential storage</h3>
1083
1084 <p>Android also now supports hardware-backed storage for your {@link android.security.KeyChain}
1085 credentials, providing more security by making the keys unavailable for extraction. That is, once
1086 keys are in a hardware-backed key store (Secure Element, TPM, or TrustZone), they can be used for
1087 cryptographic operations but the private key material cannot be exported. Even the OS kernel
1088 cannot access this key material. While not all Android-powered devices support storage on
1089 hardware, you can check at runtime if hardware-backed storage is available by calling
1090 {@link android.security.KeyChain#isBoundKeyAlgorithm KeyChain.IsBoundKeyAlgorithm()}.</p>
1091
1092
1093
1094 <h2 id="Manifest">Manifest Declarations</h2>
1095
1096 <h3 id="ManifestFeatures">Declarable required features</h3>
1097
1098 <p>The following values are now supported in the <a
1099 href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code &lt;uses-feature>}</a>
1100 element so you can ensure that your app is installed only on devices that provide the features
1101 your app needs.</p>
1102
1103 <dl>
1104 <dt>{@link android.content.pm.PackageManager#FEATURE_APP_WIDGETS}</dt>
1105 <dd>Declares that your app provides an app widget and should be installed only on devices that
1106 include a Home screen or similar location where users can embed app widgets.
1107 Example:
1108 <pre>
1109 &lt;uses-feature android:name="android.software.app_widgets" android:required="true" />
1110 </pre>
1111 </dd>
1112
1113 <dt>{@link android.content.pm.PackageManager#FEATURE_HOME_SCREEN}</dt>
1114 <dd>Declares that your app behaves as a Home screen replacement and should be installed only on
1115 devices that support third-party Home screen apps.
1116 Example:
1117 <pre>
1118 &lt;uses-feature android:name="android.software.home_screen" android:required="true" />
1119 </pre>
1120 </dd>
1121
1122 <dt>{@link android.content.pm.PackageManager#FEATURE_INPUT_METHODS}</dt>
1123 <dd>Declares that your app provides a custom input method (a keyboard built with {@link
1124 android.inputmethodservice.InputMethodService}) and should be installed only on devices that
1125 support third-party input methods.
1126 Example:
1127 <pre>
1128 &lt;uses-feature android:name="android.software.input_methods" android:required="true" />
1129 </pre>
1130 </dd>
1131
1132 <dt>{@link android.content.pm.PackageManager#FEATURE_BLUETOOTH_LE}</dt>
1133 <dd>Declares that your app uses Bluetooth Low Energy APIs and should be installed only on devices
1134 that are capable of communicating with other devices via Bluetooth Low Energy.
1135 Example:
1136 <pre>
1137 &lt;uses-feature android:name="android.software.bluetooth_le" android:required="true" />
1138 </pre>
1139 </dd>
1140 </dl>
1141
1142
1143 <h3 id="ManifestPermissions">User permissions</h3>
1144 <p>The following values are now supported in the <a
1145 href="{@docRoot}guide/topics/manifest/uses-permission-element.html">{@code &lt;uses-permission>}</a>
1146 to declare the
1147 permissions your app requires in order to access certain APIs.</p>
1148
1149 <dl>
1150 <dt>{@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE}
1151 </dt>
1152 <dd>Required to use the new {@link android.service.notification.NotificationListenerService} APIs.
1153 </dd>
1154
1155 <dt>{@link android.Manifest.permission#SEND_RESPOND_VIA_MESSAGE}</dt>
1156 <dd>Required to receive the {@link android.telephony.TelephonyManager#ACTION_RESPOND_VIA_MESSAGE}
1157 intent.</dd>
1158 </dl>
1159
1160
1161
1162
1163 <p class="note">For a detailed view of all API changes in Android 4.3, see the
1164 <a href="{@docRoot}sdk/api_diff/18/changes.html">API Differences Report</a>.</p>
1165
1166
1167