Tải bản đầy đủ (.pdf) (181 trang)

android 4 new features for application development aydin 2015 03 25 Lập trình android

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.08 MB, 181 trang )

CuuDuongThanCong.com


Android4:NewfeaturesforApplication
Development
DevelopAndroidapplicationsusingthenewfeaturesof
AndroidIceCreamSandwich
MuratAydin
BIRMINGHAM-MUMBAI

CuuDuongThanCong.com


Android4:NewfeaturesforApplicationDevelopment
Copyright©2012PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedina
retrievalsystem,ortransmittedinanyformorbyanymeans,withouttheprior
writtenpermissionofthepublisher,exceptinthecaseofbriefquotations
embeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensurethe
accuracyoftheinformationpresented.However,theinformationcontainedin
thisbookissoldwithoutwarranty,eitherexpressorimplied.Neitherthe
author,norPacktPublishing,anditsdealersanddistributorswillbeheldliable
foranydamagescausedorallegedtobecauseddirectlyorindirectlybythis
book.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallof
thecompaniesandproductsmentionedinthisbookbytheappropriateuseof
capitals.However,PacktPublishingcannotguaranteetheaccuracyofthis
information.
Firstpublished:December2012
ProductionReference:1171212


PublishedbyPacktPublishingLtd.LiveryPlace
35LiveryStreet
BirminghamB32PB,UK..
www.packtpub.comCoverImagebyAbhishekPandey
()

CuuDuongThanCong.com


Credits
Author
MuratAydin
ProjectCoordinatorEshaThakker
Reviewers
RickBoyer
AhmetOguzMermerkayaNathanSchwermannMuratYener
ProofreaderMariaGould
Indexer
MonicaAjmeraMehta
AcquisitionEditorUshaIyer
Graphics
AditiGajjar
CommissioningEditorMeetaRajani
MariaD’souza
YogeshDalvi
ProductionCoordinatorPrachaliBhiwandkar
CoverWork
PrachaliBhiwandkar
TechnicalEditorNiteeShetty


CuuDuongThanCong.com


AbouttheAuthor
MuratAydinisaSeniorSoftwareEngineerinacompanythatdevelops
software
technologiesfordefensesystems,andanenthusiasticAndroiddeveloper.He
hasseveralAndroidapplicationsinGooglePlay.HeisaSunCertifiedJava
Developerandhaseightyearsofexperienceindevelopingweb-based
applicationsusingJavatechnologies,desktop,andengineeringapplications
using.NETtechnologies.
HeearnedhisBScdegreeinComputerEngineeringfromMETU(MiddleEast
TechnicalUniversity)andhisMScdegreeinSoftwareEngineeringfrom
METU.
HeisamemberofGDGAnkara(GoogleDeveloperGroupAnkara,
www.gdgankara.org).TheyorganizeseveralAndroideventsinGDGAnkara
suchasAndroidDeveloperDays(www.androiddeveloperdays.com).
HeismarriedandlivesinAnkarawithhiswifeÜlkü.
YoucangetintouchwithhimonLinkedinatmuratayd%C4%B1n/33/702/6a2,orthroughhisTwitterhandle@maydintr,oryoucan
alsoe-mailhimat
IwouldliketothankmypreciouswifeÜlküforabidingwithmeduringmy
longhoursofworkforthisbook.Aspecialthankstomyparentsandmy
siblingsforsupportingme.IwouldalsoliketothankAhmetOğuz
Mermerkaya,MuratYener,RickBoyer,andNathanSchwermannfor
reviewingmybook.Finally,IwanttothanktheteamatPacktPublishingfor
alltheirhelp.

CuuDuongThanCong.com



AbouttheReviewers
RickBoyerhasovertwentyyearsofprofessionalprogramming
experience,
includingdevelopingapplicationsonWindows,WindowsCE,Windows
Phone,andAndroid.Withapassionformobile,henowfocusesexclusivelyon
theAndroidplatformwithhisconsultingbusiness,NightSkyDevelopment.
HealsorunstheLinkedIngroup,PublishedAndroidDevelopers
(wheredevelopersdiscussissuesrelatedtopublishingapps
tothemarket.
Youcancontacthimatabout.me\RickBoyer.
AhmetOguzMermerkayaisanElectronicsEngineerbuthasalways
worked
asasoftwaredeveloper.Hehasdevelopedsoftwaresondifferentplatforms
usingC,C++,Java,UML,andWeb(PHP,MySQL).Healsohasexperiencein
extremeprogrammingtechniquesandmodel-drivendevelopment.Currently,
heisworkingonAndroidapplicationdevelopment.Heistheauthorof
MerhabaAndroid,aturkishbookaboutAndroidapplicationdevelopment.He
isalsoanactivememberoftheGDGcommunityinTurkey.
NathanSchwermannisagraduatefromtheUniversityofKansasandhas
been
developingapplicationsforAndroidprofessionallyforovertwoyears.Heisa
strongsupporterofbackwardcompatibilityandisveryfamiliarwithboth
Google’ssupportlibraryanditsfamousextensionActionbarSherlock.Healso
reviewedAndroid3.0Animations,PacktPublishing.
YoucancontactNathananytimeatifyouwouldliketotalk
aboutAndroid,joboffers,orarrangeameetupatGoogleIOorotherpopular
Androidevents.
MuratYenercompletedhisBSandMSdegreeatIstanbulTechnical
University.
HehastakenpartinseveralprojectsstillinuseattheITUInformatics

Institute.HehasworkedonIsbank’sCoreBankingexchangeprojectasa
CuuDuongThanCong.com


J2EEdeveloper.Hehasdesignedandcompletedseveralprojectsstillonthe
marketbyMuseSystems.HehasworkedinTAVAirportsInformation
TechnologiesasaEnterpriseJava&Flexdeveloper.HehasworkedforHSBC
asaprojectleaderresponsibleforbusinessprocessesandrichclientuser
interfaces.CurrentlyheisemployedatEterationA.S.workingonseveral
projectsincludingEclipseLibraTools,GWT,andMobileapplications(both
onAndroidandiOS).
HeisalsoleadingtheGoogleTechnologyUserGroupIstanbulsince2009and
isaregularspeakeratconferencessuchasJavaOne,EclipseCon,EclipseIst,
andGDGmeetings.
IwouldliketothankMuratAydin,whoofferedmethechancetoreviewhis
wonderfulbook.IwouldalsoliketothankNaciDaiforbeingmymentorand
providingthebestworkenvironment,DanielKurkafordevelopingmgwt,the
bestmobileplatformIeverworkedon,andNilayCoskunforallhersupport.

CuuDuongThanCong.com


www.PacktPub.com
Supportfiles,eBooks,discountoffersandmore
Youmightwanttovisitwww.PacktPub.comforsupportfilesanddownloads
relatedtoyourbook.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,with
PDFandePubfilesavailable?YoucanupgradetotheeBookversionat
www.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscount
ontheeBookcopy.Getintouchwithusatformore

details.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,
signupforarangeoffreenewslettersandreceiveexclusivediscountsand
offersonPacktbooksandeBooks.



DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonline
digitalbooklibrary.Here,youcanaccess,readandsearchacrossPackt’s
entirelibraryofbooks.
WhySubscribe?
•FullysearchableacrosseverybookpublishedbyPackt
•Copyandpaste,printandbookmarkcontent
•Ondemandandaccessibleviawebbrowser
FreeAccessforPacktaccountholders
IfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethisto
accessPacktLibtodayandviewnineentirelyfreebooks.Simplyuseyour
logincredentialsforimmediateaccess.

CuuDuongThanCong.com


TableofContents
Preface1Chapter1:ActionBarforAll7
Actionbar7
Addinganactionbar9
AddinganActionProvider14
AddingsubmenustotheActionProvider19
ShareActionProvider21
Addinganactionview24

Usingtheactionbarfornavigation30
Summary35
Chapter2:ANewLayout–GridLayout37
GridLayout37
WhytouseGridLayout39
AddingaGridLayout39
ConfiguringGridLayout43
Anewview–Space49
Summary51
Chapter3:SocialAPIs53
BasicsofcontactsinAndroid53
UsingSocialAPI54
Deviceuserprofile65
Summary65
Chapter4:CalendarAPIs67
UsingCalendarAPIs67
Creatinganevent68
UsingIntentsforcreatingevents73
Addinganattendee73
Addingareminder74
Summary76
Chapter5:Fragments77

CuuDuongThanCong.com


Fragmentbasics77
Fragmentlifecycle78
Creatingandmanagingfragments79
Programmaticallyaddingafragment85

Eventsharingwithactivity86
Usingmultiplefragmentsinanactivity87
Typesoffragments91
ListFragment91
DialogFragment91
PreferenceFragment96
WebViewFragment99
Summary104
Chapter6:SupportingDifferentScreenSizes105
Android4.0supportsdifferentscreensizes105
Usingmatch_parentandwrap_content107
Usingdipinsteadofpx111
OmitusingAbsoluteLayout113
Providingdifferentbitmapdrawablesfordifferentscreendensities114
Providingdifferentlayoutsfordifferentscreensizes115
Nine-patch117
Summary118
Chapter7:AndroidCompatibilityPackage119
WhatisAndroidCompabilityPackage119
HowtousetheAndroidCompatibilityPackage120
Summary126
Chapter8:NewConnectivityAPIs–AndroidBeamandWi-FiDirect127
AndroidBeam127
BeamingNdefMessages128
Wi-FiDirect133
SampleWi-FiDirectapplication134
Summary143
Chapter9:MultipleAPKSupport
Thischapterisavailablefordownloadat
CuuDuongThanCong.com



Support.pdf.
[ ]
ii

Chapter10:APIswithAndroidJellyBean
Thischapterisavailablefordownloadat
JellyBean.pdf.

Index145
[ ]
iii

CuuDuongThanCong.com


Preface
Thisbookisapracticalandhands-onguidefordevelopingAndroid
applicationsusingnewfeaturesofAndroidIceCreamSandwich(Android
4.0),withastep-by-stepapproachandclearlyexplainedsamplecodes.You
willlearnthenewAPIsinAndroid4.0withthesesamplecodes.

CuuDuongThanCong.com


CuuDuongThanCong.com


Whatthisbookcovers

Chapter1,ActionBarforAll,introducesustotheactionbarandshowsus
howtouseandconfiguretheactionbar.
Chapter2,ANewLayout–GridLayout,introducesustoGridLayoutand
showsushowtouseandconfigureGridLayout.GridLayoutisanewlayout
introducedwithAndroidIceCreamSandwich.Thislayoutisanoptimized
layoutandcouldbeusedinsteadofLinearLayoutandRelativeLayout.
Chapter3,SocialAPIs,coverstheSocialAPIsthatwereintroducedwith
AndroidIceCreamSandwich.ThisAPImakesiteasytointegratethesocial
networks.Furthermore,highresolutionphotoscannowbeusedasacontact’s
photoafterIceCreamSandwichwasreleased.ThischaptershowsSocialAPI
usagewithexamples.
Chapter4,CalendarAPIs,coverstheCalendarAPIswhichwereintroduced
withAndroidIceCreamSandwichformanagingcalendars.Event,attendee,
alert,andreminderdatabasescanbemanagedwiththeseAPIs.TheseAPIs
allowustoeasilyintegratecalendarswithourAndroidapplications.This
chaptershowshowtouseCalendarAPIswithexamples.
Chapter5,Fragments,introducesustothebasicsoffragmentsandhowtouse
them.
Chapter6,SupportingDifferentScreenSizes,introducesustothewaysof
designinguserinterfacesthatsupportdifferentscreensizes.
Chapter7,AndroidCompatibilityPackage,introducesustotheAndroid
CompatibilityPackageandshowsushowtouseit.TheAndroidCompatibility
PackageistoallowtheportingofthenewAPIstotheolderversionsofthe
Androidplatform.
Chapter8,NewConnectivityAPIs–AndroidBeamandWi-FiDirect,
introducesustoAndroidBeam,whichusestheNFChardwareofthedevice
andWi-FiDirectwhichallowsdevicestoconnecttoeachotherwithoutusing
wirelessaccesspoints.ThischapterwillteachustheusageofAndroidBeam
andWi-FiDirect.
Chapter9,MultipleAPKSupport,introducesustoMultipleAPKSupport

whichisanewoptioninGooglePlay(AndroidMarket)bywhichmultiple
versionsofAPKscouldbeuploadedforasingleapplication.
Thischapterisavailablefordownloadat

CuuDuongThanCong.com


default/files/downloads/Multiple_APK_Support.pdf.

Chapter10,APIswithAndroidJellyBean,coversAndroidJellyBeanandthe
newAPIswithinit.
Thischapterisavailablefordownloadat />default/files/downloads/Android_JellyBean.pdf.

CuuDuongThanCong.com


Whatyouneedforthisbook
Tofollowtheexamplesinthisbook,theAndroidDevelopmentToolsshould
besetupandready.Thenecessarysoftwarelistisasfollows:
•EclipsewithADTplugin
•AndroidSDKTools
•Androidplatformtools
•ThelatestAndroidplatform
TheOperatingSystemsthatcanbeusedareasfollows:
•WindowsXP(32-bit),Vista(32-or64-bit),orWindows7(32-or64-bit)
•MacOSX10.5.8orlater(x86only)
•Linux(testedonUbuntuLinux,LucidLynx)
°GNUCLibrary(glibc)2.7orlaterisrequired
°OnUbuntuLinux,version8.04orlaterisrequired
°64-bitdistributionsmustbecapableofrunning32-bitapplicationsThe

specificationsforuseoftheEclipseIDEisasfollows:
•Eclipse3.6.2(Helios)orgreater(Eclipse3.5(Galileo)isnolongersupported
withthelatestversionofADT)
•EclipseJDTplugin(includedinmostEclipseIDEpackages)
•JDK6(JREaloneisnotsufficient)
•AndroidDevelopmentToolsplugin(recommended)

CuuDuongThanCong.com


CuuDuongThanCong.com


Whothisbookisfor
ThisbookisfordeveloperswhoareexperiencedwiththeAndroidplatform,
butwhomaynotbefamiliarwiththenewfeaturesandAPIsofAndroid4.0.
Androiddeveloperswhowanttolearnaboutsupportingmultiplescreensizes
andmultipleAndroidversions;thisbookisalsoforyou.

CuuDuongThanCong.com


Conventions
Inthisbook,youwillfindanumberofstylesoftextthatdistinguishbetween
differentkindsofinformation.Herearesomeexamplesofthesestyles,andan
explanationoftheirmeaning.
Codewordsintextareshownasfollows:“Implement
onCreateOptionsMenuandonOptionsItemSelectedmethods.”

Ablockofcodeissetasfollows:

<?xmlversion=“1.0”encoding=“utf-8”?>
<menuxmlns:android=“>android:id=”@+id/settings”
android:title=“Settings”>
</item>
<itemandroid:id=”@+id/about”android:title=“About”></item>
</menu>

Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,the
relevantlinesoritemsaresetinbold:
@Override
publicvoidonPrepareSubMenu(SubMenusubMenu){
//Inordertoaddsubmenus,weshouldoverridethismethodwedynamicallycreated
submenus
subMenu.clear();
subMenu.add(“SubItem1”).setOnMenuItemClickListener(this);
subMenu.add(“SubItem2”).setOnMenuItemClickListener(this);
}

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeon
thescreen,inmenusordialogboxesforexample,appearinthetextlikethis:
“ClickontheInsertbuttonandthenclickontheListbutton”.
Warningsorimportantnotesappearinaboxlikethis.Tipsandtricksappearlikethis.

CuuDuongThanCong.com


Readerfeedback
Feedbackfromourreadersisalwayswelcome.Letusknowwhatyouthink
aboutthisbook—whatyoulikedormayhavedisliked.Readerfeedbackis

importantforustodeveloptitlesthatyoureallygetthemostoutof.
Tosendusgeneralfeedback,simplysendane-mailto
,andmentionthebooktitleviathesubjectofyour

message.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineither
writingorcontributingtoabook,seeourauthorguideon
www.packtpub.com/authors.

CuuDuongThanCong.com


Customersupport
NowthatyouaretheproudownerofaPacktbook,wehaveanumberof
thingstohelpyoutogetthemostfromyourpurchase.

CuuDuongThanCong.com


Downloadingtheexamplecode
YoucandownloadtheexamplecodefilesforallPacktbooksyouhave
purchasedfromyouraccountat.Ifyoupurchasedthis
bookelsewhere,youcanvisitandregisterto
havethefilese-maileddirectlytoyou.
Thesourcecodewillalsobeavailableontheauthor’swebsite
atwww.ottodroid.net.

CuuDuongThanCong.com



Errata
Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,
mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybea
mistakeinthetextorthecode—wewouldbegratefulifyouwouldreportthis
tous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpus
improvesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereport
thembyvisitingktpub.com/support,selectingyourbook,clicking
ontheerratasubmissionformlink,andenteringthedetailsofyourerrata.
Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerrata
willbeuploadedonourwebsite,oraddedtoanylistofexistingerrata,under
theErratasectionofthattitle.Anyexistingerratacanbeviewedbyselecting
yourtitlefrom />
CuuDuongThanCong.com


Piracy
PiracyofcopyrightmaterialontheInternetisanongoingproblemacrossall
media.AtPackt,wetaketheprotectionofourcopyrightandlicensesvery
seriously.Ifyoucomeacrossanyillegalcopiesofourworks,inanyform,on
theInternet,pleaseprovideuswiththelocationaddressorwebsitename
immediatelysothatwecanpursuearemedy.
Pleasecontactusat
withalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthors,andourabilitytobringyou
valuablecontent.

CuuDuongThanCong.com



Questions
Youcancontactusatifyouarehavingaproblemwith
anyaspectofthebook,andwewilldoourbesttoaddressit.

CuuDuongThanCong.com


×