You are on page 1of 18

UNIT – II

BUILDING BLOCKS OF ANDROID:


Android building blocks
Android building blocks are the pieces of an application that Android offers to put
together into an Android app. Android building blocks make it easy to break the application into
conceptual units so that the user can work on them independently and put them into complete
package
Android application:
Application is a collection of
1. Activities
2. Services
3. Providers
4. Receivers
1. ACTIVITIES:
Activity is a single screen that the user sees on the device at any one time. Activities can
be flipped back and forth. Simultaneously more than one activity can be run on Android device
ACTIVITY LIFE CYCLE:
To avoid launch an activity repeatedly, an activity life cycle is managed by the Activity
Manager. This is a service that runs inside the Android Framework layer of the stack. Activity
manager is responsible for creating and managing and destroying activities.
The following diagram shows the life cycle of the activities.
Activity state diagram
An Activity will undergo the following states:
• Starting state
• Running
• Paused
• Stopped
• Destroyed
Starting State
• When an activity doesn’t exist in memory, it is in a starting state. As it starts, the activity
invokes a set of callback methods namely,
• OnCreate()
• OnStart()
• OnResume
From Starting state the activities will come to the running state, where the full screen will be
displayed.
Running state
Only one activity will be in this state always and interacting with the user. Touching the
buttons, dragging etc. will be carried out by this activity only this activity has the priority in
terms of getting memory and resources it needs to run quickly.
Paused State
No interaction with the user, is called paused state of the activity
Eg: Dialog boxes come in front of an activity.
Paused activities have high priority over memory since they are visible in the screen. The
activity manager calls OnPause () method while put an activity in this state.
Stopped State
When an activity is not visible, but still in memory, it can be said that the activity is in
stopped state. A sopped activity could be brought back to the front to become a running activity
again. It will be destroyed and removed from memory. This is done by the operating system.
Restarting an activity from stopped state is easier than starting from the beginning, therefore the
system keeps the activities in this state for some time. Because, stopped activities can be
removed from memory at any point. For this purpose, the activity Manager calls onStop() when
putting an application in this state
Destroyed state
A destroyed activity is no longer in memory. The Activity Manager decided that this activity
is no longer needed and has removed it. Before the activity is destroyed, it can perform certain
actions, such as save any unsaved information. The activity managers calls the method
OnDestroy() for this state

2. INTENDS

Intents are messages that are sent among the major building blocks. Otherwise, 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. They trigger to
 START AN ACTIVITY
 TO START A SERVICE
 TO STOP A SERVICE
 AND TO BIND A SERVICE
 AND BROADCASTS
 AND START AN ACTIVITY FROM ANOTHER ACTIVITY
 DISPLAY A WEB PAGE
 DISPLAY A LIST OF CONTACTS
 DIAL A PHONE CALL
Example code to start an activity via intend:
Intent i = new Intent(this, ActivityTwo.class);
startActivity(i)

Types of Indents:
There are two types of indents available for communication purpose.
1. Explicit – Specifically tells about the receiver component
2. Implicit – Only the type of receiver will be specified
Implicit Intent:
In an implicit intent, the sender specifies just the type of receiver. Implicit Intent doesn't specify
the component directly. In implicit indent the activity name will not be specified. In such case,
this implicit intent provides information of available components that are to be invoked provided
by the system. Implicit intents specify the action which should be performed and optionally data
which provides content for the action.
If an implicit intent is sent to the Android system, it searches for all components which
are registered for the specific action and the fitting data type. If only one component is found,
Android starts this component directly. If several components are identified by the Android
system, the user will get a selection dialog and can decide which component should be used for
the intent.
public void onClick(View arg0) {  
                 String url=editText1.getText().toString();  
                 Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));  
startActivity(intent);  
}  
Explicit Intent:
In an explicit intent, the sender clearly spells out which specific component should be on
the receiving end.
Explicit intents explicitly define the component which should be called by the Android
system, by using the Java class as identifier. Explicit intents are typically used within an
application as the classes in an application are controlled by the application developer. The
following code shows how to create an explicit intent and send it to the Android system to start
an activity.
Intent i = new Intent(Mainactivity.this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
Indents allow to replace the app with a custom one. For example, default browsers in a
device can be replaced with custom one. Like a web link, an intent can be internal to a single
app or, just as easily, connect to components in other apps. They can carry small amounts of
primitive data with them
The communication indents for activities are shown here
3. SERVICES:
Services are the one that run in the background and don’t have any user interface
components. They can perform the same actions as activities, but without any user interface.
The service runs in the background indefinitely even if application is destroyed. Services are
useful for actions that the user want to perform for a while without worrying about the contents
on the screen. Services are used for repetitive and potentially long running operations.
Example: 1. Music player playing the music. 2. Applications that are being downloaded
while the user uses some other application.
Services Life Cycle:
Like Activity, services are also have their own life cycle. But not like activity they have
all the states. Some of the states of the activities are not undergone by service.
The states of the services are as follows. 1. Start 2. Running 3. Destroyed.
The services life cycle diagram is depicted below.

Life cycle of a service


The user can start a service or stop a service. Service life cycle is controlled by the developer
and not by the system. Services have simple life cycle when compared with activities. While a
service is running the developer has to think about the CPU utilization and the power resource.
The sample code to start a service and to stop the service:
An Android component (service, receiver, activity) can trigger the execution of a service
via the startService(intent) method.
Intent i= new Intent(context, MyService.class);
context.startService(i);

Similarly, to stop a service, the following code should be used. stopService() or stopself()
method.

Methods used in the service:

OnStartCommand(), OnCreate(), OnDestroy(), OnBind()

OnCreate():

The system invokes this method to perform one-time setup procedures when the service
is initially created before it calls either onStartCommand() or onBind(). If the service is already
running, this method is not called.
OnStartCommand():
The system invokes this method by calling startService() when another component
such as an activity requests that the service be started. When this method executes, the service is
started and can run in the background indefinitely. When the service is started it should be
stopped after some time by calling either by calling stopSelf() or stopService() method.
OnDestroy();
The system invokes this method when the service is no longer used and is being
destroyed. The service should implement this to clean up any resources such as threads,
registered listeners, or receivers. This is the last call that the service receives.
OnBind();
The system invokes this method by calling bindService() when another component
wants to bind with the service. While implementing this method, an interface must be provided
that clients use to communicate with the service by returning an IBinder.
Sample Code: (MainActivity.java)
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
case R.id.buttonNext:
Intent intent=new Intent(this,NextPage.class);
startActivity(intent);
break;
}

Myservice.class

public class MyService extends Service {


MediaPlayer myPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.sun);
myPlayer.setLooping(false); // Set looping
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}

4. CONTENT PROVIDERS:
Content providers are interfaces for sharing data between applications. 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. Content providers can
help an application manage access to data stored by itself, stored by other apps, and provide a
way to share data with other apps. They encapsulate the data, and provide mechanisms for
defining data security. Content providers are the standard interface that connects data in one
process with code running in another process. Implementing a content provider has many
advantages. Most importantly you can configure a content provider to allow other applications to
securely access and modify the app data. Content provider
Overview diagram of how content providers manage access to storage.

Content provider are much better suited for sharing persistent data between possibly large
datasets. The methods that content providers use to implement the four critical operations are:
1. Create - insert() 4. Delete - delete()
2. Read - query()
3. Update - update()
Advantages of Content Provider:
5. BROADCAST RECEIVERS:
Broadcast Receiver is defined as a system built publish or subscription mechanism. This
is a code that gets activated by the occurrence of an event.
Example. 1. An incoming call event 2. An Incoming SMS alert 3. Low Battery alert
These events will be broadcasted and the receivers will receive them. They do not have any
visual representation. They will not run in memory actively. But when triggered, they initiate
to execute some code. Example: Starting an activity, starting a service, etc.

6. APPLICATION CONTEXT:

Application context are the containers that hold the building blocks that are in Android.
Container does not do anything but the activities, services, providers and receivers do the work
along with the filesystems, VM etc., Application context refers to the application environment
and the process within which all its components are running. It allows applications to share the
data and resources between various building blocks. It has its own Linux user ID and its own.
Linux process, with a dedicated Dalvik virtual machine, a dedicated filesystem for storing
application files, and so on.

The Block diagram of the container (Application Context) is shown below.

Application Context

The application context is uniquely identified on a device based on the package name of that
application. An application context gets created whenever the first component of this application
starts up. The application context lives as long as your application is alive. The application
context lives as long as your application is alive.

ANDROID USER INTERFACE:

User Interface is defined as the screens or the medium that provides the facility to access
the application by means of touching, dragging and clicking etc.

There are two ways to create an android user interface screen.

1. Declarative User Interface 2. Programmatic User Interface

In declarative user interface buttons and other components can be created using XML code.
In Programmatic user interface creation, declaration of buttons, declaration of text boxes, text
view controls can be created using java code. These can be posted into a container.
Declarative User Interface

1. This is like HTML where the user interface can be created using XML Code. Built in
tags are available in android to facilitate the creation of the user interface using XML.
All the controls have their own properties such as height, width, margin, text etc are
readily available to design the interface.

2. Provides WYSIWYG

The declarative interface is based on WYSIWYG means What You See Is What
You Get. The user interface which is created in the layout will be running in the
emulator as it is. The screen color, the height, width and match parent properties will be
adopted according to the device screen accurately. That is, the layout design will be
shown on the device as it is created using XML code. Some of the tools come with ADT
and some with third parties

Example: (Sample Code)

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical" >
    <EditText android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text=“Name”
<EditText android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text=“Mobile No.”
/>
</LinearLayout>

Output:
Disadvantages of DUI:

1. Memory space will be occupied at design time itself.

2. No proper way to handle the user input.

Programmatic User Interface:

Why PUI?

XML is unable to provide a good method to handle the user input in a proper way.
Therefore, PUI has been introduced. In this interface creation, the user has to write the java code
in the Mainactivity. Java file to create the screen. All the layouts properties, components
properties such as height, width, color, text must be given using the corresponding methods.
This approach is involving writing java code to develop UI. Buttons can be created, in
declarative approach also, but the only difference in PUI, java informs the user that what
happens when button is clicked. But in this method, the user can see the design of the screen
only when the device / emulator runs. Any changes while designing cannot be done in this
approach. Memory space will be occupied only at run time.
Example:

Output:

Which interface is the best?

Both are best.

For static declaration use declarative approach.

To specify the action of the components use programmatic approach

LAYOUTS AND VIEWS:


A Layout is defined as the screen which contains the components. A layout may have children.
Here children means the components that are on the layout and other layouts that are in the main
layout

The block diagram of a layout and the connectivity is shown below

Layout

Types of Layouts:

Different types of layouts are available to create a screen. They are,


Linear Layout – The components are arranged in a vertical order or in a horizontal manner.

Linear Layout
Table Layout:
The components are arranged in the form of a row and column like a table on the screen
Frame Layout –
The components are arranged inside a Frame like arrangement is called Frame Layout.

Relative Layout:
The components are arranged in such a way that each component is relatively placed in a
position with the other component. If there is any change in one component, then there may be
changes in the position of the other component also.

Relative Layout diagram


Logging Messages In Android:
• Android offers a system-wide logging capability. The developer can log from
anywhere in the code by calling Log.d(TAG, message), where TAG and message are
some strings.
• TAG should be a tag that is meaningful to based on the code.
• A tag would be the name of the app, class, or some module.
• Good practice is to define TAG as a Java constant for entire class.
Eg: private static final String TAG = "StatusActivity";
1. The Android system uses a centralized system for all logs. The application programmer
can also write custom log messages.
2. The tooling to develop Android applications allows you to define filters for the log
statements based on the developer’s interest.
To write Log Statements, android.util.Log class is used along with Log.v(), Log.d(), Log.i(),
Log.w(), Log.e(), Log.wtf() are used and they are sorted based on their usage.
Different Levels of Log
.d is for debug level
.e is for error
.w is for warning
.i is for information
a.Wtf – what a terrible failure
LogCat
• The Android system log is outputted to LogCat, a standardized system-wide logging
mechanism.
• LogCat is readily available to all Java code. The developer can easily view the logs
and filter their output based on severity, such as debug, info, warning, or error, or
based on custom-defined tags.
Two ways to view logcat:
1. Via Eclipse
2. Window – Show view – Other – Android – LogCat
Threading in Android
• A thread is a sequence of instructions executed in order.
• The Android operating system is based on Linux, and as such, is fully capable of
running multiple threads at the same time.
Single Thread:
• By default, an Android application runs on a single thread. Single-threaded
applications run all commands serially, meaning that no command starts until the
previous one is done.
• It is otherwise called as blocking
UI THREAD
• This single thread is also known as the UI thread because it’s the thread that
processes all the user interface commands.
• The UI thread is responsible for
1. Drawing all the elements on the screen
2. processing all the user events, such as touches on the screen,
clicks of the button, and so on.
Diagrammatic representation of single UI thread

Killing the Application (Threads)


The Android system will offer to kill any application that is not responding within a
certain time period, typically around five seconds
for activities.
• This is known as the Application Not Responding dialog, or ANR

Multithreaded Execution
While multithreading in android, the main thread as running in the foreground and the
additional threads are running in the background.
They are running but equally.


There are several ways to accomplish multithreading. Java has a Thread class that
allows for many of these operations
• Java can be used to put the processes into foregraound or background based on the
user’s requirement
The drawback:
• in Android, a thread that didn’t create the UI widget is not allowed to update the
UI.
• For this purpose, threads should be synchronized.
• To synchronize android provides a utility class called AsyncTask has been designed
for this purpose
AsyncTask
• AsyncTask is an Android mechanism created to help handle long operations that
need to report to the UI thread.
The methods associated with this classes are,
• doInBackground(),
• onProgressUpdate(),
• and onPostExecute().
UNIT II COMPLETED

You might also like