Mobile Application & Development Unit-2
Mobile Application & Development Unit-2
Design Essentials
Unit-II
---------------------------------------------------------------------------------------------------------------
There are some necessary building blocks that an Android application consists of.
These loosely coupled components are bound by the application manifest file which contains
the description of each component and how they interact. The manifest file also contains the
app’s metadata, its hardware configuration, and platform requirements, external libraries,
and required permissions. There are the following main components of an android app
1. Activities
Activities are said to be the presentation layer of our applications. The UI of our
application is built around one or more extensions of the Activity class. By using Fragments
and Views, activities set the layout and display the output and also respond to the user’s
actions. An activity is implemented as a subclass of class Activity. An activity is usually a single
screen in your application. Each activity is implemented as a single class that extends the
Activity base class. Your class will display a user interface composed of Views and respond to
events. Most applications consist of multiple screens.
Syntax : public class MainActivity extends Activity {
}
2. Services
Services are like invisible workers of our app. These components run at the backend,
updating your data sources and Activities, triggering Notification, and also broadcast Intents.
They also perform some tasks when applications are not active. A service can be used as a
subclass of class Service.
A Service is code that is long-lived and runs without a UI. A good example of this is a
media player playing songs from a play list. In a media player application, there would probably
be one or more activities that allow the user to choose songs and start playing them.
3. Content Providers
It is used to manage and persist the application data also typically interacts with the
SQL database. They are also responsible for sharing the data beyond the application
boundaries. The Content Providers of a particular application can be configured to allow
access from other applications, and the Content Providers exposed by other applications can
also be configured. A content provider should be a sub-class of the class ContentProvider.
}
4. Intents
It is a powerful inter-application message-passing framework. They are extensively
used throughout Android. Intents can be used to start and stop Activities and Services, to
broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or
to request action be performed on a particular piece of data. Android uses a special class called
Intent to move from screen to screen. Intent describe what an application wants done. The two
most important parts of the intent data structure are the action and the data to act upon. Typical
values for action are MAIN (the front door of the application), VIEW, PICK, EDIT, etc. The data
is expressed as a Uniform Resource Indicator (URI).
Intent Receiver :
You can use an IntentReceiver when you want code in your application to execute in
reaction to an external event, for example, when the phone rings, or when the data network is
available, or when it's midnight. Intent receivers do not display a UI, although they may display
Notifications to alert the user if something interesting has happened. Intent receivers are also
registered in AndroidManifest.xml, but you can also register them from code using
Context.registerReceiver().
5. Broadcast Receivers
They are known to be intent listeners as they enable your application to listen to the
Intents that satisfy the matching criteria specified by us. Broadcast Receivers make our
application react to any received Intent thereby making them perfect for creating event-
driven applications.
6. Notifications
Notifications are the application alerts that are used to draw the user’s attention to
some particular app event without stealing focus or interrupting the current activity of the
user. They are generally used to grab user’s attention when the application is not visible or
active, particularly from within a Service or Broadcast Receiver. Examples: E-mail popups,
Messenger popups, etc.
Android terminologies :
1. XML
In Android, XML is used for designing the application’s UI like creating layouts, views,
buttons, text fields etc. and also used in parsing data feeds from the internet.
2. View
A view is an UI which occupies rectangular area on the screen to draw and handle user
events.
3. Layout
Layout is the parent of view. It arranges all the views in a proper manner on the screen.
4. Activity
An activity can be referred as your device’s screen which you see. User can place UI
elements in any order in the created window of user’s choice.
5. Emulator
An emulator is an Android virtual device through which you can select the target
Android version or platform to run and test your developed application.
6. Manifest file
Manifest file acts as a metadata for every application. This file contains all the essential
information about the application like app icon, app name, launcher activity, and
required permissions etc.
7. Service
Service is an application component that can be used for long-running background
processes. It is not bounded with any activity as there is no UI. Any other application
component can start a service and this service will continue to run even when the user
switches from one application to another.
GFGC Boy’s College, Kolar 3 By: Divakar M.S
Mobile Application & Development Unit II- Android Application
Design Essentials
8. Intent
Intent is a messaging object which can be used to communicate between two or more
components like activities, services, broadcast receiver etc. Intent can also be used to
start an activity or service or to deliver a broadcast message.
9. Broadcast Receiver
Application Context :
CONTEXT: Android Applications are popular for a long time and it is evolving to a greater
level as users’ expectations are that they need to view the data that they want in an easier
smoother view. Hence, the android developers must know the important terminologies
before developing the app. In Android Programming we generally come across the
word Context.
The Overall view of the App hierarchy looks like the following:
It can be seen in the above image that in “Sample Application”, the nearest Context is
Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is
Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application
Context.The nearest Context to both is their Activity Context only.
1. Application Context:-
getApplicationContext():
It is used to return the Context which is linked to the Application which holds all
activities running inside it. When we call a method or a constructor, we often have to pass a
Context and often we use “this” to pass the activity Context or “getApplicationContext” to
pass the application Context. This method is generally used for the application level and can
be used to refer to all the activities.
For example, if we want to access a variable throughout the android app, one has to
use it via getApplicationContext().
Syntax:
// Activity 1
public class <your activity1> extends Activity {
........
........
private <yourapplicationname> globarVar;
........
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext();
// In this activity set name and email and can reuse in other activities
globalExampleVariable.setName("getApplicationContext example");
globalExampleVariable.setEmail("xxxxxx@gmail.com");
.......
}
// Activity 2
public class <your activity2> extends Activity {
........
........
private <yourapplicationname> globarVar;
.......
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext();
.......
}
So, whenever the variable scope is required throughout the application, we can get it
by means of getApplicationContext(). Following is a list of functionalities of Application
Context.
List of functionalities of Application Context:
Load Resource Values
Start a Service
Bind to a Service
Send a Broadcast
Register BroadcastReceiver
2. Activity Context:
It is the activity Context meaning each and every screen got an activity. For example,
EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only. It
is tied to the life cycle of activity. It is used for the current Context. The method of invoking
the Activity Context is getContext().
Some use cases of Activity Context are:
The user is creating an object whose lifecycle is attached to an activity.
Whenever inside an activity for UI related kind of operations like toast, dialogue, etc.,
getContext():
It returns the Context which is linked to the Activity from which it is called. This is useful
when we want to call the Context from only the current running activity.
An activity class is per definition a class in Android. Every application which has UI
must inherit it to create a window.
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. JAVA files and XML files make your activity complete.
Let’s start by declaring activity. First, open your manifest file then add an element as a
child of the element.
Syntax:
Java file:
Activity Lifecycle: Activity is one of the building blocks of Android OS. In simple words Activity
is a screen that user interact with. Every Activity in android has lifecycle like created, started,
resumed, paused, stopped or destroyed. These different states are known as Activity Lifecycle.
In other words we can say Activity is a class pre-written in Java Programming.
Activity have different states or it’s known as Activity life cycle. All life cycle
methods aren’t required to override but it’s quite important to understand them.
Lifecycles methods can be overridden according to requirements.
Every activity gets stopped before destroy in case of when user press back navigation
button. So Activity will be in stopped state when hidden or replaced by other activities that
have been launched or switched by user. In this case application will not present anything
useful to the user directly as it’s going to stop.
Activity Restarted: onRestart():
Activity is called in restart state after stop state. So activity’s onRestart() function gets
called when user comes on screen or resume the activity which was stopped. In other
words, when Operating System starts the activity for the first time onRestart() never gets
called. It gets called only in case when activity is resumes after stopped state.
Activity Destroyed: onDestroy():
Any activity is known as in destroyed state when it’s not in background. There can
different cases at what time activity get destroyed.
First is if user pressed the back navigation button then activity will be destroyed after
completing the lifecycle of pause and stop.
After the Activity is destroyed if user again click the app icon, in this case activity will be
recreated and follow the same lifecycle again. Another use case is with Splash Screens if
there is call to finish() method from onCreate() of an activity then OS can directly call
onDestroy() with calling onPause() and onStop().
Android Service
The service runs in the background indefinitely even if application is destroyed. Moreover,
service can be bounded by a component to perform interactivity and inter process
communication (IPC).
Features of Service
The Android platform provides and runs predefined system services and every Android
application can use them, given the right permissions. These system services are usually
exposed via a specific Manager class. Access to them can be gained via
the getSystemService() method.
There can be two forms of a service.The lifecycle of service can follow two different paths:
started or bound.
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now
it runs in the background indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService()
method. The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.java. getApplicationContext() returns the context for your foreground
activity.
Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent
Explicit Intent:
Explicit Intent work internally within an application to perform navigation and data transfer.
The below given code snippet will help you understand the concept of Explicit Intents
Here SecondActivity is the JAVA class name where the activity will now be navigated.
Example with code in the end of this post will make it more clear.
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just specify
the Action which has to be performed and further this action is handled by the
component of another application.
The basic example of implicit Intent is to open any web page
Let’s take an example to understand Implicit Intents more clearly. We have to open a
website using intent in your application. See the code snippet given below
Unlike Explicit Intent you do not use any class name to pass through Intent(). In this
example we has just specified an action. Now when we will run this code then Android will
automatically start your web browser and it will open AbhiAndroid home page.
In Android:
Let’s implement Intent for a very basic use. In the below example we will Navigate from one
Activity to another and open a web homepage
The above statement will fire the defined system broadcast event whenever the boot process
is completed.
Sending Broadcasts
In android, we can send a broadcasts in apps using three different ways, those are
Method Description
If you observe above code snippet we create a custom Intent “sintent”. We need to
register our intent action in android manifest file like as shown below
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name=" com.tutlane.broadcast.MY_NOTIFICATION"/>
</intent-filter>
</receiver>
This is how we can create our own custom broadcasts using Intents in android applications.
System Brodcasting:
In android, several system events are defined as final static fields in the Intent class.
Following are the some of system events available in android applications.
Event Description
AndroidManifest.xml:
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 Receiver that make the application and using Intent Filters and Permissions,
determines how they co-ordinate with each other and other applications.
Java:
The Java folder contains the Java source code files. These files are used as a controller for
controlled UI (Layout file). It gets the data from the Layout file and after processing that data
output will be shown in the UI layout. It works on the backend of an Android application.
drawable:
A Drawable folder contains resource type file (something that can be drawn). Drawables
may take a variety of file like Bitmap (PNG, JPEG), Nine Patch, Vector (XML), Shape, Layers,
States, Levels, and Scale.
layout:
A layout defines the visual structure for a user interface, such as the UI for an Android
application. This folder stores Layout files that are written in XML language.
mipmap:
Mipmap folder contains the Image Asset file that can be used in Android Studio application.
You can generate the icon types like Launcher icons, Action bar and tab icons, and
Notification icons.
colors.xml:
colors.xml file contains color resources of the Android application. Different color values are
identified by a unique name that can be used in the Android application program.
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
</resources>
strings.xml:
The strings.xml file contains string resources of the Android application. The different string
value is identified by a unique name that can be used in the Android application program. This
file also stores string array by using XML language.
styles.xml:
The styles.xml file contains resources of the theme style in the Android application. This
file is written in XML language. Below is a sample styles.xml file:
<resources>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
</style>
</resources>
build.gradle(Module: app):
This defines the module-specific build configurations. Here you can add dependencies
what you need in your Android application.
Example of AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.broadcastreceiver">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<!--Here Name of Activity is .MainActivity, image of icon name stored in drawable folder, label
present inside string name is label-->
<!--If anything is different please customize the code according to your app-->
<activity android:name=".MainActivity">
<intent-filter android:icon="@drawable/icon"
android:label="@string/label">
android:icon="@drawable/icon"
Important Note: If you have not declared any icon for your activity then android sets the icon
of parent component by default. And if no icon is defined by parent component then icon is set
as the default icon by <application> element (declared in Manifest file).
2.android:label
A label represents the title of an activity on the toolbar. You can have different Labels for
different Activities as per your requirement or choice. The label should be set as a reference
to a string resource. However, you can also use a raw string to set a label as declared in the
below given code snippet
android:label = "@string/label"
or
android:label = "New Activity"
1. Action
2. Data
3. Category
Important Note: Every intent filter must contain action element in it. Data and category
element is optional for it.
1. Action:
It represent an activities action, what an activity is going to do. It is declared with the
name attribute as given below
An Intent Filter element must contain one or more action element. Action is a string that
specifies the action to perform. You can declare your own action as given below. But we usually
use action constants defined by Intent class.
<intent-filter>
<action android:name="com.example.android.intentfilters.Main2Activity"/>
</intent-filter>
There are few common actions for starting an activity like ACTION_VIEW
ACTION_VIEW: This is used in an Intent with startActivity(). This helps when you redirect to
see any website, photos in gallery app or an address to view in a map app.
For example: As we have done in previous topic of Intent, we started a website using implicit
intent in that Intent we used ACTION_VIEW element to view website in the web browser.
<data android:scheme="string"
android:host="string"
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
This specifies the format of data associated with an Intent which you use with
component. As explained in above code snippet, data passed through Intent is a type of URI.
Check the below given table for better clarification
3.Category:
This attribute of Intent filter dictates the behavior or nature of an Intent. There is a string
which contains some additional information about the intent which will be handled by a
component. The syntax of category is as follows:
BROWSABLE – Browsable category, activity allows itself to be opened with web browser to
open the reference link provided in data.
LAUNCHER – Launcher category puts an activity on the top of stack, whenever
application will start, the activity containing this category will be opened first.
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<!--Code here-->
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
Permissions:-
The purpose of a permission is to protect the privacy of an Android user. Android apps must
request permission to access sensitive user data (such as contacts and SMS), as well as certain
system features (such as camera and internet). Depending on the feature, the system might
grant the permission automatically or might prompt the user to approve the request.
Add permissions to the manifest
On all versions of Android, to declare that your app needs a permission, put a <uses-
permission> element in your app manifest, as a child of the top-level <manifest> element. For
example, an app that needs to access the internet would have this line in the manifest:
Example
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snazzyapp">
<uses-permission android:name="android.permission.INTERNET"/>
<!-- other permissions go here -->
<application ...>
...
</application>
</manifest>