0% found this document useful (0 votes)
11 views

Lesson 8 Android Mobile Application Development1

The document provides an overview of the structure and essential files of an Android project, detailing the purpose of directories such as /src, /gen, /res, and the AndroidManifest.xml file. It explains the lifecycle of an Activity, including key methods like onCreate(), onStart(), onResume(), and others that manage the Activity's state. Additionally, it emphasizes the role of the AndroidManifest.xml in defining application components and permissions, and includes code examples for better understanding.

Uploaded by

somose2111
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Lesson 8 Android Mobile Application Development1

The document provides an overview of the structure and essential files of an Android project, detailing the purpose of directories such as /src, /gen, /res, and the AndroidManifest.xml file. It explains the lifecycle of an Activity, including key methods like onCreate(), onStart(), onResume(), and others that manage the Activity's state. Additionally, it emphasizes the role of the AndroidManifest.xml in defining application components and permissions, and includes code examples for better understanding.

Uploaded by

somose2111
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Overview of the Android Project Files

The following files and directories are created for the Android application. The list below is just
an overview of the files and directories
• /src folder— The folder that contains the entire Java source file of the application. The folder
contains a directory structure corresponding to the package name supplied in the application. The
folder contains the project’s default package: com.company.basichelloworld. On expanding the
package, you find the Activity of the application, the MainActivity.java file, within it.
• /src/com.company.basichelloworld — Refers to the package name of the application. To avoid
any collision among the class names, variable names, and so on used in the application with
those of other Android applications, each application has to be packaged in a unique container.
• /src/com.company.helloworld/MainActivity.java- The default Activity file of the application.
Recall that each application has at least one Activity that acts as the main entry point to the
application. The Activity file is automatically defined as the default launch Activity in the
Android Manifest file.
• /gen folder—Contains Java files generated by ADT (Android Devt Tool) on compiling the
application. That is, the gen folder will come into existence after compiling the application for
the first time. The folder contains two files
1. R.java: file that contains references for all the resources defined in the res directory.
2. BuildConfig.java: file that is used to run code only in debug mode. It contains a DEBUG
constant that helps in running debug-only functions.
• /gen/com.company.basichelloworld/R.java—All the layout and other resource information that
is coded in the XML files is converted into Java source code and placed in the R.java file. It also
means that the file contains the ID of all the resources of the application. The R.java file is
compiled into the Java byte code files and then converted into .dex format. You should never edit
this file by hand, as it is automatically overwritten when you add or edit resources.
• /assets folder—The assets folder is empty by default. It stores raw asset files that may be
required in the application. It may contain fonts, external JAR(Java ARchive) files, and so on to
be used in the application. The assets folder is like a resource folder where uncompiled resources
of the project are kept and no IDs are generated for the resources kept here
• Android SDK jar file—The jar file for the target platform
• /bin folder—The folder that stores the compiled version of the application.
• /res folder—The folder where all application resources (images, layout files, and string files)
are kept. Instead of hard coding an image or string in an application, a better approach is to
create a respective resource in the res folder and include its reference in the application. Each
resource is assigned a unique resource ID, which automatically appears in the R.java file and
thus in the R class after compilation, enabling us to refer to the resource in the code

1
• /res/drawable-xhdpi, /res/drawable-hdpi, /res/drawablemdpi, /res/drawable-ldpi—the
application’s icon and graphic resources are kept in these folders. Because devices screens of
different densities, the graphics of different resolutions are kept in these folders. Usually,
graphics of 320dpi, 240dpi, 160dpi, and 120dpi are used in Android applications. The
application picks up the graphic from the correct folder after determining the density of the
current device.
• /res/layout—Stores the layout file(s) in XML format.
• /res/values—Stores all the values resources. The values resources include many types such as
string resource, dimension resource, and color resource.
• /res/layout/activity_main.xml—The layout file used by MainActivity to draw views on the
screen. The views or controls are laid in the specified layout.
• /res/values/strings.xml—Contains the string resources. String resources contain the text matter
to be assigned to different controls of the applications.
• AndroidManifest.xml—The central configuration file for the application. It is one of the most
important file in the Android project structure. It contains information of the package, including
components of the application such as activities, services, broadcast receivers, content provider
• project.properties—A build file used by Eclipse and the Android ADT plug-in. It contains
project settings such as the build target. You can use this file to change various properties of the
project. If required, the file should not be edited directly but through editors available in Eclipse.
It’s clear that the Java Activity file is the main file that drives the entire Android application.
Understanding Activities
An Activity is a single screen in Android. It is like a window in a desktop app, or a Frame in a
Java program. An Activity allows you place all your UI components or widgets together on the
screen. Every unique screen the user interacts with in an application is displayed through an
Activity—one Activity for each screen.
Users can interact with an application by performing different actions with the visual controls
found in the Activity. A simple application may consist of just one Activity, whereas large
applications contain several Activities. Each Activity of an application operates independently of
the others.
If you have worked with C, C++ or Java programming language then you must have seen that
your program starts from main() function. Very similar way, Android system initiates its
program within an Activity starting with a call on onCreate() callback method. There is a
sequence of callback methods that start up an activity and a sequence of callback methods that
tear down an activity.
A stack of Activities is maintained while running an application, and the Activity at the top of
the stack is the one currently being displayed. When the Back button is pressed, the Activity is
popped from the stack, making the previous Activity the current Activity, which therefore

2
displays the previous screen. The transition from one Activity to another is accomplished
through the use of asynchronous messages called intents(Messages wiring components
together).
Intents can be used to pass data from one Activity to another. All of the Activities in the
application must be defined in the Application’s manifest file, an XML file that keeps track of all
the components and permissions of the application.
Each Activity in an Android application is either a direct subclass of the Activity base class or a
subclass of an Activity subclass.
Activity life cycle
Activities have life cycles and inherit a set of life cycle methods from the Activity base class that
are executed when the corresponding life cycle state of the Activity is reached.
The Android Activity life cycle defines the states or events that an Activity goes through from
the time it is created until it finishes running. The Activity monitors and reacts to these events by
executing methods that override the Activity class methods for each event.
Each time the Activity state changes, one of the following lifecycle methods will be called on the
Activity class. The lifecycle method of Activity describes how activity will behave at different
states
 onCreate(): This is called when the Activity is first initialized. You need to implement this
method in order to do any initialization specific to your Activity. Views are created, bind data,
etc. A Bundle object is passed where all the previous activity states are captured.
 onStart(): This is called the first time that the Activity is about to become visible to the user, as
the Activity prepares to come to the foreground become interactive. Once this callback finishes,
the onResume() method will be called.
 onResume(): When the Activity goes into this state, it begins to interacts with the user. The
Activity continues in this state till something happen to take focus from the app or Activity (such
as an incoming call). When this happens, the onPause() method will be called

onPause(): This method is used to pause operations that should not happen when the Activity is
in paused state. A call to this method indicates that the user is leaving the app. For example, in a
music player app, an incoming call will cause the app to transition into a paused state. This
should mute or pause the currently playing music. When the user returns to the app, the
onResume() method will be called.
 onStop(): This method is called when the Activity is no longer visible in the app. It can
happen, for example, when another Activity has been loaded and is taking the full screen of the
device. When this method is called, the Activity is said to be in a stopped state. In this state, the
system either calls the onRestart() to bring back interactivity with Activity. Or it calls the
onDestroy() method to destroy the Activity.

3
 onDestroy(): This gets called before the Activity is destroyed. The system calls this method
when a user terminates the Activity, or because the system is temporarily destroying the process
that contains the Activity to save space. Be sure to free up any resources your Activity has
created in this method, or else your app will have a memory leak!
 onRestart(): This gets called when an Activity restarts after it had been stopped.
All the activities of an application, permissions, and intents are defined through the XML-
structured manifest file AndroidManifest.xml. For each Activity, there needs to be an entry in the
AndroidManifest.xml file, where you can define labels, permissions, and so on. In fact, the
manifest file is the configuration file where all the different components of the application are
defined.
An example XML file describing the layout of an activity
<LinearLayout xmlns:"http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>
Android App Development
An example Java source code file of an activity
public class Main Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

4
setContentView(R.layout.activity_display_message);
EditText input = (EditText)findViewById(R.id.edit_message);
...
}
}

Example: program to demonstrate the life cycle methods of an activity


import android.app.Activity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();

5
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
ROLE OF THE ANDROID MANIFEST FILE
The AndroidManifest.xml is a configuration file. It is created by ADT when creating a new
Android project and is kept in the project’s root directory. The manifest file presents essential
information about your app to the Android system, information the system must have before it
can run any of the app's code.
It’s an XML file that defines the overall structure and information about the application for
example, the activities, services, and intents used in the application. It also contains the

6
permissions that the application might need to run. The manifest also defines metadata of the
application such as its icon and label. Besides this, the file also contains the information required
in building and packaging the application for installing and deploying it on an Android device or
the emulator. To sum up, the application manifest file contains all the essential information
required by the Android system to run the application.
The manifest essentially fulfills the following roles:
 It makes key information about the app available without having to read other files in the
package or run the application.
 It defines which components of the application (such as activities and services) will be
accessible externally to other apps, and how those components interact with other apps.
 It unambiguously declares which components and resources (icons, text strings, etc.) to use in
which cases, in particular with relation to other apps.
 It lists the libraries that the application must be linked against.
For example, if your app can accept files shared from other apps, the manifest says which
component will receive the files, and what kind of files it can receive.
The main advantage of this approach is, it puts all of the information in one place, which reduces
the chance of mistakes or human error when a developer is making an app. It is also an
extensible system, so other kinds of data can be added later without breaking existing apps. And
being able to read one file to get all the app’s metadata can help with performance

Default Code in the Android Manifest File


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.welcomemsg"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

7
<activity
android:name=".WelcomeMsgActivity"
android:label="@string/title_activity_welcome_msg" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

The <manifest> tag, is the root element of this XML document and contains several attributes:
• android—Identifies the Android namespace used to provide several system attributes used
within the application.
• package—Its value is set to the application’s Java package. The name of the application
package acts as the unique identifier for the application in the Android device.
• versionCode/versionName—The versionCode attribute is used to define the current application
version.
The version is used internally to compare application versions. The versionName attribute is
used to specify a version number that is displayed to users.
• <uses-sdk>—This tag is optional and is used to specify the maximum, minimum, and preferred
API level required for the application to operate. Three attributes are used with this tag as
follows:
• android:minSdkVersion—Used to specify the minimum API level required for this application
to run. The default value is “1.” For example, the following attribute says that the minimum API
level required by the application is 15: android:minSdkVersion="15"
Hence, the application will run on API Level 15 and above, but will not run on API Level 14 or
below.
• android:targetSdkVersion—Used to specify the preferred API level on which the application is
designed to run.
• android:maxSdkVersion—Used to specify the maximum API level supportable by the
application; that is, the application cannot run on an API level higher than the one specified in

8
this attribute. While installing the application, the Android system checks the <uses-sdk>
attributes defined in the application’s manifest files and compares it with its own internal API
level. The application can be installed only if
 The value of the android:minSdkVersion attribute of the application must be less than or equal
to the system’s API level. If the android:minSdkVersion attribute is not declared, it is assumed
that the requires API Level 1.
 The value of the android:maxSdkVersion attribute of the application (if it is declared) must be
equal to, or greater than, the system’s API level.
• <application> tag—Nested within <manifest> is <application>, which is the parent of
application control tags. The icon and label attributes of the application tag refer to icon and
label resources that will be displayed in Android devices to represent the application. The term
"@drawable/icon" refers to the image file icon.png in the res/drawablefolder, and
"@string/app_name" refers to the control resource with ID app_name in the strings.xml file that
is stored in the res/values folder of the application.
• <activity> tag—Nested within <application> is the <activity> tag, which describes an Activity
component.
This tag’s name attribute identifies a class that is an Activity, WelcomeMsgActivity. This name
begins with a period character to show that it’s relative to the
com.androidunleashed.welcomemsg package. That is, the WelcomeMsgActivity is relative to
<manifest>’s package value, com.androidunleashed.welcomemsg.
Remember that on creating the new Android project WelcomeMsg, an Activity named
WelcomeMsgActivity was automatically created for us in the specified package
com.androidunleashed.welcomemsg by the ADT

• <intent- filter>—Nested within <activity> is the <intent-filter>. The intents are used to interact
with the applications and services. By default, the intent specifies the action as MAIN and the
category as LAUNCHER; that is, it makes this Activity available from the application launcher,
allowing it to launch when the application starts. Basically, the <intent-filter> tag declares the
capabilities of different components through the nested <action> and <category> tags.
Besides the preceding default tags used in the manifest file, the following are some of the most
commonly used tags:
• <service> tags—Used for declaring services. Services refer to the processes that run in the
background without a user interface. They perform required processing and handle events
silently without user interaction.
• <receiver> tags—Used for declaring broadcast receivers. Broadcast receivers are used to listen
and respond to broadcast announcements. Applications initiate broadcasts for the interested
applications when some event occurs that requires attention; for example, essential information

9
or confirmation is required from the user before taking some destructive action. An application
can have any number of broadcast receivers. A broadcast receiver responds by taking a specific
action.
• <provider> tags—Used for declaring content providers. Content providers provide content, that
is, data to applications. They help in handling, storing, and sharing data such as audio, images,
video, and contact lists other applications. Android ships with a number of content providers that
the applications can use to access and share data with other applications.
• <uses-permission> tags—Used for declaring the permissions that the application needs

Creating the User Interface


There are three approaches to creating user interfaces in Android.
1. You can create user interfaces entirely in Java code
2. Entirely in XML
3. Combining both methods (defining the user interface in XML and then referring and
modifying it through Java code).
The third approach, the combined approach, is highly preferred.
The graphical user interface for an Android app is built using a hierarchy of View and
ViewGroup objects.
 A View is an interactive UI component (or widget or control), such as button and text field. It
controls a rectangular area on the screen. It is responsible for drawing itself and handling events
(such as clicking, entering texts). Android provides many ready-to-use Views such as TextView,
EditText, Button, RadioButton, etc, in package android.widget. You can also create your custom
View by extending android.view.View.
 A ViewGroup is an invisible container used to layout the View components. Android provides
many ready-to-use ViewGroups such as LinearLayout, RelativeLayout, TableLayout and
GridLayout in package android.widget. You can also create your custom ViewGroup by
extending from android.view.ViewGroup.
Views and ViewGroups are organized in a single tree structure called view-tree. You can create a
view-tree either using programming codes or describing it in a XML layout file

Commonly used Layouts and Controls


The views or the controls that we want to display in an application are arranged in an order or

10
sequence by placing them in the desired layout. The layouts also known as Containers or
ViewGroups. Theseare used for organizing the views or controls in the required format. Android
provides the following layouts
• LinearLayout: In this layout, all elements are arranged in a descending column from top to
bottom or left to right. Each element contains properties to specify how much of the screen space
it will consume. Depending on the orientation parameter, elements are either arranged in row or
column format.
• RelativeLayout:In this layout, each child element is laid out in relation to other child elements.
That is, a child element appears in relation to the previous child. Also, the elements are laid out
in relation to the parent.
• AbsoluteLayout: In this layout, each child is given a specific location within the bounds of the
parent layout object. This layout is not suitable for devices with different screen sizes and hence
is deprecated.
• FrameLayout: This is a layout used to display a single view. Views added to this are always
placed at the top left of the layout. Any other view that is added to the FrameLayout overlaps the
previous view; that is, each view stacks on top of the previous one.
• TableLayout: In this layout, the screen is assumed to be divided in table rows, and each of the
child elements is arranged in a specific row and column.
• GridLayout: n this layout, child views are arranged in a grid format, that is, in the rows and
columns pattern.
The views can be placed at the specified row and column location. Also, more than one view can
be placed at the given row and column position.
The following list highlights some of the controls commonly used in Android applications:
• TextView:A read-only text label. It supports multiline display, string formatting, and automatic
wordwrapping.
• EditText: An editable text box that also accepts multiline entry and word-wrapping.
• ListView: A ViewGroup that creates and manages a vertical list of views, displaying them as
rows within the list
Event Handling
The action of clicking a Button, pressing the Enter key, or performing any action on any control
is considered an event. The reaction to the event, that is, the action to be taken when the event
occurs, is called event handling. To handle an event, you use the listeners that wait for an event
occurrence. When an event occurs, the listeners detect it and direct the program to the
appropriate routine.
An event listener is an interface in the View class that contains a single callback method, called
an event . For example the callback method onClick() is called when the user clicks on a button.
11
For event handling, the event listener is either implemented in the Activity class or is defined as
an anonymous class.
Thereafter, an instance of the implementation is passed to the respective control through the
setOnClickListener() method.
Note: Click is just one type of an event.
There are three ways of event handling:
• Creating an anonymous inner class
• Implementing the OnClickListener interface
• Declaring the event handler in the XML definition of the control
• Actions are performed when there is an event (e.g. the app is launched, a button is clicked, a
check box is checked)
• You will implement specific functions or event handlers and attach these to UI elements
• An example:
button.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
Toast.maketext(getApplicationContext(), “Hello!”, Toast.LENGTH_SHORT).show();
}
});

12

You might also like