Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
AndroidProjectsandApps ClassCheck o PowerupAndroidStudioandloadHelloWorldonyourphones.I’llcomearoundandverifythatyou’reabletopushan APKfiletoyourphone. AndroidDocumentation 1. https://developer.android.comistheprimarysourcefordocumentationabouttheAndroidplatformandAPIs. 2. Atthetopofthemainpageare3links:Design,DevelopandDistribute. • DesigntellsyouabouthowthedifferentfeaturesavailableinAndroidcanbeusedtomakeanesthetically interestingapplication. • We’llusetheDeveloplinkalot. o Herewe’llfindAPIGuidesthatdiscusshowthevariouscomponentsaredesignedtoworktogether.Weneed toknowhowtheframeworkandcomponentsworktogetherbeforewecancode. o We’llalsofindundertheReferencelink,theactualclassspecifications.We’llneedtoconsulttheseregularly whenwe’recoding. o TheToolslinkleadsyoutoresourcesforthevariousbuild,debugandreleasetoolsandservicesthatAndroid StudioandotherIDEsusetodevelopAndroidapps. CSCI-300MobileApplicationDevelopment AndroidProjectFiles Let’slookinsideanAndroidStudioproject.Atthetopofthetopleftpanelwecanchoose3differenttabslabeledProject, Structure,andCaptures.ClickonProject.Now,atthetopoftheleftmostpaneisadropdownmenu,chooseAndroid. Thefilesthatcompriseaprojectarestoredinthreedirectories,app,buildandgradle.Youshouldseethecontentsoftheapp andgradledirectories. Theappdirectorycontainsthreesubdirectories: 1. manifests–Amanifestfileisanxmlfilethattellsthedeviceinformationabouttheapp,forexamplewhichactivityto loadfirstandwhichprivilegestheapprequests. 2. java–ThisdirectorycontainsyourappsJavasourcecode. 3. res–Theresourcedirectorycontainsfoursubdirectories: o drawable–foriconsandotherimages o layout–xmlfilesthatdefinetheposition(andotherproperties)ofthevariouscomponentsonascreenlike editboxes,spinners,etc. o mipmap–forapplaunchicons o values–xmlfilesthatprovideaplacetodefinestringandnumericconstants. Note:AllresourcesarecompiledintoasingleRobjectthatcanbereferencedinyourjavacode. TheGradleScriptsdirectorycontainsconfigurationfilesforcompilingandbuildingyourapp.Inparticularthebuild.gradle (Module:app)filecontainsinformationaboutwhichversionsoftheSDKtheapplicationwillrunonandtheapplicationId.The applicationIdmustbethesameasthenameofthedirectoryunderthejavadirectory. AndroidStudioShortcuts AtthebottomoftheAndroidStudioTipsandTrickspageyou’llfindshortcutsformanyfrequentlyusedcommands. CSCI-300MobileApplicationDevelopment ApplicationFundamentals Let’swalkthroughthefundamentsoftheAndroidplatform. o AnappiswritteninJava,andalongwithappresources,iscompiledintoanapkfile. o Androidisamulti-userLinuxoperatingsystem. o WhenanappisinstalledonadeviceitisgivenauniqueuserID. o TheOSsettheownerforalltheapp’sfilestotheuserIDassignedtotheappsothatonlyappcanaccessthem. o Eachapprunsinitsownprocessthatinturnrunsitsownvirtualmachinesothatnoappcan,bydefault,accessthe resourcesofanother. o AppscanhoweverbedesignedtoshareauserID,process,virtualmachine,orresource. o Appsmayalsosharecommunityresourceslikehardware,SMSmessages,contacts,etc.Permissiontousethese resourcesmustbegrantedbytheuseratinstalltime. ApplicationComponents Thereare4distinctcomponentsthatstructureanapplication:Activities,Services,ContentprovidersandBroadcastreceivers. 1. AnActivitydefinesasinglescreenthatcontainsauserinterface.MostappshavemorethanoneActivity,thatis,more thanonescreen.EachActivityisimplementedusingasubclassoftheActivityclass.TheusermovesfromoneActivity toanotheroftenbyusingcontrols(menuoptions,buttons,etc). 2. AServiceisacomponentthatdoesnothaveauserinterfaceandrunsinthebackground.Servicescanremainrunning whentheuserswitchestoanotherapplication.AserviceisimplementedusingasubclassoftheServiceclass. • synchingdatawithdatabase • playingmusic 3. AContentProviderisacomponentthatmanagesshareddata(infiles,db,etc).Itmaybroadcasttootherappsthatithas dataandallowotherappstoreadandwritethedata,solongastheapplicationhasobtainedtheuser’spermission.It CSCI-300MobileApplicationDevelopment mayalsokeepthedataprivatetotheapp.AcontentproviderisimplementedusingasubclassoftheContentProvider class. o e.g.contacts 4. ABroadcastReceiverlistensforspecificsystem-widemessagesandrespondsbyrunningeventhandlers.These messagescanemanatefromthesystem,suchasalowbatterymessage,orcanemanatefromapplications.Abroadcast receiverisimplementedusingasubclassoftheBroadcastReceiverclass. RegisteringComponentsintheManifest Allactivities,servicesandcontentprovidersmustberegisteredinthemanifestfileorelsetheyarenotvisibletotheapp. BroadcastReceiverscanbelistedinthemanifestfileortheycanberegistereddynamicallyusingtheregisterReceiver()method. TheHelloWorldapp,forexample,hasoneActivityimplementedinapp/java/your_namespace/MainActivity.Whenthe AndroidStudiowizardcreatedtheclassfile,itaddedanentryinthemanifestfile.Thisentryregistersourclassnamed MainActivityasthestartingActivityfortheapp. <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> CSCI-300MobileApplicationDevelopment Activities Activitiesarecomponentsthattakeuptheentirescreen.Theuseroftenmovesfromoneactivitybypressingmenuoptions andbuttons.Activitiesarestoredinastackinmemory.Eachapplicationhasitsownstack.ThesetofActivitieswithinastack arereferredtoasatask. Androidallowsmultipletaskstobeinmemoryatanypointintime,butonlyonetaskandoneActivityinthattaskhasfocusat anytime. Whenauserlaunchesanapp,thecurrentlyrunningtask’sstateispreserved,theActivitythatisinfocusisstoppedandthe taskisputinthebackground.AnewtaskiscreatedforthenewappanditsmainActivity(asdefinedinthemanifest)isplaced onanewstack. Whentheuserpressesamenuoptionorbuttontostartanewactivitywithintheapp,thecurrentActivityisstoppedandthe newActivityisplacedonthetopofthestackandgainsfocus.ThisprocesscancontinuecreatingmultipleActivitiesinthe task’sstack. WhentheuserpressesthebackbuttonthetopActivityispoppedfromthestackandtheActivitynowontopisrestarted. Whentheuserpressesthehomebutton,thecurrentActivityisstopped,andthetask(stackincluded)isputinthebackground. Note:Ifanapphasmultipleentrypoints(buttons,menuoptions,etc)toanActivity,thenmultipleinstancesofthesame Activitycanexistinthestack–sobecareful.Thisisusuallynotwhatyouintended. Note:Thesystemmightdestroybackgroundtasksifitneedsadditionalmemory.Topreservedatawhenthishappenswecan implementacallbackmethodthatisinvokedbeforethetaskisdestroyed.SeeSavingActivityState. CSCI-300MobileApplicationDevelopment CreatingNewActivities TocreateanewActivity,selectthedirectorywhereyouwantthenewActivitytoresideintheAndroidfilehierarchy.Then selectFile>New>Activity>EmptyActivity. Note:DONOTCHOOSENew>FileorNew>JavaClass.BychoosingNew>Activity,AndroidStudioautomaticallyaddsthe Activitytothemanifestfile.Theseothermethodsdonot. AndroidStudiowilldisplayaformwhereyouenterinformationabouttheactivity.ActivityNamespecifiesthenameofthe Javaclassthatwillbeadded.ByselectingGenerateLayoutFile,askeletonxmlfilewillbecreated.Thelayoutfileiswhereyou specifytheGUI.ByselectingtheLauncherActivitycheckboxtheappwillbemodifiedtolaunchthecurrentactivitywhenthe appisfirststarted.ByselectingBackwardsCompatibilitythenewactivitywillextendtheAppCompatActivityclass.Thisis preferred(moreonthislater).Last,thePackagenamefieldspecifiestheJavapackagethattheclasswillbestoredin. CSCI-300MobileApplicationDevelopment ApplicationLifeCycle WedescribedabovewhathappenswhendifferentappschangefocusinAndroid.Inthissectionwe’lldiscussanapplication’s lifecycle. Activitieshave3states:Running(resumed),Paused(,andStopped. 1. Running-TheActivityhastheuserfocus. 2. Paused-TheActivityisbehindanotheractivitybutcanbepartiallyseen.Itsstateismaintained. 3. Stopped–Theactivityisobscuredbyanotheractivity.Itsstateismaintained. Whenanapphasmultipleactivitiesthatarepoppedonandoffthestack,weoftenwanttodothingsbeforeanActivitylooses focusordothingsbeforeanActivityonthestackregainsfocus.Wecanperformthesetasksimplementingcallbackmethods whicharecalledbeforethestateofanActivityischanged. ThemostcommonlyusedcallbacksareonCreate()andononPause(). public class ExampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // A new activity is created. // Display layout here } @Override CSCI-300MobileApplicationDevelopment protected void onRestart() { super.onStart(); // Either the apps task was restarted or the user hit the // back button which destroyed the stacks top Activity, // leaving this Activity active. } @Override protected void onStart() { super.onStart(); // The activity is about to become visible. } @Override protected void onResume() { super.onResume(); // The activity is about to gain focus and the activity is put // on the top of the stack. } @Override protected void onPause() { super.onPause(); // Current Activity is loosing focus. Either another Activity is CSCI-300MobileApplicationDevelopment // pushed on the stack or the entire task is stopped. } @Override protected void onStop() { super.onStop(); // The activity is no longer visible. } @Override protected void onDestroy() { super.onDestroy(); // The activity is about to be destroyed. // call onSaveInstanceState() to save user information like username. } } Note:Youmustcallthesuperclass’callbackmethodfirstinthesecallbackmethods. LayoutsandWidgets TheGUIthatisdisplayedinanActivityisdefinedinalayoutxmlfileresidingintheres/layoutdirectory.Byclickingona layoutfile,AndroidStudiodisplaysaprototypeonthescreen.WecanseetheactualtextofthexmlfilebyclickingontheText tabunderinprototypedisplay. CSCI-300MobileApplicationDevelopment AnActivity’slayoutfilespecifieswidgetswithinalayout.Eachwidgethaspropertiesthataremodifiable. Let’sgobacktotheprototypebyclickingtheDesigntab.Awidgetisacomponentthattheusercansee:TextViews,Buttons, CheckBoxes,etc.AndroidStudioallowsustodraganddropthemintoourlayout. Alayoutcontrolshowthewidgetsaredisplayedwithrespecttooneanother.Youmayhavenestedlayoutsinonesinglexml file. Exercise:AddasecondTextViewtoyourHelloWorldlayout.Experimentwiththedifferentwidgets. CSCI-300MobileApplicationDevelopment