Android App Development 2 Flashcards Preview

Android Dev Java Essentials > Android App Development 2 > Flashcards

Flashcards in Android App Development 2 Deck (55):

Features of the onCreate() method

- All subclasses of Activity must implement it.- Receives an intent if started from another activity- Must define the activity layout with the setContentView() method.- Performs the initial setup of the activity components



The manifest file defines the app package and defines things such as the launcher icon, a theme and definitions of the app's activities.It may also define permissions.


The element within the element in XML

The element defines how the activity can be used.


How to identify in XML which activity is the first activity the user sees when they launch the app.

An element which has an action of MAIN and category of LAUNCHER



An object which provides runtime binding between separate components (such as two activities).Represents an app's 'intent to do something'.


Parameters for creating a new intent

1). A Context- In most cases you will pass 'this' since you are passing the current acitivity and the Activity is a subclass of Context.2). The Class of the app component to which the system should deliver the intent: activityName.class


How to retrieve an element in the source code

findViewById( to cast it to the appropriate type.


How to add additional stuff to an intent

Use the putExtra() method


Parameters of the putExtra() method

It takes a key-value pair (called an extra).Key (1st param): It's good practice to use your package name as a prefix for this. E.g. com.mycompany.myapp.MESSAGE. The key can be declared as a public constant in the class so it can be used multiple times.Value (2nd param): This is the stuff you want to send.


How to start a new activity

Most commonly done by using intents.startActivity(intentObj)


All activities are invoked by an intent. How would you retrieve this intent?

Call the getIntent() function- returns the intent object:Intent myIntent = getIntent();


An intent sends an extra which is a string data type. How would you retrieve this from the activity which was invoked via this intent (Called MyActivity)?

Intent intent = getIntent();String msg = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);(Here EXTRA_MESSAGE is a static string defined in MyActivity which is how this is possible- otherwise you'd need to create an object of the class first).


Why should you put strings in the strings.xml file instead of hardcoding them?

So you can support multiple languages in the long run.


How to add support for more langauges?

Create additional values directories inside the res/ that includes a hyphen and the ISO language code at the end of the directory name.Example:MyProject/res/values/strings.xml (This is the default)MyProject/res/values-es/strings.xml (Spanish)MyProject/res/values-fr/strings.xml (French)


How to refer to a string resource

"IN CODE:R.string.Example:TextView textView = new TextView(this);textView.setText(R.string.hello_world);IN XML:@string/Example:android:layout_width=""wrap_content"" android:layout_height=""wrap_content"" android:hint=""@string/edit_message"" />(Note the string resource name attribute can be called anything- in the example it is the same as the ID just to make it clear what element it's for)."


Generalised screen sizes

- Small- Normal- Large- Xlarge


Generalised screen densities

- Low (ldpi)- Medium (mdpi)- High (hdpi)- Extra high (xhdpi)


How to support different screen sizes.

Create a unique layout XML file for each screen size you want to support. These should go in the relevant directories similar to the structure the string resources were.General resources directory syntax: layout-Example:MyProject/res/layout/main.xml (default)MyProject/res/layout/layout-large/main.xml (Large screens)


What to consider when supporting different screen sizes.

Focus on the layout structure that affects the user experience (such as the size or position of important views relative to sibling views).Android automatically scales your layout in order to properly fit the screen, thus your layouts for different screen sizes don't need to worry about the absolute size of UI elements.Note: Portrait and landscape are considered as two different screen 'sizes' so you should have different layout files for these as well.


How to generate images for different screen densities (which you should do!)

Start with your raw resource in vector format and generate the images for each density using the appropriate scales:- xhdpi: 2.0- hdpi: 1.5- mdpi: 1.0 (baseline)- ldpi: 0.75Place each image resource in the appropriate drawable resource directory.


Factor to scale an image for extra-high density screen



Factor to scale an image for high density screen



Factor to scale an image for medium density screen



Factor to scale an image for low density screen



How to specify the minimum and maximum API levels your app is compatible with

"In the AndroidManifest.xml file, the element you specify the minSdkVersion and targetSdkVersion attributes: ..."


What should you set the targetSdkVersion value to in AndroidManifest.xml

The latest Android version available


How to ensure code which relies on higher API levels is only executed when those APIs are available on the system?

The Build class contains constants which allow you to check the system version at runtime.Build.VERSION_SDK_INTBuild.VERSION_CODES.


Should you worry about using XML attributes which are only supported by newer Android versions?

No since Android ignores XML attributes which aren't supported by the current device.


How to apply a default Android theme to the current Activity

">Example- make your activity look like a dialog box:"


How to apply a custom theme to your activity

"The custom theme is defined in /res/values/styles.xml"


How to apply a theme to your entire app (all activities)

Specify the android:theme attribute to the element


By implementing the activity lifecycle methods properly ensures your app behaves well in what ways?

- Does not crash if user receives a phone call or switches to another app while using your app.- Does not consume valuable system resources when the user is not actively using it.- Does not lose the user's progress if they leave your app and return to it at a later time.- Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation.


The three static states of the activity lifecycle

- Resumed/Running- Paused- Stopped


Resumed/Running state

The activity is in the foreground and the user can interact with it.


Paused state

The activity is partially obscured by another activity- the other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The paused activity does not receive user input and cannot execute any code.


Stopped state

The activity is completely hidden and not visible to the user- it is considered to be in the background.While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.


Transient states

- Created- StartedThe system quickly moves from these states to the next state by calling the next lifecycle method.After the system calls onCreate(), it quickly calls onStart(), which is quickly followed by onResume()


Why do we implement onCreate() method to perform basic startup logic and not onStart()

onCreate() is called only once in the entire duration of using the activity whereas onStart() may be called multiple times- e.g. after the activity has been stopped it is restarted by calling onStart() after onRestart()


Something which you will likely need to put in the onCreate() method

Define the user interface for the activity by using the setContentView() method.E.g. setContentView(R.layout.main_activity);


Where should you perform cleanup code?

Your activity should perform clean-up code during onPause() and onStop()Note: If your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy()


When may onDestroy() be called before onPause() and onStop()?

When you call finish() within the onCreate() method.You might do this when the activity operates as a temporary decision maker to launch another activity.


What should you usually use the onPause() callback to do?

- Stop animations or other ongoing actions that could consume CPU- Commit unsaved changes *but only if users expect such changes to be permanently saved when they leave* (such as a draft email).- Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect the battery life while your activity is paused and the user does not need them.


Important thing you must do when overriding activity callback methods

Call the superclass method first.E.g.super.onPause()


What to avoid doing in the onPause method and what to do instead.

Avoid performing CPU-intensive work during onPause(), such as writing to a database, because it can slow the visible transition to the next activity.You should instead perform heavy load shutdown operations during onStop()Keep the amount of operations done in onPause SIMPLE.


What should you do in the onResume() callback?

You should implement onResume() to initialise components that you released during onPause() and perform any initialisations that must occur each time the activity enters the Resumed state.


Key scenarios in which your activity is stopped and restarted

- The user opens the Recent Apps window and switches from your app to another app. The activity in your app that's currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts.- The user performs an action in your app that starts a new activity. The current activity is s topped when the second activity is created. If the user then presses the back button, the first activity is restarted.- The user receives a phone call while using your app on his/her phone.


onStart() vs onRestart()

It's uncommon that an app needs to use onRestart() since you will generally need to perform the same initialisations that you do when the app is first started in the onStart() method. For this reason, you generally use the onStart() method as the counterpart to the onStop() method.


Instance state

This is a collection of key-value pairs stored in a Bundle object. This is created when an activity is destroyed by the system due to system constraints (rather than normal app behaviour- pressing the back button or the activity finishes itself).Although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity issuing a set of saved data that describes the state of the activity when it was destroyed- the instance state.*Note:* Your activity is destroyed and recreated each time the user rotates the screen because the system configuration has changed and your activity might need to load alternative resources (such as layout).


When will you not need to write code to recreate an activity when it has been destroyed?

By default, the Bundle instance state saves information about each View object in your activity layout. If your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you.


When will you need to write code to recreate an activity when it has been destroyed?

Your activity may have more state information that you'd like to store, such as member variables that track the user's progress in the activity.This will be stuff not to do with the layout.


How to save additional data about the activity state (What method to use)

You must override the onSavedInstanceState() callback method.



The system calls this method when the user is leaving your activity and passes it the Bundle object that will be saved in the event that your activity is destroyed unexpectedly.If the system must recreate the activity later, it passes the same Bundle object to both the onRestoreSavedInstanceState() and onCreate() methods.


What to remember when implementing onSavedInstanceSate()

Like overriding all callback methods, you must remember to call the superclass method first so that the default functions are carried out.


What is important so that the Android system can restore the state of views in your activity

Each view must have a unique ID, supplied by the android:id attribute


Methods of recreating an Activity

There are 2 ways:1). onCreate => If you use this you MUST check if it is null since it is called whether the system is creating a new instance of your activity or recreating a previous one.2). onRestoreInstanceState => Called after onStart() ONLY if there is a saved state to restore, therefore do not need to check if bundle is null.