CS代考 CS 213 SOFTWARE METHODOLOGY

CS 213 SOFTWARE METHODOLOGY
LILY CHANG ASSOCIATE TEACHING PROFESSOR DEPARTMENT OF COMPUTER SCIENCE RUTGERS UNIVERSITY – NEW BRUNSWICK FALL 2021

Essential Components in an Android App

Copyright By PowCoder代写 加微信 powcoder

Android App Fundamentals
Android apps can be written using Kotlin, Java, and C++ languages.
The Android SDK tools compile your code along with any data and resource files into an APK, an Android package, which is an archive file with an .apk suffix.
One APK file contains all the contents of an Android app and is the file that Android- powered devices use to install the app.

Android App Fundamentals
• EachAndroidapplivesinitsownsecuritysandbox,protectedbythefollowingAndroidsecurityfeatures:
• TheAndroidoperatingsystemisamulti-userLinuxsysteminwhicheachappisadifferentuser.
• Bydefault,thesystemassignseachappauniqueLinuxuserID(theIDisusedonlybythesystemandis unknown to the app). The system sets permissions for all the files in an app so that only the user ID assigned to that app can access them.
• Eachprocesshasitsownvirtualmachine(VM),soanapp’scoderunsinisolationfromotherapps.
• Bydefault,everyapprunsinitsownLinuxprocess.TheAndroidsystemstartstheprocesswhenanyof the app’s components need to be executed, and then shuts down the process when it’s no longer needed or when the system must recover memory for other apps.

Android App Fundamentals
• TheAndroidsystemimplementstheprincipleofleastprivilege;i.e.,eachapp,bydefault,hasaccessonlyto the components that it requires to do its work and no more. This creates a very secure environment in which an app cannot access parts of the system for which it is not given permission. However, there are ways for an app to share data with other apps and for an app to access system services:
• It’spossibletoarrangefortwoappstosharethesameLinuxuserID,inwhichcasetheyareableto access each other’s files. To conserve system resources, apps with the same user ID can also arrange to run in the same Linux process and share the same VM. The apps must also be signed with the same certificate.
• Anappcanrequestpermissiontoaccessdevicedatasuchasthedevice’slocation,camera,and Bluetooth connection. The user has to explicitly grant these permissions.

App Components
App components are the essential building blocks of an Android app.
Each component is an entry point through which the system or a user can enter your app. Some components depend on others.
There are four different types of app components:
• Activities
• Services (can run without UI)
• Broadcast receivers (can run without UI) • Content providers
Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed.

Activities
• Themobile-appexperiencediffersfromitsdesktopcounterpartinthata user’s interaction with the app doesn’t always begin in the same place. Instead, the user journey often begins non-deterministically.
• Forexample,ifyouareusingasocialmediaappthatthenlaunches your email app, you might go directly to the email app’s screen for composing an email.
• TheActivityclassisacrucialcomponentofanAndroidapp,andtheway activities are launched and put together is a fundamental part of the platform’s application model.
• Whenoneappinvokesanother,thecallingappinvokesanactivityin the other app,
• Unlikeprogrammingparadigmsinwhichappsarelaunchedwithamain() method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its lifecycle.

Activities
• Anactivityprovidesthewindowinwhichthe app draws its UI. This window typically fills the screen but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen
• Mostappscontainmultiplescreens,which means multiple activities; one activity in an app is specified as the main activity, which is the first screen to appear when the user launches the app
• Eachactivityislooselyboundtotheother activities; there are usually minimal dependencies among the activities in an app.
• Touseactivitiesinyourapp,youmust register information about them in the app’s manifest, and you must manage activity lifecycles appropriately.

Activity Lifecycle
• Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the “back stack”).
• When the user is done with the current activity and presses the Back button, the activity is popped from the stack and destroyed, and the previous activity resumes.
• Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re- enters the activity.
• Good implementation of the lifecycle callbacks can help ensure that your app avoids crashing

Back Stack
• A task is a collection of activities that users interact with when performing a certain job.
• The activities are arranged in a stack—the back stack—in the order in which each activity is opened.
• For example, an email app might have one activity to show a list of new messages. When the user selects a message, a new activity opens to view that message. This new activity is added to the back stack. If the user presses the Back button, that new activity is finished and popped off the stack.

Up and Back buttons

onCreate() Method
• You must implement this callback, which fires when the system first creates the activity.
• On activity creation, the activity enters the Created state. In the onCreate() method, you perform basic application startup logic that should happen only once for the entire life of the activity; for example, instantiate some class-scope variables.
• This method receives the parameter savedInstanceState, which is a Bundle object containing the activity’s previously saved state, or null If the activity has never existed before
protected void onCreate(Bundle savedInstanceState) { }

• You can bind data to lists, associate the activity with a ViewModel, and instantiate some class- scope variables.

onStart() Method • YouractivitydoesnotresideintheCreatedstate.
• AftertheonCreate()methodfinishesexecution,theactivityentersthe Started state, and the system calls the onStart() and onResume() methods in quick succession
• WhentheactivityenterstheStartedstate,thesysteminvokesthis callback and makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive. For example, this method is where the app initializes the code that maintains the UI.
• TheonStart()methodcompletesveryquicklyand,aswiththeCreated state, the activity does not stay resident in the Started state. Once this callback finishes, the activity enters the Resumed state, and the system invokes the onResume() method.

OnResume() Method
• WhentheactivityenterstheResumedstate,itcomestotheforeground, and then the system invokes the onResume() callback.
• Thisisthestateinwhichtheappinteractswiththeuser
• Theappstaysinthisstateuntilsomethinghappenstotakefocusaway from the app. Such an event might be, for instance, receiving a phone call, the user’s navigating to another activity, or the device screen’s turning off.
• Whenaninterruptiveeventoccurs,theactivityentersthePausedstate, and the system invokes the onPause() callback.
• IftheactivityreturnstotheResumedstatefromthePausedstate,the system once again calls onResume() method. For this reason, you should implement onResume() to initialize components that you release during onPause(), and perform any other initializations that must occur each time the activity enters the Resumed state.

The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed);
It indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode).
Use the onPause() method to pause or adjust operations that should not continue (or should continue in moderation) while the Activity is in the Paused state, and that you expect to resume shortly
You can also use the onPause() method to release system resources, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.

OnStop() Method
• When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback.
• This may occur, for example, when a newly launched activity covers the entire screen. The system may also call onStop() when the activity has finished running and is about to be terminated.
• In the onStop() method, the app should release or adjust resources that are not needed while the app is not visible to the user.
• You should also use onStop() to perform relatively CPU- intensive shutdown operations.

onDestroy() is called before the activity is destroyed. The system invokes this callback either because:
• The activity is finishing (due to the user completely dismissing the activity or due to finish() being called on the activity), or
• The system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode)
If the activity is finishing, onDestroy() is the final lifecycle callback the activity receives. If onDestroy() is called as the result of a configuration change, the system immediately creates a new activity instance and then calls onCreate() on that new instance in the new configuration.
The onDestroy() callback should release all resources that have not yet been released by earlier callbacks such as onStop().
OnDestroy() Method

A service is a general-purpose entry point for keeping an app running in the background for all kinds of reasons
A service does not provide a user interface; for example, a service might play music in the background while the user is in a different app

A broadcast receiver is a component that enables the system to deliver events to the app outside of a
regular user flow, allowing the app to respond to system-wide broadcast announcements.
Because broadcast receivers are another well- defined entry into the app, the system can deliver
broadcasts even to apps that aren’t currently running.
• For example, an app can schedule an alarm to post a notification to tell the user about an upcoming event… and by delivering that alarm to a BroadcastReceiver of the app, there is no need for the app to remain running until the alarm goes off.

A content provider manages a shared set of app data that you can store in the file system, in a SQLite database, on the web, or on any other persistent storage location that your app can access.
Through the content provider, other apps can query or modify the data if the content provider allows it.
• For example, the Android system provides a content provider that manages the user’s contact information. As such, any app with the proper permissions can query the content provider, such as ContactsContract.Data, to read and write information about a particular person.

In most cases, every Android application runs in its own Linux process
and Application Lifecycle
An unusual and fundamental feature of Android is that an application process’s lifetime is not directly controlled by the application itself. Instead, it is determined by the system through a combination of the parts of the application that the system knows are running, how important these things are to the user, and how much overall memory is available in the system.
It is important that application developers understand how different application components (in particular Activity, Service, and BroadcastReceiver) impact the lifetime of the application’s process. Not using these components correctly can result in the system killing the application’s process while it is doing important work.

Navigating between
activities
An app is likely to enter and exit an activity, perhaps many times, during the app’s lifetime. For example, the user may tap the device’s Back button, or the activity may need to launch a different activity, i.e., when an app needs to move from the current screen to a new one.
Depending on whether your activity wants a result back from the new activity it’s about to start, you start the new activity using either the startActivity() or
the startActivityForResult() method. In either case, you pass in an Intent object.

Coordinating Activities
• Whenoneactivitystartsanother,theybothexperiencelifecycletransitions.
• ThefirstactivitystopsoperatingandentersthePausedorStoppedstate,whiletheotheractivityiscreated.Incasethese activities share data saved to disc or elsewhere, it’s important to understand that the first activity is not completely
stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.
• Theorderoflifecyclecallbacksiswelldefined,particularlywhenthetwoactivitiesareinthesameprocess(app)andone is starting the other. Here’s the order of operations that occur when Activity A starts Activity B:
1. Activity A’s onPause() method executes.
2. Activity B’s onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
3. Then, if Activity A is no longer visible on screen, its onStop() method executes.
• Thispredictablesequenceoflifecyclecallbacksallowsyoutomanagethetransitionofinformationfromoneactivityto another.

Activating Components
Because the system runs each app in a separate process with file permissions that restrict access to other apps, your app cannot directly activate a component from another app.
To activate a component in another app, deliver a message to the system that specifies your intent to start a particular component. The system then activates the component for you.
Activities, services, and broadcast receivers are activated by an asynchronous message called an intent.
For activities and services, an intent defines the action to perform
For broadcast receivers, the intent simply defines the announcement being broadcast.

Intent Object
• The Intent object specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application).
• An Intent object can also carry small amounts of data to be used by the activity that is started.
• If the newly started activity does not need to return a result, the current activity can start it by calling the startActivity() method.
• When working within your own application, you often need to simply launch a known activity
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);

• AnIntentprovidesafacilityforperforminglateruntimebindingbetweenthecodeindifferentapplications.
• Itsmostsignificantuseisinthelaunchingofactivities,whereitcanbethoughtofasthegluebetweenactivities. • Itisbasicallyapassivedatastructureholdinganabstractdescriptionofanactiontobeperformed.
• Althoughintentsfacilitatecommunicationbetweencomponentsinseveralways,therearethreefundamentalusecases: • Startinganactivity,whichrepresentsasinglescreeninanapp
• Startingaservice,whichisacomponentthatperformsoperationsinthebackgroundwithoutauserinterface
To ensure that your app is secure, always use an explicit intent when starting a Service and do not declare intent filters for your services
• Deliveringabroadcast,whichisamessagethatanyappcanreceive

Intent – Starting an activity
Intent intent = new Intent(this, SignInActivity.class); startActivity(intent);
• An Activity represents a single screen in an app. You can start a new instance of an Activity by passing an Intent to startActivity(). The Intent describes the activity to start and carries any necessary data.
• If you want to receive a result from the activity when it finishes, call startActivityForResult(). Your activity receives the result as a separate Intent object in your activity’s onActivityResult() callback; See reference here: https://developer.android.com/training/basics/intents/result

Intent Types
• Explicitintentsspecifywhichapplicationwillsatisfytheintent,bysupplyingeitherthetargetapp’spackagenameora fully-qualified component class name. You’ll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start.
• Implicitintentsdonotnameaspecificcomponent,butinsteaddeclareageneralactiontoperform,whichallowsa component from another app to handle it.
For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map.
Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.

Implicit Intent
•Activity A creates an Intent with an action description and passes it
to startActivity().
•The Android System searches all apps for an intent filter that matches the intent.
•When a match is found, the system starts the matching activity (Activity B) by invoking its onCreate() method and passing it the Intent.

Intent filter
• An intent filter is an expression in an app’s manifest file that specifies the type of intents that the component would like to receive.
• For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent

Building an Intent
• AnIntentobjectcarriesinformationthattheAndroidsystemusestodeterminewhichcomponenttostart (such as the exact component name or component category that should receive the intent), plus information that the recipient component uses in order to properly perform the action (such as the action to take and the data to act upon).
• TheprimaryinformationcontainedinanIntentis
• Componentname–afullyqualifiedclass(package)name; Without a component name, the intent is implicit
• Action –a string that specifies the generic action to perform, (ACTION_VIEW, ACTION_SEND)
• Data–theURI(aUriobject)thatreferencesthedatatobeactedonand/ortheMIMEtypeofthat
• Category–astringcontainingadditionalinformationaboutthekindofcomponentthatshouldhandle the intent. (CATEGORY_BROWSABLE, CATEGORY_LAUNCHER, CATEGORY_APP_MAPS)
• Extra–key-valuepairsthatcarryadditionalinformationrequiredtoaccomplishtherequestedaction;

EXAMPLE – EXPLICIT INENT
You built a service in your app, named DownloadService, designed to download a file from the web, you can start it with the following code:
// Executed in an Activity, so ‘this’ is the Context
// The fileUrl is a string URL, such as “http://www.example.com/image.png” Intent downloadIntent = new Intent(this, DownloadService.class); downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);

Example – Implicit Intent
Is useful when your app cannot perform the action, but other apps probably can and you’d like the user to pick which app to use.
• For example, if you have content that you want the user to share with other people, create an intent with the ACTION_SEND action and add extras that specify the content to share

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com