Android Development Blocks
Android Development Blocks
Abdulrahman Ahmed
PhD IT(Currently), MSc. IT, MSc. CS & BSc. IT
CONTENT
1. Android Building Blocks
2. Android Emulators
3. Lab Session
1. Android Building Blocks
Android Building Blocks
An android component is simply a piece of code that has a
well defined life cycle e.g. Activity, Receiver, Service etc.
The core building blocks or fundamental components of
android are
1. Activities
2. Views
3. Intents
4. Services
5. Content Providers
6. Fragments
7. AndroidManifest.xml.
1. Activities
An activity is a class that represents a single screen.
It is like a Frame in AWT.
An activity in Android is a specific combination of XML
files and JAVA files.
It is basically a container that contains the design as well as
coding stuff.
XML files provide the design of the screen and JAVA files
deal with all coding stuff like handles, what is happening,
design files, etc.
1. Activities
Lifecycle of Activity
An activity goes
through a number of
states.
Activity lifecycle in
Android manages the
different states of
activity, such as when
the activity starts or
stops, etc.
All of these states are
managed by callback
methods.
1. Activities
Lifecycle of Activity
There are seven callback methods:-
1. onCreate():- This callback method must be created by you,
this is fired when your activity is created by the system. For
example, when you open the app it will call onCreate(),
onStart(), and onResume() methods. These three methods are
initiated when you open an app.
2. onStart():- There should always be an onStart() callback
after onCreate() finishes. In the started state users will be able
to see the activity but they are not ready for user interaction.
3. onResume():- In this, activities will be in the foreground
and ready for user interaction. You can understand the use of
this callback from this example: “when the user presses the
phone’s answer button it will give onPause() after you end up
calling it will again give onResume()”.
1. Activities
Lifecycle of Activity
There are seven callback methods:-
4. onPause():- This callback occurs when there is a case of
another activity starting in front of the current activity. It is
the opposite of onResume(). An example for this callback can
be “when you open the app, that is another app from the
notification bar, or open settings then it will call onPause()
and onStop()”.
5. onStop():- It is the opposite of onStart(). In this case,
activity will no longer be visible to the users.
6. onRestart():- This occurs when the activity is stopped and
before the activity starts again. It is a less common callback.
7. onDestroy():- It is opposite of onCreate(). This starts
when the system needs to free memory or when finish() is
called. It is used for cleanup which is a very common activity.
2. Views
A View is a simple building block of a user interface. It is a
small rectangular box that can be TextView, EditText, or even
a button.
A view is the UI element such as button, label, text field etc.
It occupies the area on the screen in a rectangular area and is
responsible for drawing and event handling.
View is a superclass of all the graphical user interface
components.
View is the basic building block of UI(User Interface) in
android. View refers to the android.view.
View class, which is the super class for all the GUI
components like TextView, ImageView, Button etc.
View class extends Object class and implements
Drawable.Callback, KeyEvent.Callback and
AccessibilityEventSource.
2. Views
Types of Android Views
Another thing that might now
come to your mind must be,
“what are the available types
of view in Android that we
can use?”
For that, we’ll see all these
types one by one as follows:
1. TextView
2. EditText
3. Button
4. Image Button
5. Date Picker
6. RadioButton
7. CheckBox buttons
8. Image View
3. Intents
Intent is used to invoke components.
It is mainly used to:
1. Start the service
2. Launch an activity
3. Display a web page
4. Display a list of contacts
5. Broadcast a message
6. Dial a phone call etc.
For example, you may write the following code to view the
webpage.
3. Intents
Android application components can connect to other
Android applications.
This connection is based on a task description represented
by an Intent object.
Intents are asynchronous messages which allow application
components to request functionality from other Android
components.
Intents allow you to interact with components from the
same applications as well as with components contributed
by other applications.
For example, an activity can start an external activity for
taking a picture.
Intents are objects of the android.content.Intent type.
3. Intents
Your code can send them to the Android system defining
the components you are targeting.
For example, via the startActivity() method you can define
that the intent should be used to start an activity.
An intent can contain data via a Bundle.
This data can be used by the receiving component.
In Android the reuse of other application components is a
concept known as task.
An application can access other Android components to
achieve a task.
For example, from a component of your application you can
trigger another component in the Android system, which
manages photos, even if this component is not part of your
application.
3. Intents
In this component you select a photo and return to your
application to use the selected photo.
Such a flow of events is depicted in the following graphic.
4. Service
Services in Android are a special component that facilitates
an application to run in the background in order to
perform long-running operation tasks.
The prime aim of a service is to ensure that the application
remains active in the background so that the user can
operate multiple applications at the same time.
A user-interface is not desirable for android services as it is
designed to operate long-running processes without any
user intervention.
Service is a background process that can run for a long
time.
There are two types of services local and remote.
Local service is accessed from within the application
Whereas remote service is accessed remotely from other
applications running on the same device.
4. Service
Types of Android Services
4. Service
1. Foreground Services:
Services that notify the user about its ongoing operations
are termed as Foreground Services.
Users can interact with the service by the notifications
provided about the ongoing task.
Such as in downloading a file, the user can keep track of
the progress in downloading and can also pause and
resume the process.
2. Background Services:
Background services do not require any user intervention.
These services do not notify the user about ongoing
background tasks and users also cannot access them.
The process like schedule syncing of data or storing of data
fall under this service.
4. Service
3. Bound Services:
This type of android service allows the components of the
application like activity to bound themselves with it.
Bound services perform their task as long as any
application component is bound to it.
More than one component is allowed to bind themselves
with a service at a time.
In order to bind an application component with a service
bindService() method is used.
4. Service
The Life Cycle of Android Services
In android, services have 2 possible paths to complete its
life cycle namely Started and Bounded.
1. Started Service (Unbounded Service):
By following this path, a service will initiate when an
application component calls the startService() method.
Once initiated, the service can run continuously in the
background even if the component is destroyed which was
responsible for the start of the service.
Two option are available to stop the execution of service:
By calling stopService() method,
The service can stop itself by using stopSelf() method.
4. Service
The Life Cycle of Android Services
2. Bounded Service:
It can be treated as a server in a client-server interface. By
following this path, android application components can
send requests to the service and can fetch results.
A service is termed as bounded when an application
component binds itself with a service by calling
bindService() method.
To stop the execution of this service, all the components
must unbind themselves from the service by using
unbindService() method.
5. Content Providers
A content provider manages access to a central repository
of data.
A provider is part of an Android application, which often
provides its own UI for working with the data.
However, content providers are primarily used by other
applications, which access the provider using a provider
client object.
Together, providers and provider clients offer a consistent,
standard interface to data that also handles inter-process
communication and secure data access.
Content Providers are used to share data between the
applications.
5. Content Providers
A content provider presents data to external applications as
one or more tables that are similar to the tables found in a
relational database.
A row represents an instance of some type of data the
provider collects, and each column in the row represents an
individual piece of data collected for an instance.
A content provider coordinates access to the data storage
layer in your application for a number of different APIs and
components.
As illustrated in figure below, these include the following:
Sharing access to your application data with other applications
Sending data to a widget
Returning custom search suggestions for your application
through the search framework using
SearchRecentSuggestionsProvider
5. Content Providers
As illustrated in figure below, these include the following:
Synchronizing application data with your server using an
implementation of AbstractThreadedSyncAdapter
Loading data in your UI using a CursorLoader
6. Fragments
A Fragment represents a reusable portion of your app's UI.
A fragment defines and manages its own layout, has its
own lifecycle, and can handle its own input events.
Fragments can't live on their own.
They must be hosted by an activity or another fragment.
The fragment’s view hierarchy becomes part of, or attaches
to, the host’s view hierarchy.
Fragments are like parts of activity.
An activity can display one or more fragments on the
screen at the same time.
You create fragments by extending Fragment class and You
can insert a fragment into your activity layout by declaring
the fragment in the activity's layout file, as a <fragment>
element.
6. Fragments
Fragment Lifecycle In Android
In Android, Fragments have their own life cycle very similar
to an Activity but it has extra events that are particular to
the Fragment’s view hierarchy, state and attachment to its
activity.
6. Fragments
Fragment Lifecycle In Android
1. onAttach(): The fragment instance is associated with an
activity instance.This method is called first, even before
onCreate() method. This method let us know that our
Fragment has been attached to an activity.
2. onCreate(): This will be called when creating the
fragment. It means when a new fragment instance initializes,
which always happens after it attaches to the host.
3. onCreateView(): The will be called when it’s time for the
fragment to draw its UI(user interface) for the first time. To
draw a UI for our fragment we must return a View component
from this method that is the root of our fragment’s layout. We
can also return null if the fragment does not provide a UI.
6. Fragments
Fragment Lifecycle In Android
4. onViewCreated(): This will be called after onCreateView()
method. This method is particularly useful when inheriting
the onCreateView() method implementation but we need to
configure the resulting views such as with a ListFragment and
when to set up an adapter.
5. onActivityCreated(): This method is called after the
onCreateView() method when the host activity is created.
This method indicates that the activity’s onCreate() has
completed.
6. onStart(): This method is called once the fragment gets
visible.
7. onResume(): This method is called when the Fragment is
visible and intractable.
6. Fragments
Fragment Lifecycle In Android
8. onPause(): This method is the first indication that the
user is leaving the current fragment or fragment is no longer
interactable. It occurs when any Fragment Transition
processed or Fragment is removed.
9. onStop(): This method is called after onPause()
method.Fragment going to be stopped by calling onStop().
This method calls when the Fragment is no longer visible. it
occurs either after the fragment is about to be removed or
Fragment Transition is processed(replace Fragment) or when
the host activity stops
10. onDestroyView(): This method is called when the view
and other related resources created in onCreateView()
method is removed from the activity’s view hierarchy and
destroyed.
6. Fragments
Fragment Lifecycle In Android
11. onDestroy(): This method is called to do final clean
up of the Fragment’s state but Not guaranteed to be
called by the Android platform. This method called after
onDestroyView() method.
12. onDetach(): This method called after onDestroy()
method to notify that the fragment has been disassociated
from its hosting activity means Fragment is detached from its
host Activity.
7. AndroidManifest.xml
Every app project must have an AndroidManifest.xml file,
with precisely that name, at the root of the project source
set.
The manifest file describes essential information about
your app to the Android build tools, the Android operating
system, and Google Play.
It contains information about activities, content providers,
permissions etc.
It is like the web.xml file in Java EE.
7. AndroidManifest.xml
Every project in Android includes a Manifest XML file,
which is AndroidManifest.xml, located in the root directory
of its project hierarchy.
The manifest file is an important part of our app because it
defines the structure and metadata of our application, its
components, and its requirements.
This file includes nodes for each of the Activities, Services,
Content Providers, and Broadcast Receivers that make the
application, and using Intent Filters and Permissions
determines how they coordinate with each other and other
applications.
7. AndroidManifest.xml
The manifest file also specifies the application metadata,
which includes its icon, version number, themes, etc., and
additional top-level nodes can specify any required
permissions, and unit tests, and define hardware, screen, or
platform requirements. The manifest comprises a root
manifest tag with a package attribute set to the project’s
package.
It should also include an xmls:android attribute that will
supply several system attributes used within the file.
We use the versionCode attribute is used to define the
current application version in the form of an integer that
increments itself with the iteration of the version due to
update.
Also, the versionName attribute is used to specify a public
version that will be displayed to the users.
2. Android Emulators
Android Emulator
The Android emulator is an Android Virtual Device (AVD),
which represents a specific Android device.
We can use the Android emulator as a target device to
execute and test our Android application on our PC.
The Android emulator provides almost all the functionality
of a real device.
We can get the incoming phone calls and text messages.
It also gives the location of the device and simulates
different network speeds.
Android emulator simulates rotation and other hardware
sensors.
It accesses the Google Play store, and much more
Android Emulator
Testing Android applications on
emulator are sometimes faster
and easier than doing on a real
device.
For example, we can transfer data
faster to the emulator than to a
real device connected through
USB.
The Android emulator comes
with predefined configurations
for several Android phones, Wear
OS, tablet, Android TV devices.
Android Emulator
Requirement and recommendations.
The Android emulator takes additional requirements
beyond the basic system requirement for Android Studio.
These requirements are given below:
1. SDK Tools 26.1.1 or higher
2. 64-bit processor
3. Windows: CPU with UG (unrestricted guest) support
4. HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)
Android Emulator
Install the emulator
The Android emulator is installed while installing the
Android Studio.
However some components of emulator may or may not be
installed while installing Android Studio.
To install the emulator component, select the Android
Emulator component in the SDK Tools tab of the SDK
Manager.
Android Emulator
Run an Android app on the Emulator
We can run an Android app form the Android Studio
project, or we can run an app which is installed on the
Android Emulator as we run any app on a device.
To start the Android Emulator and run an application in
our project:
1. In Android Studio, we need to create an Android Virtual
Device (AVD) that the emulator can use to install and run
your app. To create a new AVD:-
1.1 Open the AVD Manager by clicking Tools > AVD
Manager.
Android Emulator
Run an Android app on the Emulator….
1.1 Open the AVD Manager by clicking Tools > AVD
Manager.
Android Emulator
Run an Android app on the Emulator….
1.2 Click on Create Virtual Device, at the bottom of the
AVD Manager dialog.
Then Select Hardware page appears.
Android Emulator
Run an Android app on the Emulator….
1.3 Select a hardware profile and then click Next.
If we don't see the hardware profile we want, then we can
create or import a hardware profile.
The System Image page appears.
Android Emulator
Run an Android app on the Emulator….
1.4 Select the system image for the particular API level and
click Next.
This leads to open a Verify Configuration page.
Android Emulator
Run an Android app on the Emulator….
1.5 Change AVD properties if needed, and then click Finish.
2. In the toolbar, choose the AVD, which we want to run our
app from the target device from the drop-down menu.
3. Click Run
Android Emulator
Launch the Emulator without first running an app
To start the emulator:
Open the AVD Manager.
Double-click an AVD, or click Run
While the emulator is running, we can run the Android Studio
project and select the emulator as the target device.
We can also drag an APKs file to install on an emulator, and
then run them.
Run and stop an emulator, and clear data
From the Virtual Device page, we can perform the following
operation on emulator:
Android Emulator
Run and stop an emulator, and clear data
To run an Android emulator that uses an AVD, double-click
the AVD, or click Launch
To stop the running emulator, right-click and select Stop, or
click Menu ▼ and select Stop.
If we want to clear the data from an emulator and return it to
the initial state when it was first defined, then right-click an
AVD and select Wipe Data. Or click menu ▼ and
select Wipe Data.
3. Lab Session
Exercise 1
Exercise 1
Android Hide Title Bar and Full Screen Example
In this example, we are going to explain how to hide the
title bar and how to display content in full screen mode.
The requestWindowFeature(Window.FEATURE_NO_T
ITLE) method of Activity must be called to hide the title.
But, it must be coded before the setContentView method.
Code that hides title bar of activity
The getSupportActionBar() method is used to retrieve
the instance of ActionBar class.
Calling the hide() method of ActionBar class hides the title
bar.
Exercise 1
Android Hide Title Bar and Full Screen Example
Code that enables full screen mode of activity
The setFlags() method of Window class is used to display
content in full screen mode.
You need to pass
the WindowManager.LayoutParams.FLAG_FULLSCREEN
constant in the setFlags method.
Exercise 1
Android Hide Title Bar and Full Screen Example
The full code to hide the title bar in android.
1. Activity_main.xml
Exercise 1
Android Hide Title Bar and Full Screen Example
The full code to hide the title bar in android.
2. Activity class
Exercise 1
Android Hide Title Bar and Full Screen Example
The full code to hide the title bar in android.
3. Output
Exercise 2
Exercise 2
Android Screen Orientation Example
The screenOrientation is the attribute of activity element.
The orientation of android activity can be portrait, landscape, sensor,
unspecified etc.
You need to define it in the AndroidManifest.xml file.
Exercise 2
Android Screen Orientation Example
The common values for screenOrientation attribute are as follows:
Exercise 2
Android Screen Orientation
Example
Android Portrait and Landscape mode
screen orientation example
In this example, we will create two
activities of different screen
orientation.
The first activity (MainActivity) will be
as "portrait" orientation and second
activity (SecondActivity) as "landscape"
orientation type.
1. Activity_main.xml
Exercise 2
Android Screen Orientation Example
2. Activity class
Exercise 2
Android Screen Orientation Example
3. Activity_second.xml
Exercise 2
Android Screen Orientation Example
4. SecondActivity class
Exercise 2
Android Screen Orientation Example
5. AndroidManifest.xml
In AndroidManifest.xml file add the
screenOrientation attribute in
activity and provides its orientation.
In this example, we provide
"portrait" orientation for
MainActivity and "landscape" for
SecondActivity.
Exercise 2
Android Screen Orientation Example
6. Output
Next Session
Android Apps Coding – Part 1
Analog & Digital Clock App Coding
Date Picker App Coding
The End
Any Questions?