Вы находитесь на странице: 1из 67

Introduction to Android

Android is a complete set of software for mobile devices such as


tablet computers, notebooks, smartphones, electronic book readers,
set-top boxes etc.

It contains a linux-based Operating System, middleware and key


mobile applications.

It can be thought of as a mobile operating system. But it is not limited


to mobile only. It is currently used in various devices such as mobiles,
tablets, televisions etc.

Android is a software package and linux based operating system for


mobile devices such as tablet computers and smartphones.

It is developed by Google and later the OHA (Open Handset Alliance).


Java language is mainly used to write the android code even though
other languages can be used.

The goal of android project is to create a successful real-world product


that improves the mobile experience for end users.

There are many code names of android such as Lollipop, Kitkat, Jelly
Bean, Ice cream Sandwich, Froyo, Ecliar, Donut etc

What is Open Handset Alliance (OHA)

It's a consortium of 84 companies such as google, samsung, AKM,


synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc.

It was established on 5th November, 2007, led by Google. It is


committed to advance open standards, provide services and deploy
handsets using the Android Plateform.

Features of Android

After learning what is android, let's see the features of android. The
important features of android are given below:
1) It is open-source.

2) Anyone can customize the Android Platform.

3) There are a lot of mobile applications that can be chosen by the


consumer.

4) It provides many interesting features like weather details, opening


screen, live RSS (Really Simple Syndication) feeds etc.

It provides support for messaging services(SMS and MMS), web


browser, storage (SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi
etc.), media, handset layout etc.

Categories of Android applications

There are many android applications in the market. The top categories
are:

o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.

Android Versions, Codename and API

android versions, codenames and API Level provided by Google.

Version Code name API Level

1.5 Cupcake 3
1.6 Donut 4

2.1 Eclair 7

2.2 Froyo 8

2.3 Gingerbread 9 and 10

3.1 and 3.3 Honeycomb 12 and 1

4.0 Ice Cream Sandwitch 15

4.1, 4.2 and 4.3 Jelly Bean 16, 17 a

4.4 KitKat 19

5.0 Lollipop 21

6.0 Marshmallow 23

7.0 Nougat 24-25

8.0 Oreo 26-27

Android Architecture

android architecture or Android software stack is categorized into five


parts:

1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications

Let's see the android architecture first.

1) Linux kernel

It is the heart of android architecture that exists at the root of android


architecture. Linux kernel is responsible for device drivers, power
management, memory management, device management and resource
access.

2) Native Libraries

On the top of linux kernel, their are Native libraries such as WebKit,


OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc.

The WebKit library is responsible for browser support, SQLite is for


database, FreeType for font support, Media for playing and recording
audio and video formats.

3) Android Runtime

In android runtime, there are core libraries and DVM (Dalvik Virtual
Machine) which is responsible to run android application. DVM is like
JVM but it is optimized for mobile devices. It consumes less memory
and provides fast performance.

4) Android Framework
On the top of Native libraries and android runtime, there is android
framework. Android framework includes Android API's such as UI (User
Interface), telephony, resources, locations, Content Providers (data)
and package managers. It provides a lot of classes and interfaces for
android application development.

5) Applications

On the top of android framework, there are applications. All


applications such as home, contact, settings, games, browsers are
using android framework that uses android runtime and libraries.
Android runtime and native libraries are using linux kernal.

Android Core Building Blocks or Components

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


activities, views, intents, services, content providers, fragments and
AndroidManifest.xml.

Activity

An activity is a class that represents a single screen. It is like a Frame


in AWT.

View

A view is the UI element such as button, label, text field etc. Anything
that you see is a view.
Intent

Intent is used to invoke components. It is mainly used to:

o Start the service


o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.

For example, you may write the following code to view the webpage.

1. Intent intent=new Intent(Intent.ACTION_VIEW);  
2. intent.setData(Uri.parse("http://www.google.com"));  
3. startActivity(intent);  
Service

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.

Content Provider

Content Providers are used to share data between the applications.

Fragment

Fragments are like parts of activity. An activity can display one or


more fragments on the screen at the same time.
AndroidManifest.xml

It contains informations about activities, content providers,


permissions etc. It is like the web.xml file in Java EE.

Android Virtual Device (AVD)

It is used to test the android application without the need for mobile or
tablet etc. It can be created in different configurations to emulate
different types of real devices.

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

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.

How to make android apps

In this page, you will know how to create the simple hello android
application. We are creating the simple example of android using the
Eclipse IDE. For creating the simple example:

1. Create the new android project


2. Write the message (optional)
3. Run the android application
Internal Details of Hello Android Example

Here, we are going to learn the internal details or working of hello


android example.

Android application contains different components such as java source


code, string resources, images, manifest file, apk file etc. Let's
understand the project structure of android application.

Java Source Code

Let's see the java source file created by the Eclipse IDE:

File: MainActivity.java

1. package com.example.helloandroid;  
2. import android.os.Bundle;  
3. import android.app.Activity;  
4. import android.view.Menu;  
5. import android.widget.TextView;  
6. public class MainActivity extends Activity {//(1)  
7.     @Override  
8.     protected void onCreate(Bundle savedInstanceState) {//(2)  
9.         super.onCreate(savedInstanceState);  
10.                 
11.         setContentView(R.layout.activity_main);//(3)  
12.     }  
13.     @Override  
14.     public boolean onCreateOptionsMenu(Menu menu) {//(4)  
15.         // Inflate the menu; this adds items to the action bar if it is pr
esent.  
16.         getMenuInflater().inflate(R.menu.activity_main, menu);  
17.         return true;  
18.     }  
19. }  
(1) Activity is a java class that creates and default window on the
screen where we can place different components such as Button,
EditText, TextView, Spinner etc. It is like the Frame of Java AWT.

It provides life cycle methods for activity such as onCreate, onStop,


OnResume etc.

(2) The onCreate method is called when Activity class is first created.

(3) The setContentView(R.layout.activity_main) gives information
about our layout resource. Here, our layout resources are defined in
activity_main.xml file.

File: activity_main.xml

1. <RelativeLayout xmlns:androclass="http://schemas.android.com/
apk/res/android"  
2.     xmlns:tools="http://schemas.android.com/tools"  
3.     android:layout_width="match_parent"  
4.     android:layout_height="match_parent"  
5.     tools:context=".MainActivity" >  
6.     <TextView  
7.         android:layout_width="wrap_content"  
8.         android:layout_height="wrap_content"  
9.         android:layout_centerHorizontal="true"  
10.         android:layout_centerVertical="true"  
11.         android:text="@string/hello_world" />  
12. </RelativeLayout>  

As you can see, a textview is created by the framework automatically.


But the message for this string is defined in the strings.xml file.
The @string/hello_world provides information about the textview
message. The value of the attribute hello_world is defined in the
strings.xml file.

File: strings.xml

1. <?xml version="1.0" encoding="utf-8"?>  
2. <resources>  
3.     <string name="app_name">helloandroid</string>  
4.     <string name="hello_world">Hello world!</string>  
5.     <string name="menu_settings">Settings</string>  
6. </resources>  

You can change the value of the hello_world attribute from this file.

Generated R.java file

It is the auto-generated file that contains IDs for all the resources of
res directory. It is generated by aapt(Android Asset Packaging Tool).
Whenever you create any component on activity_main, a
corresponding ID is created in the R.java file which can be used in the
Java Source file later.

File: R.java

APK File

An apk file is created by the framework automatically. If you want to


run the android application on the mobile, transfer and install it.

Resources

It contains resource files including activity_main, strings, styles etc.

Manifest file

It contains information about package including components such as


activities, services, content providers etc.

For more information about manifest file visit


here: AndroidManifest.xml file.
Dalvik Virtual Machine | DVM

As we know the modern JVM is high performance and provides


excellent memory management. But it needs to be optimized for low-
powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine


optimized for mobile devices. It optimizes the virtual machine
for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by


Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on
the Dalvik VM. Multiple class files are converted into one dex file.

Let's see the compiling and packaging process from the source file:

The javac tool compiles the java source file into the class file.

The dx tool takes all the class files of your application and generates a
single .dex file. It is a platform-specific tool.

The Android Assets Packaging Tool (aapt) handles the packaging


process.

AndroidManifest.xml file in android

The AndroidManifest.xml file contains information of your package,


including components of the application such as activities, services,
broadcast receivers, content providers etc.

It performs some other tasks also:

o It is responsible to protect the application to access any


protected parts by providing the permissions.
o It also declares the android api that the application is going to
use.
o It lists the instrumentation classes. The instrumentation classes
provides profiling and other informations. These informations are
removed just before the application is published etc.

This is the required xml file for all the android application and located
inside the root directory.

A simple AndroidManifest.xml file looks like this:

1. <manifest xmlns:android="http://schemas.android.com/apk/res/an
droid"  
2.     package="com.javatpoint.hello"  
3.     android:versionCode="1"  
4.     android:versionName="1.0" >  
5.   
6.     <uses-sdk  
7.         android:minSdkVersion="8"  
8.         android:targetSdkVersion="15" />  
9.   
10.     <application  
11.         android:icon="@drawable/ic_launcher"  
12.         android:label="@string/app_name"  
13.         android:theme="@style/AppTheme" >  
14.         <activity  
15.             android:name=".MainActivity"  
16.             android:label="@string/title_activity_main" >  
17.             <intent-filter>  
18.                 <action android:name="android.intent.action.MAIN" />  
19.   
20.                 <category android:name="android.intent.category.LAU
NCHER" />  
21.             </intent-filter>  
22.         </activity>  
23.     </application>  
24.   
25. </manifest>  
AndroidManifest.xml file in android

The AndroidManifest.xml file contains information of your package,


including components of the application such as activities, services,
broadcast receivers, content providers etc.

It performs some other tasks also:

o It is responsible to protect the application to access any


protected parts by providing the permissions.
o It also declares the android api that the application is going to
use.
o It lists the instrumentation classes. The instrumentation classes
provides profiling and other informations. These informations are
removed just before the application is published etc.

This is the required xml file for all the android application and located
inside the root directory.

A simple AndroidManifest.xml file looks like this:

1. <manifest xmlns:android="http://schemas.android.com/apk/res/an
droid"  
2.     package="com.javatpoint.hello"  
3.     android:versionCode="1"  
4.     android:versionName="1.0" >  
5.   
6.     <uses-sdk  
7.         android:minSdkVersion="8"  
8.         android:targetSdkVersion="15" />  
9.   
10.     <application  
11.         android:icon="@drawable/ic_launcher"  
12.         android:label="@string/app_name"  
13.         android:theme="@style/AppTheme" >  
14.         <activity  
15.             android:name=".MainActivity"  
16.             android:label="@string/title_activity_main" >  
17.             <intent-filter>  
18.                 <action android:name="android.intent.action.MAIN" />  
19.   
20.                 <category android:name="android.intent.category.LAU
NCHER" />  
21.             </intent-filter>  
22.         </activity>  
23.     </application>  
24.   
25. </manifest>  

Elements of the AndroidManifest.xml file

The elements used in the above xml file are described below.

<manifest>

manifest is the root element of the AndroidManifest.xml file. It


has package attribute that describes the package name of the activity
class.

<application>

application is the subelement of the manifest. It includes the


namespace declaration. This element contains several subelements
that declares the application component such as activity etc.

The commonly used attributes are of this element


are icon, label, theme etc.

android:icon represents the icon for all the android application


components.

android:label works as the default label for all the application


components.

android:theme represents a common theme for all the android


activities.
<activity>

activity is the subelement of application and represents an activity


that must be defined in the AndroidManifest.xml file. It has many
attributes such as label, name, theme, launchMode etc.

android:label represents a label i.e. displayed on the screen.

android:name represents a name for the activity class. It is required


attribute.

<intent-filter>

intent-filter is the sub-element of activity that describes the type of


intent to which activity, service or broadcast receiver can respond to.

<action>

It adds an action for the intent-filter. The intent-filter must have at


least one action element.

<category>

It adds a category name to an intent-filter.

Android R.java file

Android R.java is an auto-generated file by aapt (Android Asset


Packaging Tool) that contains resource IDs for all the resources of res/
directory.

If you create any component in the activity_main.xml file, id for the


corresponding component is automatically created in this file. This id
can be used in the activity source file to perform any action on the
component.

Android Directory structure

There are many more items which you use to build a good Android
application. Apart from coding for the application, you take care of
various other resources like static content that your code uses, such
as bitmaps, colors, layout definitions, user interface strings,
animation instructions, and more. These resources are always
maintained separately in various sub-directories under res/ directory
of the project.

This tutorial will explain you how you can organize your application
resources, specify alternative resources and access them in your
applications.

Organize resource in Android Studio

MyProject/
app/
manifest/
AndroidManifest.xml
java/
MyActivity.java
res/
drawable/
icon.png
layout/
activity_main.xml
info.xml
values/
strings.xml

Sr.No Directory & Resource Type


.

1 anim/

XML files that define property animations. They are saved in


res/anim/ folder and accessed from the R.anim class.

2 color/
XML files that define a state list of colors. They are saved in
res/color/ and accessed from the R.color class.

3 drawable/

Image files like .png, .jpg, .gif or XML files that are compiled into
bitmaps, state lists, shapes, animation drawable. They are
saved in res/drawable/ and accessed from the R.drawable class.

4 layout/

XML files that define a user interface layout. They are saved in
res/layout/ and accessed from the R.layout class.

5 menu/

XML files that define application menus, such as an Options


Menu, Context Menu, or Sub Menu. They are saved in res/menu/
and accessed from the R.menu class.

6 raw/

Arbitrary files to save in their raw form. You need to


call Resources.openRawResource() with the resource ID, which
is R.raw.filename to open such raw files.

7 values/

XML files that contain simple values, such as strings, integers,


and colors. For example, here are some filename conventions for
resources you can create in this directory −

 arrays.xml for resource arrays, and accessed from


the R.array class.

 integers.xml for resource integers, and accessed from


the R.integer class.

 bools.xml for resource boolean, and accessed from


the R.bool class.

 colors.xml for color values, and accessed from


the R.color class.

 dimens.xml for dimension values, and accessed from


the R.dimen class.

 strings.xml for string values, and accessed from


the R.string class.

 styles.xml for styles, and accessed from the R.style class.

8 xml/

Arbitrary XML files that can be read at runtime by


calling Resources.getXML(). You can save various configuration
files here which will be used at run time.

Components of Android screen

Application components are the essential building blocks of an


Android application. These components are loosely coupled by the
application manifest file AndroidManifest.xml that describes each
component of the application and how they interact.

There are following four main components that can be used within an
Android application −

Sr.N Components & Description


o

1 Activities

They dictate the UI and handle the user interaction to the smart
phone screen.

Services
2
They handle background processing associated with an
application.

Broadcast Receivers
3
They handle communication between Android OS and
applications.

Content Providers
4
They handle data and database management issues.

Activities

An activity represents a single screen with a user interface,in-short


Activity performs actions on the screen. For example, an email
application might have one activity that shows a list of new emails,
another activity to compose an email, and another activity for reading
emails. If an application has more than one activity, then one of them
should be marked as the activity that is presented when the
application is launched.

An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity {


}

Services

A service is a component that runs in the background to perform long-


running operations. For example, a service might play music in the
background while the user is in a different application, or it might
fetch data over the network without blocking user interaction with an
activity.
A service is implemented as a subclass of Service class as follows −

public class MyService extends Service {


}

Broadcast Receivers

Broadcast Receivers simply respond to broadcast messages from


other applications or from the system. For example, applications can
also initiate broadcasts to let other applications know that some data
has been downloaded to the device and is available for them to use,
so this is broadcast receiver who will intercept this communication
and will initiate appropriate action.

A broadcast receiver is implemented as a subclass


of BroadcastReceiver class and each message is broadcaster as
an Intent object.

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}

Content Providers

A content provider component supplies data from one application to


others on request. Such requests are handled by the methods of
the ContentResolver class. The data may be stored in the file system,
the database or somewhere else entirely.

A content provider is implemented as a subclass


of ContentProvider class and must implement a standard set of APIs
that enable other applications to perform transactions.

public class MyContentProvider extends ContentProvider {


public void onCreate(){}
}

We will go through these tags in detail while covering application


components in individual chapters.

Additional Components
There are additional components which will be used in the
construction of above mentioned entities, their logic, and wiring
between them. These components are −

S.N Components & Description


o

1 Fragments

Represents a portion of user interface in an Activity.

Views
2
UI elements that are drawn on-screen including buttons, lists
forms etc.

Layouts
3
View hierarchies that control screen format and appearance of
the views.

Intents
4
Messages wiring components together.

Resources
5
External elements, such as strings, constants and drawable
pictures.

Manifest
6
Configuration file for the application.
Android - UI Design

UI screen components

A typical user interface of an android application consists of action


bar and the application content area.

 Main Action Bar


 View Control
 Content Area
 Split Action Bar
These components have also been shown in the image below −

Understanding Screen Components

The basic unit of android application is the activity. A UI is defined in


an xml file. During compilation, each element in the XML is compiled
into equivalent Android GUI class with attributes represented by
methods.

View and ViewGroups

An activity is consist of views. A view is just a widget that appears on


the screen. It could be button e.t.c. One or more views can be
grouped together into one GroupView. Example of ViewGroup
includes layouts.

Types of layout

There are many types of layout. Some of which are listed below −
 Linear Layout
 Absolute Layout
 Table Layout
 Frame Layout
 Relative Layout
Linear Layout

Linear layout is further divided into horizontal and vertical layout. It


means it can arrange views in a single column or in a single row. Here
is the code of linear layout(vertical) that includes a text view.

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


<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
</LinearLayout>
AbsoluteLayout

The AbsoluteLayout enables you to specify the exact location of its


children. It can be declared like this.

<AbsoluteLayout
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >

<Button
android:layout_width=”188dp”
android:layout_height=”wrap_content”
android:text=”Button”
android:layout_x=”126px”
android:layout_y=”361px” />
</AbsoluteLayout>
TableLayout

The TableLayout groups views into rows and columns. It can be


declared like this.

<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_height=”fill_parent”
android:layout_width=”fill_parent” >

<TableRow>
<TextView
android:text=”User Name:”
android:width =”120dp”
/>

<EditText
android:id=”@+id/txtUserName”
android:width=”200dp” />
</TableRow>

</TableLayout>
RelativeLayout

The RelativeLayout enables you to specify how child views are


positioned relative to each other.It can be declared like this.

<RelativeLayout
android:id=”@+id/RLayout”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>
FrameLayout

The FrameLayout is a placeholder on screen that you can use to


display a single view. It can be declared like this.

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


<FrameLayout
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignLeft=”@+id/lblComments”
android:layout_below=”@+id/lblComments”
android:layout_centerHorizontal=”true” >

<ImageView
android:src = “@drawable/droid”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</FrameLayout>

Apart form these attributes, there are other attributes that are
common in all views and ViewGroups. They are listed below −

Sr.N View & description


o

1 layout_width

Specifies the width of the View or ViewGroup

2 layout_height

Specifies the height of the View or ViewGroup

3 layout_marginTop

Specifies extra space on the top side of the View or ViewGroup

4 layout_marginBottom

Specifies extra space on the bottom side of the View or


ViewGroup

5 layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup

6 layout_marginRight

Specifies extra space on the right side of the View or ViewGroup

7 layout_gravity

Specifies how child Views are positioned

8 layout_weight

Specifies how much of the extra space in the layout should be


allocated to the View

Units of Measurement

When you are specifying the size of an element on an Android UI, you
should remember the following units of measurement.

Sr.N Unit & description


o

1 dp

Density-independent pixel. 1 dp is equivalent to one pixel on a


160 dpi screen.

2 sp

Scale-independent pixel. This is similar to dp and is


recommended for specifying font sizes

3 pt

Point. A point is defined to be 1/72 of an inch, based on the


physical screen size.

4 px

Pixel. Corresponds to actual pixels on the screen

Screen Densities

Sr.No Density & DPI

1 Low density (ldpi)

120 dpi

2 Medium density (mdpi)

160 dpi

3 High density (hdpi)

240 dpi

4 Extra High density (xhdpi)

320 dpi

TextView in Android

In Android, TextView displays text to the user and optionally allows


them to edit it programmatically. TextView is a complete text editor,
however basic class is configured to not allow editing but we can edit
it.
View is the parent class of TextView. Being a subclass of view
the text view component can be used in your app’s GUI inside a
ViewGroup, or as the content view of an activity.

We can create a TextView instance by declaring it inside a


layout(XML file) or by instantiating it programmatically(Java Class).

TextView code in XML:

<TextView android:id="@+id/simpleTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="AbhiAndroid" />

TextView code in JAVA:

TextView textView = (TextView) findViewById(R.id.textView);

textView.setText("AbhiAndroid"); //set text for text view

Edit Text

In Android, EditText is a standard entry widget in android apps. It is an


overlay over TextView that configures itself to be editable. EditText is
a subclass of TextView with text editing operations. We often use
EditText in our applications in order to provide an input or text field,
especially in forms. The most simple example of EditText is Login or
Sign-in form.
EditText Code:

We can create a EditText instance by declaring it inside a


layout(XML file) or by instantiating it programmatically (i.e.
in Java Class).

EditText code in XML:

<EditText

android:id="@+id/simpleEditText"

android:layout_height="wrap_content"

android:layout_width="match_parent"/>

Retrieving / Getting the Value From EditText In Java Class:

Below is the example code of EditText in which we retrieve the value


from a EditText in Java class. We have used this code in the example
you will find at the end of this post.

EditText simpleEditText = (EditText)


findViewById(R.id.simpleEditText);

String editTextValue = simpleEditText.getText().toString();

In Android, Button represents a push button. A Push buttons can be


clicked, or pressed by the user to perform an action. There are
different types of buttons used in android such as
CompoundButton, ToggleButton, RadioButton.
Button is a subclass of TextView class and compound button is the
subclass of Button class. On a button we can perform different actions
or events like click event, pressed event, touch event etc.

Android buttons are GUI components which are sensible to taps


(clicks) by the user. When the user taps/clicks on button in an Android
app, the app can respond to the click/tap . These buttons can be
divided into two categories: the first is Buttons with text on, and
second is buttons with an image on. A button with images on can
contain both an image and a text. Android buttons with images on are
also called ImageButton.

Button code in XML:

The below code will create Button and write “Abhi Android” text on it.

<Button

android:id="@+id/simpleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Abhi Android"/>

Image Button

In Android, ImageButton is used to display a normal button with a


custom image in a button. In simple words we can say, ImageButton is
a button with an image that can be pressed or clicked by the users. By
default it looks like a normal button with the standard button
background that changes the color during different button states.
An image on the surface of a button is defined within a xml (i.e.
layout ) by using src attribute or within java class by using
setImageResource() method. We can also set an image or custom
drawable in the background of the image button.

Important Note: Standard button background image is displayed in the


background of button whenever you create an image button. To
remove that image, you can define your own background image
in xml by using background attribute or in java class by using
setBackground() method.

Below is the code and image which shows how custom imagebutton


looks in Android:

Important Note: ImageButton has all the properties of a normal button


so you can easily perform any event like click or any other event which
you can perform on a normal button.

ImageButton code in XML:

<!--Make Sure To Add Image Name home in Drawable Folder-->

<ImageButton

android:id="@+id/simpleImageButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/home" />
Toggle Button

In Android, ToggleButton is used to display checked and unchecked


state of a button. ToggleButton basically an off/on button with a light
indicator which indicate the current state of toggle button. The most
simple example of ToggleButton is doing on/off in sound, Bluetooth,
wifi, hotspot etc. It is a subclass of compoundButton.

ToggleButton Vs Switch In Android:

ToggleButton allow the users to change the setting between two


states like turn on/off your wifi, Bluetooth etc from your phone’s
setting menu. Since, Android 4.0 version ( API level 14 ) there is an
another kind of ToggleButton called Switch which provide the user
slider control. You can learn more about it reading Switch tutorial.

Important Note: Android Switch and ToggleButton both are the


subclasses of CompoundButton class.

ToggleButton code in XML:

<ToggleButton

android:id="@+id/simpleToggleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>
How To Check Current State Of ToggleButton:

To check current state of a toggle button programmatically we


use isChecked() method. This method returns a Boolean value
either true or false. If a toggle button is checked then it returns true
otherwise it returns false. Below is the code which checks the current
state of a toggle button.

In Android, ToggleButton is used to display checked and unchecked


state of a button. ToggleButton basically an off/on button with a light
indicator which indicate the current state of toggle button. The most
simple example of ToggleButton is doing on/off in sound, Bluetooth,
wifi, hotspot etc. It is a subclass of compoundButton.

ToggleButton Vs Switch In Android:

ToggleButton allow the users to change the setting between two


states like turn on/off your wifi, Bluetooth etc from your phone’s
setting menu. Since, Android 4.0 version ( API level 14 ) there is an
another kind of ToggleButton called Switch which provide the user
slider control. You can learn more about it reading Switch tutorial.

Important Note: Android Switch and ToggleButton both are the


subclasses of CompoundButton class.

ToggleButton code in XML:


<ToggleButton

android:id="@+id/simpleToggleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

How To Check Current State Of ToggleButton:

To check current state of a toggle button programmatically we


use isChecked() method. This method returns a Boolean value
either true or false. If a toggle button is checked then it returns true
otherwise it returns false. Below is the code which checks the current
state of a toggle button.

Android RadioButton

RadioButton is a two states button which is either checked or


unchecked. If a single radio button is unchecked, we can click it to
make checked radio button. Once a radio button is checked, it cannot
be marked as unchecked by user.

RadioButton is generally used with RadioGroup. RadioGroup contains


several radio buttons, marking one radio button as checked makes all
other radio buttons as unchecked.

RadioGroup  is a widget in Android which groups  RadioButtons . More


specifically, the use of  RadioGroup  provides the capability of
selecting only one  RadioButton  from the set. When the user chooses
one  RadioButton , the previous one that was selected, becomes
automatically unchecked.

Checkbox in Android

CheckBox belongs to android.widget.CheckBox class. Android


CheckBox class is the subclass of CompoundButton class. It is
generally used in a place where user can select one or more than
choices from a given list of choices. For example, selecting hobbies.
It has two states – checked or unchecked.

Methods of CheckBox class


 public boolean isChecked(): If CheckBox is in checked state then
return true otherwise false.
 public void setChecked(boolean status): It changes the state of
the CheckBox.



 Progress Bar in android
 In Android, ProgressBar is used to display the status of work
being done like analyzing status of work or downloading a file
etc. In Android, by default a progress bar will be displayed as a
spinning wheel but If we want it to be displayed as a horizontal
bar then we need to use style attribute as horizontal. It mainly
use the “android.widget.ProgressBar” class.


 Important Note: A progress bar can also be made indeterminate.
In this mode a progress bar shows a cyclic animation without an
indication of progress. This mode is used in application when we
don’t know the amount of work to be done.

 To add a progress bar to a layout (xml) file, you can use


the <ProgressBar> element. By default, a progress bar is a
spinning wheel (an indeterminate indicator). To change to a
horizontal progress bar, apply the progress bar’s horizontal style.
 ProgressBar code:
 <ProgressBar

 android:id="@+id/simpleProgressBar"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content" />

List View inAndroid

List of scrollable items can be displayed in Android using ListView. It


helps you to displaying the data in the form of a scrollable list. Users
can then select any list item by clicking on it. ListView is default
scrollable so we do not need to use scroll View or anything else
with ListView.

ListView is widely used in android applications. A very common


example of ListView is your phone contact book, where you have a list
of your contacts displayed in a ListView and if you click on it then user
information is displayed.

Adapter: To fill the data in a ListView we simply use adapters. List


items are automatically inserted to a list using an Adapter that pulls
the content from a source such as an arraylist, array or database.

ListView in Android Studio: Listview is present inside Containers. From


there you can drag and drop on virtual mobile screen to create it.
Alternatively you can also XML code to create it.

Here is Android ListView XML Code:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/simpleListView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

tools:context="abhiandroid.com.listexample.MainActivity">

</ListView>

Grid View in Android

In android GridView is a view group that display items in two


dimensional scrolling grid (rows and columns), the grid items are not
necessarily predetermined but they are automatically inserted to the
layout using a ListAdapter. Users can then select any grid item by
clicking on it. GridView is default scrollable so we don’t need to
use ScrollView or anything else with GridView.

GridView is widely used in android applications. An example of


GridView is your default Gallery, where you have number of images
displayed using grid.

Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView


we simply use adapter and grid items are automatically inserted to a
GridView using an Adapter which pulls the content from a source such
as an arraylist, array or database. You can read full Adapter tutorial
here.

GridView in Android Studio: Gridview is present inside Containers.


From there you can drag and drop on virtual mobile screen to create it.
Alternatively you can also XML code to create it.
Basic GridView code in XML:

<GridView

android:id="@+id/simpleGridView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:numColumns="3"/>

Image View in Android

In Android, ImageView class is used to display an image file in


application. Image file is easy to use but hard to master in Android,
because of the various screen sizes in Android devices. An android is
enriched with some of the best UI design widgets that allows us to
build good looking and attractive UI based application.

Important Note: ImageView comes with different configuration options


to support different scale types. Scale type options are used for
scaling the bounds of an image to the bounds of the imageview. Some
of them scaleTypes configuration properties are center, center_crop,
fit_xy, fitStart etc. You can read our ScaleType tutorial to learn all
details on it.

Below is an ImageView code in XML:

Make sure to save lion image in drawable folder

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion" />

Scroll View

In android ScrollView can hold only one direct child. This means that,


if you have complex layout with more views(Buttons, TextViews or any
other view) then you must enclose them inside another standard
layout like Table Layout, Relative Layout or Linear Layout. You can
specify layout_width and layout_height to adjust width and height of
screen. You can specify height and width in dp(density pixel) or
px(pixel). Then after enclosing them in a standard layout, enclose the
whole layout in ScrollView to make all the element or views scrollable.

ScrollView in Android Studio Design: It is present inside Containers


>> ScrollView or HorizontalScrollView

Important Note 1: We never use a Scroll View with


a ListView because List View is default scrollable(i.e. vertical
scrollable). More importantly, doing this affects all of the important
optimizations in a List View for dealing with large lists(list items). Just
because it effectively forces the List View to display its entire list of
items to fill up the infinite container supplied by a ScrollView so we
don’t use it with List View.

Important Note 2: In android default ScrollView is used to scroll the


items in vertical direction and if you want to scroll the items
horizontally then you need to implement horizontal ScrollView.
ScrollView Syntax:

<ScrollView

android:id="@+id/scrollView"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<!-- add child view’s here -->

</ScrollView>

In Android, Toast is used to display information for a period of time. It


contains a message to be displayed quickly and disappears after
specified period of time. It does not block the user
interaction. Toast is a subclass of Object class. In this we use two
constants for setting the duration for the Toast. Toast notification in
android always appears near the bottom of the screen. We can also
create our custom toast by using custom layout(xml file).

Special Note: In Android, Toast is used when we required to notify user


about an operation without expecting any user input. It displays a
small popup for message and automatically fades out after timeout.

Toast
Important Methods Of Toast:

Let’s we discuss some important methods of Toast that may be called


in order to manage the Toast.

1. makeText(Context context, CharSequence text, int


duration): This method is used to initiate the Toast. This
method take three parameters First is for the application
Context, Second is text message and last one is duration
for the Toast.
2.

Constants of Toast: Below is the constants of Toast that are used for


setting the duration for the Toast.

1. LENGTH_LONG: It is used to display the Toast for a long period of


time. When we set this duration the Toast will be displayed for a long
duration.

2. LENGTH_SHORT: It is used to display the Toast for short period of


time. When we set this duration the Toast will be displayed for short
duration.

Below we show the use of makeText() method of Toast in which we


set application context, a text message and duration for the Toast.

Toast toast = Toast.makeText(getApplicationContext(), "Simple


Toast", Toast.LENGTH_LONG); // initiate the Toast with context,
message and duration for the Toast

2. show(): This method is used to display the Toast on the screen. This


method is display the text which we create using makeText() method
of Toast.

Below we Firstly initiate the Toast and then display it using show()
method.

Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast


In Android", Toast.LENGTH_LONG); // initiate the Toast with context,
message and duration for the Toast

toast.show(); // display the Toast


3. setGravity(int,int,int): This method is used to set the gravity for the
Toast. This method accepts three parameters: a Gravity constant, an
x-position offset, and a y-position offset.

Below we Firstly initiate the Toast, set top and left gravity and then
display it using show() method.

Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast


In Android", Toast.LENGTH_LONG); // initiate the Toast with context,
message and duration for the Toast

toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);     // set gravity for


the Toast.

toast.show(); // display the Toast

4. setText(CharSequence s): This method is used to set the text for the


Toast. If we use makeText() method and then we want to change the
text value for the Toast then we use this method.

Below we firstly create a new Toast using makeText() method and


then set the text for the Toast.

Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast


In Android", Toast.LENGTH_LONG); // initiate the Toast with context,
message and duration for the Toast

toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);     // set gravity for


the Toast.

toast.setText("Changed Toast Text"); // set the text for the Toast

toast.show(); // display the Toast

5. setDuration(int duration): This method is used to set the duration for


the Toast. If we use makeText() method and then we want to change
the duration for the Toast then we use this method.

Below we firstly create a new Toast using makeText() method and


then set the duration for the Toast.
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast
In Android", Toast.LENGTH_LONG); // initiate the Toast with context,
message and duration for the Toast

toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);     // set gravity for


the Toast.

toast.setDuration(Toast.LENGTH_SHORT); // set the duration for the


Toast.

toast.show(); // display the Toast

6. inflate(int, ViewGroup): This method is used to inflate the layout


from the xml. In this method first parameter is the layout resource ID
and the second is the root View.

Below we retrieve the Layout Inflater and then inflate the layout from
the xml file.

// Retrieve the Layout Inflater and inflate the layout from xml

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast_layout,

(ViewGroup) findViewById(R.id.toast_layout_root));

7. setView(View): This method is used to set the view for the Toast. In


this method we pass the inflated layout which we inflate using inflate()
method.

Below we firstly retrieve the layout inflater and then inflate the layout
and finally create a new Toast and pass the inflated layout in the
setView() method.

// Retrieve the Layout Inflater and inflate the layout from xml

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast_layout,

(ViewGroup) findViewById(R.id.toast_layout_root));
// create a new Toast using context

Toast toast = new Toast(getApplicationContext());

toast.setDuration(Toast.LENGTH_LONG); // set the duration for the


Toast

toast.setView(layout); // set the inflated layout

toast.show(); // display the custom Toast

  Custom Toast in Android:

In Android, Sometimes simple Toast may not be satisfactory, and then


we can go for customizing a Toast. For creating a custom layout,
define a View layout, in XML and pass the root View object to the
setView(View) method.

Steps for Implementation of Custom Toast In Android:

Step 1: Firstly Retrieve the Layout Inflater  with  getLayoutInflater()


(or getSystemService()) and then inflate the layout from XML
using inflate(int, ViewGroup). In inflate method first parameter is the
layout resource ID and the second is the root View.

Step 2: Create a new Toast with Toast(Context) and set some


properties of the Toast, such as the duration and gravity.

Step 3: Call setView(View) and pass the inflated layout in this method.

Step 4: Display the Toast on the screen using show() method of Toast.

In the below example we have shown the functioning of Toast and


custom Toast both.

Toast And Custom Toast Example In Android Studio:

Below is the example of Toast and Custom Toast in Android. In this


example we display two Button’s one for Simple Toast and other for
Custom Toast and perform click event on them. Whenever a user click
on simple Toast Button a Toast with message “Simple Toast In
Android” displayed on the screen and when a user clicks on custom
toast Button a message “Custom Toast In Android” with a image
displayed on the screen. For Creating a custom toast we firstly
retrieve the layout inflater and then inflate the custom toast layout
from the xml file. After that we get the reference
of TextView and ImageView from the inflated layout and set the text
and image in the TextView and ImageView. Finally we create a new
Toast and pass the inflated layout in the setView() method and then
display the Toast by using show() method of Toast.

In Android, DatePicker is a widget used to select a date. It allows to


select date by day, month and year in your custom UI (user interface).
If we need to show this view as a dialog then we have to use a
DatePickerDialog class. For selecting time Android also
provides timepicker to select time.

DatePicker code in XML:

<DatePicker

android:id="@+id/simpleDatePicker"

android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:datePickerMode="spinner"/>

Methods of DatePicker

Let’s discuss some common methods of a datepicker which are used


to configure a DatePicker in our application.

1. setSpinnersShown(boolean shown):

This method is used to set whether the spinner of the date picker in


shown or not. In this method you have to set a Boolean value either
true or false. True indicates spinner is shown, false value
indicates spinner is not shown. Default value for this function is true.

Below we show the use of setSpinnerShown() function by setting false


value.

DatePicker simpleDatePicker =
(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date
picker

simpleDatePicker.setSpinnersShown(false); // set false value for the


spinner shown function
2. getDayOfMonth():

This method is used to get the selected day of the month from a date
picker.  This method returns an integer value.

Below we get the selected day of the month from a date picker.

/*Add in Oncreate() funtion after setContentView()*/

DatePicker simpleDatePicker = (DatePicker)


findViewById(R.id.simpleDatePicker); // initiate a date picker

int day = simpleDatePicker.getDayOfMonth(); // get the selected day of


the month

3. getMonth():

This method is used to get the selected month from a date picker. 
This method returns an integer value.

Below we get the selected month from a date picker.

DatePicker simpleDatePicker =
(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date
picker
int month = simpleDatePicker.getMonth(); // get the selected month

4. getYear():

This method is used to get the selected year from a date picker.  This
method returns an integer value.

Below code is used to get the selected year from a date picker.

DatePicker simpleDatePicker =
(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date
picker

int year = simpleDatePicker.getYear(); // get the selected year

5. getFirstDayOfWeek():

This method is used to get the first day of the week. This method
returns an integer value.

Below code is used to get the first day of the week.

DatePicker simpleDatePicker =
(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date
picker

int firstDay=simpleDatePicker.getFirstDayOfWeek(); // get the first day


of the week

Attributes of DatePicker

Now let’s  we discuss some important attributes that helps us to


configure a DatePicker in your XML file (layout).

1. id: id is an attribute used to uniquely identify a date picker.

<DatePicker

android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"

android:layout_height="wrap_content"

/>

2. datePickerMode: This attribute is used to set the Date Picker in


mode either spinner or calendar. Default mode is calendar but this
mode is not used after api level 21, so from api level 21 you have to set
the mode to spinner.

Intent

Android uses Intent for communicating between the components of an


Application and also from one application to another application.

Intent are the objects which is used in android for passing the


information among Activities in an Application and from one app to
another also. Intent are used for communicating between the
Application components and it also provides the connectivity between
two apps.

For example: Intent facilitate you to redirect your activity to another


activity on occurrence of any event. By calling, startActivity() you can
perform this task.

Intent intent = new Intent(getApplicationContext(),


SecondActivity.class);

startActivity(intent);

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 Intents are used to connect the application internally.


 In Explicit we use the name of component which will be affected
by Intent. For Example: If we know class name then we can
navigate the app from One Activity to another activity using
Intent. In the similar way we can start a service to download a
file in background process.

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

Intent intent = new Intent(getApplicationContext(),


SecondActivity.class);

startActivity(intent);

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

Intent intentObj = new Intent(Intent.ACTION_VIEW);

intentObj.setData(Uri.parse("https://www.abhiandroid.com"));

startActivity(intentObj);

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.

Intent Filter
Intent Filter are the components which decide the behavior of
an intent. As we have read in our previous tutorial of Intent about the
navigation of one activity to another, that can be achieve by
declaring intent filter. We can declare an Intent Filter for an Activity in
manifest file.

Intent filters specify the type of intents that an Activity, service or


Broadcast receiver can respond to. It declares the functionality of its
parent component (i.e. activity, services or broadcast receiver). It
declares the capability of any activity or services or a broadcast
receiver.

Intent Filter Code Inside Android Manifest:

The code of Intent Filter is used inside AndroidManifest.xml file for an


activity. You can see it: open manifests folder >> open
AndroidManifest.xml file

Syntax of Intent Filters:

Intent filter is declared inside Manifest file for an Activity.

<!--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"

>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

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.

Below is Activity Lifecycle Table:

Short description of Activity Lifecycle example:

onCreate() – Called when the activity is first created

onStart() – Called just after it’s creation or by restart method after


onStop(). Here Activity start becoming visible to user

onResume() – Called when Activity is visible to user and user can


interact with it

onPause() – Called when Activity content is not visible because user


resume previous activity

onStop() – Called when activity is not visible to user because some


other activity takes place of it

onRestart() – Called when user comes on screen or resume the activity


which was stopped

onDestroy – Called when Activity is not in background


Below Activity Lifecycle Diagram Shows Different States:

Different Types of Activity Lifecycle States:

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.

LIST OF ACTIVITY LIFECYCLE METHODS OR STATES:

Activity Created: onCreate(Bundle savedInstanceState):

onCreate() method is called when activity gets memory in the OS. To


use create state we need to override onCreate(Bundle
savedInstanceState) method. Now there will be question in mind what
is Bundle here, so Bundle is a data repository object that can store any
kind of primitive data and this object will be null until some data isn’t
saved in that.

 When an Activity first call or launched then onCreate(Bundle


savedInstanceState) method is responsible to create the activity.
 When ever orientation(i.e. from horizontal to vertical or vertical
to horizontal) of activity gets changed or when an Activity gets
forcefully terminated by any Operating System then
savedInstanceState i.e. object of Bundle Class will save the state
of an Activity.
 It is best place to put initialization code.

Learn More About onCreate(Bundle savedInstanceState) With Example

Activity Started: onStart():

onStart() method is called just after it’s creation. In other case Activity
can also be started by calling restart method i.e after activity stop. So
this means onStart() gets called by Android OS when
user switch between applications. For example, if a user was using
Application A and then a notification comes and user clicked on
notification and moved to Application B, in this case Application A will
be paused. And again if a user again click on app icon of Application A
then Application A which was stopped will again gets started.

Learn More About onStart() With Example

Activity Resumed:.onResume():

Activity resumed is that situation when it is actually visible to user


means the data displayed in the activity is visible to user. In lifecycle
it always gets called after activity start and in most use case after
activity paused (onPause).

Activity Paused: onPause():

Activity is called paused when it’s content is not visible to user, in


most case onPause() method called by Android OS when user press
Home button (Center Button on Device) to make hide.

Activity also gets paused before stop called in case user press the
back navigation button. The activity will go in paused state for these
reasons also if a notification or some other dialog is overlaying any
part (top or bottom) of the activity (screen). Similarly, if the other
screen or dialog is transparent then user can see the screen but
cannot interact with it. For example, if a call or notification comes in,
the user will get the opportunity to take the call or ignore it.
Learn More About onPause() With Example

Activity Stopped: onStop():

Activity is called stopped when it’s not visible to user. Any activity
gets stopped in case some other activity takes place of it. For
example, if a user was on screen 1 and click on some button and
moves to screen 2. In this case Activity displaying content for screen 1
will be stopped.

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.

Learn More About onStop() With Example

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.

In case if user press the home button and app moves to background.
User is not using it no more and it’s being shown in recent apps list. So
in this case if system required resources need to use somewhere else
then OS can destroy the Activity.

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().

Broadcast

A broadcast receiver (receiver) is an Android component which allows


you to register for system or application events. All registered
receivers for an event are notified by the Android runtime once this
event happens.

For example, applications can register for


the ACTION_BOOT_COMPLETED system event which is fired once the
Android system has completed the boot process.

1.2. Implementation

A receiver can be registered via the AndroidManifest.xml file.

Alternatively to this static registration, you can also register a receiver


dynamically via the Context.registerReceiver() method.

The implementing class for a receiver extends


the BroadcastReceiver class.

If the event for which the broadcast receiver has registered happens,
the onReceive() method of the receiver is called by the Android system.

1.3. Life cycle of a broadcast receiver

After the onReceive() of the receiver class has finished, the Android


system is allowed to recycle the receiver.

1.4. Asynchronous processing

Before API level 11, you could not perform any asynchronous operation
in the onReceive() method, because once the onReceive() method had
been finished, the Android system was allowed to recycle that
component. If you have potentially long running operations, you should
trigger a service instead.
Since Android API 11 you can call the goAsync() method. This method
returns an object of the PendingResult type. The Android system
considers the receiver as alive until you call
the PendingResult.finish() on this object. With this option you can
trigger asynchronous processing in a receiver. As soon as that thread
has completed, its task calls finish() to indicate to the Android system
that this component can be recycled.

Content provider in android

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 1, these include:

 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

 Synchronizing application data with your server using an


implementation of AbstractThreadedSyncAdapter

 Loading data in your UI using a CursorLoader


Accessing a provider

When you want to access data in a content provider, you use


the ContentResolver object in your application's Context to
communicate with the provider as a client.
The ContentResolver object communicates with the provider object,
an instance of a class that implements ContentProvider. The provider
object receives data requests from clients, performs the requested
action, and returns the results. This object has methods that call
identically-named methods in the provider object, an instance of one of
the concrete subclasses of ContentProvider.
The ContentResolver methods provide the basic "CRUD" (create,
retrieve, update, and delete) functions of persistent storage.

A common pattern for accessing a ContentProvider from your UI uses


a CursorLoader to run an asynchronous query in the background.
The Activity or Fragment in your UI call a CursorLoader to the query,
which in turn gets the ContentProvider using the ContentResolver.
This allows the UI to continue to be available to the user while the
query is running. This pattern involves the interaction of a number of
different objects, as well as the underlying storage mechanism, as
illustrated in figure 2.

Fragments in android

A Fragment is a piece of an activity which enable more modular


activity design. or a fragment is a kind of sub-activity.

Following are important points about fragment −

 A fragment has its own layout and its own behaviour with its
own life cycle callbacks.
 You can add or remove fragments in an activity while the activity
is running.
 You can combine multiple fragments in a single activity to build
a multi-pane UI.
 A fragment can be used in multiple activities.
 Fragment life cycle is closely related to the life cycle of its host
activity which means when the activity is paused, all the
fragments available in the activity will also be stopped.
 A fragment can implement a behaviour that has no user interface
component.
 Fragments were added to the Android API in Honeycomb version
of Android which API version 11.

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.

Prior to fragment introduction, we had a limitation because we can


show only a single activity on the screen at one given point in time.
So we were not able to divide device screen and control different
parts separately. But with the introduction of fragment we got more
flexibility and removed the limitation of having a single activity on the
screen at a time. Now we can have a single activity but each activity
can comprise of multiple fragments which will have their own layout,
events and complete life cycle.

Following is a typical example of how two UI modules defined by


fragments can be combined into one activity for a tablet design, but
separated for a handset design.
The application can embed two fragments in Activity A, when running
on a tablet-sized device. However, on a handset-sized screen, there's
not enough room for both fragments, so Activity A includes only the
fragment for the list of articles, and when the user selects an article,
it starts Activity B, which includes the second fragment to read the
article.

Fragment Life Cycle

Android fragments have their own life cycle very similar to an android
activity. This section briefs different stages of its life cycle.

Fragment lifecycle
Here is the list of methods which you can to override in your fragment
class −

 onAttach()The fragment instance is associated with an activity


instance.The fragment and the activity is not fully initialized.
Typically you get in this method a reference to the activity
which uses the fragment for further initialization work.
 onCreate() The system calls this method when creating the
fragment. You should initialize essential components of the
fragment that you want to retain when the fragment is paused or
stopped, then resumed.
 onCreateView() The system calls this callback when it's time for
the fragment to draw its user interface for the first time. To
draw a UI for your fragment, you must return a View component
from this method that is the root of your fragment's layout. You
can return null if the fragment does not provide a UI.
 onActivityCreated()The onActivityCreated() is called after the
onCreateView() method when the host activity is created.
Activity and fragment instance have been created as well as the
view hierarchy of the activity. At this point, view can be
accessed with the findViewById() method. example. In this
method you can instantiate objects which require a Context
object
 onStart()The onStart() method is called once the fragment gets
visible.
 onResume()Fragment becomes active.
 onPause() The system calls this method as the first indication
that the user is leaving the fragment. This is usually where you
should commit any changes that should be persisted beyond the
current user session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this
method
 onDestroy()onDestroy() called to do final clean up of the
fragment's state but Not guaranteed to be called by the Android
platform.

Android Service

Android service is a component that is used to perform operations on


the background such as playing music, handle network transactions,
interacting content providers etc. It doesn't has any UI (user
interface).
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).

The android.app.Service is subclass of ContextWrapper class.

Note: Android service is not a thread or separate process.

Life Cycle of Android Service

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.

Android System Architecture


Android operating system is a stack of software components which is
roughly divided into five sections and four main layers as shown
below in the architecture diagram.

Linux kernel

At the bottom of the layers is Linux - Linux 3.6 with approximately 115
patches. This provides a level of abstraction between the device
hardware and it contains all the essential hardware drivers like
camera, keypad, display etc. Also, the kernel handles all the things
that Linux is really good at such as networking and a vast array of
device drivers, which take the pain out of interfacing to peripheral
hardware.

Libraries

On top of Linux kernel there is a set of libraries including open-source


Web browser engine WebKit, well known library libc, SQLite database
which is a useful repository for storage and sharing of application
data, libraries to play and record audio and video, SSL libraries
responsible for Internet security etc.

Android Libraries

This category encompasses those Java-based libraries that are


specific to Android development. Examples of libraries in this
category include the application framework libraries in addition to
those that facilitate user interface building, graphics drawing and
database access. A summary of some key core Android libraries
available to the Android developer is as follows −

 android.app − Provides access to the application model and is


the cornerstone of all Android applications.

 android.content − Facilitates content access, publishing and


messaging between applications and application components.

 android.database − Used to access data published by content


providers and includes SQLite database management classes.

 android.opengl − A Java interface to the OpenGL ES 3D graphics


rendering API.

 android.os − Provides applications with access to standard


operating system services including messages, system services
and inter-process communication.

 android.text − Used to render and manipulate text on a device


display.

 android.view − The fundamental building blocks of application


user interfaces.

 android.widget − A rich collection of pre-built user interface


components such as buttons, labels, list views, layout
managers, radio buttons etc.

 android.webkit − A set of classes intended to allow web-


browsing capabilities to be built into applications.

Having covered the Java-based core libraries in the Android runtime,


it is now time to turn our attention to the C/C++ based libraries
contained in this layer of the Android software stack.
Android Runtime

This is the third section of the architecture and available on the


second layer from the bottom. This section provides a key component
called Dalvik Virtual Machine which is a kind of Java Virtual Machine
specially designed and optimized for Android.

The Dalvik VM makes use of Linux core features like memory


management and multi-threading, which is intrinsic in the Java
language. The Dalvik VM enables every Android application to run in
its own process, with its own instance of the Dalvik virtual machine.

The Android runtime also provides a set of core libraries which enable
Android application developers to write Android applications using
standard Java programming language.

Application Framework

The Application Framework layer provides many higher-level services


to applications in the form of Java classes. Application developers
are allowed to make use of these services in their applications.

The Android framework includes the following key services −

 Activity Manager − Controls all aspects of the application


lifecycle and activity stack.

 Content Providers − Allows applications to publish and share


data with other applications.

 Resource Manager − Provides access to non-code embedded


resources such as strings, color settings and user interface
layouts.

 Notifications Manager − Allows applications to display alerts and


notifications to the user.

 View System − An extensible set of views used to create


application user interfaces.

Applications
You will find all the Android application at the top layer. You will write
your application to be installed on this layer only. Examples of such
applications are Contacts Books, Browser, Games etc.

Вам также может понравиться