Академический Документы
Профессиональный Документы
Культура Документы
UI Refinements The platform adds a variety of refinements to make the user interface more intuitive and more efficient to use. Connectivity for USB accessories It also adds broad platform support for a variety of USB-connected peripherals and accessories. Users can attach many types of input devices (keyboards, mice, game controllers) and digital cameras. Applications can build on the platforms USB support to extend connectivity to almost any type of USB device. Expanded Recent Apps list The Recent Apps list is now expandable for improved multitasking and instant visual access to a much larger number of apps. Users can now scroll the list of recent apps vertically to see thumbnail images all of the tasks in progress and recently used apps, then touch a thumbnail to jump back into that task. Resizeable Home screen widgets Users can now resize their Home screen widgets using drag bars provided by the system. Users can expand widgets both horizontally and/or vertically to include more content, where supported by each widget. Support for external keyboards and pointing devices Users can now attach almost any type of external keyboard or mouse to their Android-powered devices, to create a familiar environment and work more efficiently Support for joysticks and gamepads To make the platform even better for gaming, the platform adds support for most PC joysticks and gamepads that are connected over USB or Bluetooth HID. Robust Wi-Fi networking The platform adds robust Wi-Fi features, to make sure that users and their apps can take full advantage of higher-speed Wi-Fi access at home, at work, and while away. Updated set of standard apps The platform includes an updated set of standard applications that are optimized for use on larger screen devices. Enterprise support Users can now configure an HTTP proxy for each connected Wi-Fi access point. This lets administrators work with users to set a proxy hostname, port, and any bypass subdomains. This proxy configuration is automatically used by the Browser when the Wi-Fi access point is connected, and may optionally be used by other apps. The proxy and IP configuration is now backed up and restored across system updates and resets.
Android3.1Platform
Inthisdocument
1. 2. 3. 4. 5. 6. Revisions APIOverview APILevel BuiltinApplications Locales EmulatorSkins
Reference
1. APIDifferencesReport
SeeAlso
1. OptimizingAppsforAndroid3.0
API Level: 12 For developers, the Android 3.1 platform is available as a downloadable component for the Android SDK. The downloadable platform includes an Android library and system image, as well as a set of emulator skins and more. The downloadable platform includes no external libraries. To get started developing or testing against Android 3.1, use the Android SDK Manager to download the platform into your SDK. For more information, see Adding SDK Components. If you are new to Android, download the SDK Starter Package first. For a high-level introduction to Android 3.1, see the Platform Highlights. Reminder: If you've already published an Android application, please test and optimize your application on Android 3.0 and Android 3.1 as soon as possible. You should do so to be sure your application provides the best experience possible on the latest Android-powered devices. For information about what you can do, read Optimizing Apps for Android 3.0.
Revisions
To determine what revision of the Android 3.1 platform you have installed, refer to the "Installed Packages" listing in the Android SDK and AVD Manager. Android 3.1, Revision 1 (May 2011)
Dependencies:
APIOverview
The sections below provide a technical overview of what's new for developers in Android 3.1, including new features and changes in the framework API since the previous version.
USB APIs
Android 3.1 introduces powerful new APIs for integrating connected peripherals with applications running on the platform. The APIs are based on a USB (Universal Serial Bus) stack and services that are built into the platform, including support for both USB host and device interactions. Using the APIs, developers can create applications that are able to discover, communicate with, and manage a variety of device types connected over USB. The stack and APIs distinguish two basic types of USB hardware, based on whether the Androidpowered device is acting as host or the external hardware is acting as host:
For both types USB devices and USB accessories the platform's USB APIs support discovery by intent broadcast when attached or detached, as well as standard interfaces, endpoints, and transfer modes (control, bulk, and interrupt). The USB APIs are available in the package android.hardware.usb. The central class is UsbManager, which provides helper methods for identifying and communicating with both USB devices and USB accessories. Applications can acquire an instance of UsbManager and then query for the list of attached devices or accessories and then communicate with or manage them. UsbManager also declares intent actions that the system broadcasts, to announce when a USB device or accessory is attached or detached. Other classes include:
UsbDevice,aclassrepresentingexternalhardwareconnectedasaUSB device(withtheAndroidpowereddeviceactingashost). UsbAccessory,representingexternalhardwareconnectedastheUSB host(withtheAndroidpowereddeviceactingasaUSBdevice). UsbInterfaceandUsbEndpoint,whichprovideaccesstostandard USBinterfacesandendpointsforadevice. UsbDeviceConnectionandUsbRequest,forsendingandreceiving dataandcontrolmessagestoorfromaUSBdevice,sychronouslyand asynchronously. UsbConstants,whichprovidesconstantsfordeclaringendpointtypes, deviceclasses,andsoon.
Note that although the USB stack is built into the platform, actual support for USB host and open accessory modes on specific devices is determined by their manufacturers. In particular, host mode relies on appropriate USB controller hardware in the Android-powered device. Additionally, developers can request filtering on Android Market, such that their applications are not availabe to users whose devices do not provide the appropriate USB support. To request filtering, add one or both of the elements below to the application manifest, as appropriate:
IftheapplicationshouldonlybevisibletodevicesthatsupportUSBhost mode(connectionofUSBdevices),declarethiselement:
<uses-feature android:name="android.hardware.usb.host" android:required="true">
IftheapplicationshouldonlybevisibletodevicesthatsupportUSB accessories(connectionofUSBhosts),declarethiselement:
<uses-feature android:name="android.hardware.usb.accessory" android:required="true"> For complete information about how to develop applications that interact with USB accessories, please see the developer documentation. To look at sample applications that use the USB host API, see ADB Test and Missile Launcher
MTP/PTP API
Android 3.1 exposes a new MTP API that lets applications interact directly with connected cameras and other PTP devices. The new API makes it easy for an application to receive notifications when devices are attached and removed, manage files and storage on those devices, and transfer files and metadata to and from them. The MTP API implements the PTP (Picture Transfer Protocol) subset of the MTP (Media Transfer Protocol) specification. The MTP API is available in the android.mtp package and provides these classes:
importFile()letsanapplicationcopydataforanobjecttoafile inexternalstorage.Thiscallmayblockforanarbitraryamountof timedependingonthesizeofthedataandspeedofthedevices,so shouldbemadefromaspearatethread. o open()letsanapplicationopenaconnectedMTP/PTPdevice. o getThumbnail()returnsthethumbnailoftheobjectasabyte array. MtpStorageInfoholdsinformationaboutaboutastorageunitonan MTPdevice,correspondingtotheStorageInfoDatasetdescribedin section5.2.2oftheMTPspecification.Methodsintheclassletan applicationgetastorageunitsdescriptionstring,freespace,maximum storagecapacity,storageID,andvolumeidentifier. MtpDeviceInfoholdsinformationaboutanMTPdevicecorresponding totheDeviceInfoDatasetdescribedinsection5.1.1oftheMTP specification.Methodsintheclassletapplicationsgetadevices manufacturer,model,serialnumber,andversion. MtpObjectInfoholdsinformationaboutanobjectstoredonanMTP device,correspondingtotheObjectInfoDatasetdescribedinsection5.3.1 oftheMTPspecification.Methodsintheclassletapplicationsgetan objectssize,dataformat,associationtype,creationdate,andthumbnail information. MtpConstantsprovidesconstantsfordeclaringMTPfileformatcodes, associationtype,andprotectionstatus.
o
AXIS_SIZE, AXIS_TOUCH_MAJOR, AXIS_TOUCH_MINOR, AXIS_TOOL_MAJOR, AXIS_TOOL_MINOR, and AXIS_ORIENTATION. Additionally, MotionEvent defines a number of generic axis codes that are used when the framework does not know how to map a particular axis. Specific devices can use the generic axis codes to pass custom motion data to applications. For a full list of axes and their intended interpretations, see the MotionEvent class documentation. The platform provides motion events to applications in batches, so a single event may contain a current position and multiple so-called historical movements. Applications should use getHistorySize() to get the number of historical samples, then retrieve and process all historical samples in order using getHistoricalAxisValue(). After that, applications should process the current sample using getAxisValue(). Some axes can be retrieved using special accessor methods. For example, instead of calling getAxisValue(), applications can call getX(). Axes that have built-in accessors include AXIS_X, AXIS_Y, AXIS_PRESSURE, AXIS_SIZE, AXIS_TOUCH_MAJOR, AXIS_TOUCH_MINOR, AXIS_TOOL_MAJOR, AXIS_TOOL_MINOR, and AXIS_ORIENTATION. Each input device has a unique, system-assigned ID and may also provide multiple sources. When a device provides multiple sources, more than one source can provide axis data using the same axis. For example, a touch event coming from the touch source uses the X axis for screen position data, while a joystick event coming from the joystick source will use the X axis for the stick position instead. For this reason, it's important for applications to interpret axis values according to the source from which they originate. When handling a motion event, applications should use methods on the InputDevice class to determine the axes supported by a device or source. Specifically, applications can use getMotionRanges() to query for all axes of a device or all axes of a given source of the device. In both cases, the range information for axes returned in the InputDevice.MotionRange object specifies the source for each axis value. Finally, since the motion events from joysticks, gamepads, mice, and trackballs are not touch events, the platform adds a new callback method for passing them to a View as "generic" motion events. Specifically, it reports the non-touch motion events to Views through a call to onGenericMotionEvent(), rather than to onTouchEvent(). The platform dispatches generic motion events differently, depending on the event source class. SOURCE_CLASS_POINTER events go to the View under the pointer, similar to how touch events work. All others go to the currently focused View. For example, this means a View must take focus in order to receive joystick events. If needed, applications can handle these events at the level of Activity or Dialog by implementing onGenericMotionEvent() there instead. To look at a sample application that uses joystick motion events, see GameControllerInput and GameView.
RTP API
Android 3.1 exposes an API to its built-in RTP (Real-time Transport Protocol) stack, which applications can use to manage on-demand or interactive data streaming. In particular, apps that provide VOIP, push-to-talk, conferencing, and audio streaming can use the API to initiate sessions and transmit or receive data streams over any available network. The RTP API is available in the android.net.rtp package. Classes include:
optionallyinteractswiththedevicespeakerandthemicrophoneatthe sametime.
The simplest usage involves a single remote endpoint and local endpoint. For more complex usages, please refer to the limitations described for AudioGroup. To use the RTP API, applications must request permission from the user by declaring <usespermission android:name="android.permission.INTERNET"> in their manifest files. To acquire the device microphone, the <uses-permission android:name="android.permission.RECORD_AUDIO"> permission is also required.
Animation framework
NewViewPropertyAnimatorclass o AnewViewPropertyAnimatorclassprovidesaconvenient wayfordeveloperstoanimateselectpropertiesonViewobjects. Theclassautomatiesandoptimizestheanimationofthe propertiesandmakesiteasiertomanagemultiplesimulataneous animationsonaViewobject.
Using the ViewPropertyAnimator is straightforward. To animate properties for a View, call animate() to construct a ViewPropertyAnimator object for that View. Use the methods on the ViewPropertyAnimator to specify what property to animate and how to animate it. For example, to fade the View to transparent, call alpha(0);. The ViewPropertyAnimator object handles the details of configuring the underlying Animator class and starting it, then rendering the animation.
Animationbackgroundcolor o NewgetBackgroundColor()and setBackgroundColor(int)methodsletyouget/setthe backgroundcolorbehindanimations,forwindowanimationsonly. Currentlythebackgroundmustbeblack,withanydesiredalpha level. GettinganimatedfractionfromViewAnimator o AnewgetAnimatedFraction()methodletsyougetthe currentanimationfractiontheelapsed/interpolatedfraction usedinthemostrecentframeupdatefromaValueAnimator.
UI framework
Forcedrenderingofalayer
AnewbuildLayer()methodletsanapplicationforceaView's layertobecreatedandtheViewrenderedintoitimmediately.For example,anapplicationcouldusethismethodtorenderaView intoitslayerbeforestartingananimation.IftheViewiscomplex, renderingitintothelayerbeforestartingtheanimationwillavoid skippingframes. Cameradistance o Applicationscanuseanewmethod setCameraDistance(float)tosetthedistancefromthe cameratoaView.Thisgivesapplicationsimprovedcontrolover 3DtransformationsoftheView,suchasrotations. GettingacalendarviewfromaDatePicker o AnewgetCalendarView()methodletsyougeta CalendarViewfromaDatePickerinstance. Gettingcallbackswhenviewsaredetached o AnewView.OnAttachStateChangeListenerletsyou receivecallbackswhenaViewisattachedordetachedfromits window.UseaddOnAttachStateChangeListener()toadda listenerandaddOnAttachStateChangeListener()to removeit. Fragmentbreadcrumblistener,newonInflate()signature o Anewmethod,setOnBreadCrumbClickListener(), providesahooktoletapplicationsinterceptfragmentbreadcrumb clicksandtakeanyactionneededbeforegoingtothebackstack entryorfragmentthatwasclicked. o IntheFragmentclass,onInflate(attrs, savedInstanceState)isdeprecated.Pleaseuse onInflate(activity, attrs, savedInstanceState) instead. Displaysearchresultinnewtab o AnEXTRA_NEW_SEARCHdatakeyforACTION_WEB_SEARCH intentsletsyouopenasearchinanewbrowsertab,ratherthanin anexistingone. Drawabletextcursor o Youcannowspecifyadrawabletouseasthetextcursorusingthe newresourceattributetextCursorDrawable. Settingdisplayedchildinremoteviews o Anewconveniencemethod,setDisplayedChild(viewId, childIndex),isavailableinRemoteViewssubclasses,tolet yousetthechilddisplayedinViewAnimatorand AdapterViewAnimatorsubclassessuchas AdapterViewFlipper,StackView,ViewFlipper,and ViewSwitcher. Generickeysforgamepadsandotherinputdevices o KeyEventaddsarangeofgenerickeycodestoaccommodate gamepadbuttons.TheclassalsoaddsisGamepadButton(int) andseveralotherhelpermethodsforworkingwithkeycodes.
o
Graphics
Helpersformanagingbitmaps
setHasAlpha(boolean)letsanappindicatethatallofthe pixelsinaBitmapareknowntobeopaque(false)orthatsomeof thepixelsmaycontainnonopaquealphavalues(true).Note,for someconfigs(suchasRGB_565)thiscallisignored,sinceitdoes notsupportperpixelalphavalues.Thisismeantasadrawinghint, asinsomecasesabitmapthatisknowntobeopaquecantakea fasterdrawingcasethanonethatmayhavenonopaqueperpixel alphavalues. o getByteCount()getsaBitmap'ssizeinbytes. o getGenerationId()letsanapplicationfindoutwhethera Bitmaphasbeenmodified,suchasforcaching. o sameAs(android.graphics.Bitmap)determineswhethera givenBitmapdiffersfromthecurrentBitmap,indimension, configuration,orpixeldata. Settingcameralocationandrotation o Cameraaddstwonewmethodsrotate()andsetLocation() forcontrolofthecamera'slocation,for3Dtransformations.
o
Network
HighperformanceWiFilock o AnewhighperformanceWiFilockletsapplicationsmaintain highperformanceWiFiconnectionsevenwhenthedevicescreen isoff.Applicationsthatstreammusic,video,orvoiceforlong periodscanacquirethehighperformanceWiFilocktoensure streamingperformanceevenwhenthescreenisoff.Becauseit usesmorepower,applicationsshouldacquirethehigh performanceWiFiwhenthereisaneedforalongrunningactive connection.
To create a high-performance lock, pass WIFI_MODE_FULL_HIGH_PERF as the lock mode in a call to createWifiLock().
Download Manager
Handlingofcompleteddownloads o Applicationscannowinitiatedownloadsthatnotifyusersonlyon completion.Toinitiatethistypeofdownload,applicationspass VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETIONinthe setNotificationVisibility()methodofthearequest object. o Anewmethod,addCompletedDownload(),letsanapplication addafiletothedownloadsdatabase,sothatitcanbemanagedby theDownloadsapplication. Showdownloadssortedbysize
IME framework
Gettinganinputmethod'sextravaluekey o TheInputMethodSubtypeaddsthemethod containsExtraValueKey()tocheckwhetheranExtraValue stringisstoredforthesubtypeandthemethod getExtraValueOf()toextractaspecifickeyvaluefromthe ExtraValuehashmap.
Media
Newstreamingaudioformats o ThemediaframeworkaddsbuiltinsupportforrawADTSAAC content,forimprovedstreamingaudio,aswellassupportforFLAC audio,forhighestquality(lossless)compressedaudiocontent.See theSupportedMediaFormatsdocumentformoreinformation.
ACTION_PACKAGE_FIRST_LAUNCHSenttotheinstallerpackageof anapplicationwhenthatapplicationisfirstlaunched(thatis,thefirst timeitismovedoutofastoppedstate).Thedatacontainsthenameofthe package. ACTION_MY_PACKAGE_REPLACEDNotifiesanapplicationthatitwas updated,withanewversionwasinstalledoveranexistingversion.Thisis onlysenttotheapplicationthatwasreplaced.Itdoesnotcontainany additionaldata.Toreceiveit,declareanintentfilterforthisaction.You canusetheintenttotriggercodethathelpsgetyourapplicationbackin properrunningshapeafteranupgrade.
This intent is sent directly to the application, but only if the application was upgraded while it was in started state (not in a stopped state).
Core utilities
LRUcache o AnewLruCacheclassletsyourapplicationsbenefitfromefficient caching.Applicationscanusetheclasstoreducethetimespent computingordownloadingdatafromthenetwork,while maintainingasensiblememoryfootprintforthecached data.LruCacheisacachethatholdsstrongreferencestoalimited numberofvalues.Eachtimeavalueisaccessed,itismovedtothe headofaqueue.Whenavalueisaddedtoafullcache,thevalueat theendofthatqueueisevictedandmaybecomeeligiblefor garbagecollection. Filedescriptorasint o Youcannowgetthenativefiledescriptorintfora ParcelFileDescriptorusingeitherofthenewmethods getFd()ordetachFd().
WebKit
Fileschemecookies o TheCookieManagernowsupportscookiesthatusethefile: URIscheme.YoucanusesetAcceptFileSchemeCookies() toenable/disablesupportforfileschemecookies,before constructinganinstanceofWebVieworCookieManager.Ina CookieManagerinstance,youcancheckwhetherfilescheme cookiesisenabledbycallingallowFileSchemeCookies(). Notificationofloginrequest o TosupportthebrowserautologinfeaturesintroducedinAndroid 3.0,thenewmethodonReceivedLoginRequest()notifiesthe hostapplicationthatanautologinrequestfortheuserwas processed. Removedclassesandinterfaces o SeveralclassesandinterfaceswereremovedfromthepublicAPI, afterpreviouslybeingindeprecatedstate.SeetheAPIDifferences Reportformoreinformation.
Browser
The Browser application adds the following features to support web applications:
APILevel
The Android 3.1 platform delivers an updated version of the framework API. The Android 3.1 API is assigned an integer identifier 12 that is stored in the system itself. This identifier, called the "API Level", allows the system to correctly determine whether an application is compatible with the system, prior to installing the application. To use APIs introduced in Android 3.1 in your application, you need compile the application against the Android library that is provided in the Android 3.1 SDK platform. Depending on your needs, you might also need to add an android:minSdkVersion="12" attribute to the <uses-sdk> element in the application's manifest. For more information about how to use API Level, see the API Levels document.
BuiltinApplications
The system image included in the downloadable platform provides these built-in applications:
APIDemos Browser Calculator Camera Clock Contacts CustomLocale DevTools Downloads Email
Locales
The system image included in the downloadable SDK platform provides a variety of built-in locales. In some cases, region-specific strings are available for the locales. In other cases, a default version of the language is used. The languages that are available in the Android 3.0 system image are listed below (with language_country/region locale descriptor).
Arabic,Egypt(ar_EG) Arabic,Israel(ar_IL) Bulgarian,Bulgaria (bg_BG) Catalan,Spain(ca_ES) Czech,CzechRepublic (cs_CZ) Danish,Denmark(da_DK) German,Austria(de_AT) German,Switzerland (de_CH) German,Germany(de_DE) German,Liechtenstein (de_LI) Greek,Greece(el_GR) English,Australia(en_AU)
English,Canada(en_CA) English,Britain(en_GB) English,Ireland(en_IE) English,India(en_IN) English,NewZealand (en_NZ) English,Singapore(en_SG) English,US(en_US) English,Zimbabwe (en_ZA) Spanish(es_ES) Spanish,US(es_US) Finnish,Finland(fi_FI) French,Belgium(fr_BE) French,Canada(fr_CA) French,Switzerland (fr_CH) French,France(fr_FR) Hebrew,Israel(he_IL) Hindi,India(hi_IN)
Norwegianbokml,Norway (nb_NO) Dutch,Belgium(nl_BE) Dutch,Netherlands(nl_NL) Polish(pl_PL) Portuguese,Brazil(pt_BR) Portuguese,Portugal(pt_PT) Romanian,Romania(ro_RO) Russian(ru_RU) Slovak,Slovakia(sk_SK) Slovenian,Slovenia(sl_SI) Serbian(sr_RS) Swedish,Sweden(sv_SE) Thai,Thailand(th_TH) Tagalog,Philippines(tl_PH) Turkish,Turkey(tr_TR) Ukrainian,Ukraine(uk_UA) Vietnamese,Vietnam(vi_VN) Chinese,PRC(zh_CN) Chinese,Taiwan(zh_TW)
Note: The Android platform may support more locales than are included in the SDK system image. All of the supported locales are available in the Android Open Source Project.
EmulatorSkins
The downloadable platform includes the following emulator skin:
WXGA(1280x800,mediumdensity,xlargescreen)
For more information about how to develop an application that displays and functions properly on all Android-powered devices