KEMBAR78
Mobile Application Development | PDF | Android (Operating System) | Payment System
0% found this document useful (0 votes)
36 views78 pages

Mobile Application Development

Uploaded by

Lokesh Pck
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views78 pages

Mobile Application Development

Uploaded by

Lokesh Pck
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Mobile Application Development

Unit I
1. Mobile Device Operating Systems
An operating system (OS) for mobile devices manages the basic functions. It runs apps, controls
memory, and connects to networks. These systems provide an easy-to-use interface.
They're designed for smartphones, tablets, and wearable tech. Mobile OSes let you multitask,
browse the web and download apps. Popular options include iOS from Apple, Android from
Google, and Huawei's HarmonyOS.
Key Features of a Mobile Operating System
1. User Interface (UI): Touch inputs of Graphical User Interface (GUI) provided by mobile OS
are optimized. This is where users can use touch gestures, in other words, swiping, tapping, and
pinching, to interact with their gadgets.
2. Multitasking: It helps in running of many apps at the same time but what is more we can
quickly switch between them without any hindrance. Such offloading is for applications that are
not currently used actively.
3. Connectivity: It provides a variety of connections such as cellular, Wi-Fi, Bluetooth, NFC
(Near Field Communication) and others to facilitate the communication of the device with other
devices and networks.
4. Application Management: Is a platform that has its own app marketplace or store which the
users utilize to browse, install, run and updates the applications exclusively for that platform.
5. Resource Management: Efficiently allocates hardware resources like the CPU ,ram , and
battery by achieving a balance between performance and battery life.
Types of Mobile Operating System
The mobile world has seen many operating systems. Some are big and powerful. Others are
small and niche. Here are the main types of mobile OS :
1. Android: Made by Google, Android is the most used mobile OS worldwide. It's an open-
source system built on Linux code. Android is made mostly for touchscreen phones and tablets.
Being open allows companies to customize Android for their gadgets. That leads to many
different Android devices.
2. Apple Inc. created iOS, the operating system for iPhone, iPad, and iPod Touch. Its smooth
interface and tight Apple ecosystem integration are hallmarks. However, Apple's total control
over hardware and software limits customization options, unlike Android's open platform.
3. Huawei developed HarmonyOS (Hongmeng OS in China): work across diverse devices like
smartphones, wearables, laptops, smart home gadgets. By offering a unified ecosystem, Huawei
aims to navigate US government restrictions on its business.
4. KaiOS is a basic mobile OS: It powers basic phones without touchscreens. KaiOS is based on
discontinued Firefox OS. KaiOS supports 4G, GPS, and apps like Facebook and WhatsApp. It
offers strong capabilities for non-smartphone mobile devices.
5. Tizen is a Linux-based mobile OS developed by Samsung. It was created with Intel and the
Tizen Association. Tizen powers various Samsung products.
Smartphones have different operating systems.
2. Special Constraints & Requirements
There are special constraints under which the operating system of a mobile device to operate …
Limited memory
Limited screen size
Miniature keyboard
Limited processing power
Limited battery power
Limited and fluctuating of the wireless medium
Special service Requirements
Support for specific communication protocols
Support for a variety of input mechanism
Compliance with open standard
Extensive library support

3. Popular platforms of the Mobile OS /commercial mobile operating systems

Android OS: The Android operating system is the most popular operating system today. It is a
mobile OS based on the Linux Kernel and open-source software. The android operating system
was developed by Google. The first Android device was launched in 2008.

Bada (Samsung Electronics): Bada is a Samsung mobile operating system that was launched in
2010. The Samsung wave was the first mobile to use the bada operating system. The bada operating
system offers many mobile features, such as 3-D graphics, application installation, and multipoint-
touch.

BlackBerry OS: The BlackBerry operating system is a mobile operating system developed
by Research In Motion (RIM). This operating system was designed specifically for BlackBerry
handheld devices. This operating system is beneficial for the corporate users because it provides
synchronization with Microsoft Exchange, Novell GroupWise email, Lotus Domino, and other
business software when used with the BlackBerry Enterprise Server.
iPhone OS / iOS: The iOS was developed by the Apple inc for the use on its device. The iOS
operating system is the most popular operating system today. It is a very secure operating system.
The iOS operating system is not available for any other mobiles.

Symbian OS: Symbian operating system is a mobile operating system that provides a high-level
of integration with communication. The Symbian operating system is based on the java language.
It combines middleware of wireless communications and personal information management (PIM)
functionality. The Symbian operating system was developed by Symbian Ltd in 1998 for the use
of mobile phones. Nokia was the first company to release Symbian OS on its mobile phone at that
time.

Windows Mobile OS: The window mobile OS is a mobile operating system that was developed
by Microsoft. It was designed for the pocket PCs and smart mobiles.

Harmony OS: The harmony operating system is the latest mobile operating system that was
developed by Huawei for the use of its devices. It is designed primarily for IoT devices.

Palm OS: The palm operating system is a mobile operating system that was developed by Palm
Ltd for use on personal digital assistants (PADs). It was introduced in 1996. Palm OS is also known
as the Garnet OS.

WebOS (Palm/HP): The WebOS is a mobile operating system that was developed by Palm. It
based on the Linux Kernel. The HP uses this operating system in its mobile and touchpads.

4. M Commerce
What is M-Commerce?
Mobile commerce or simply M-Commerce means engaging users in a buy or sell process via a
mobile device. For instance, when someone buys an Android app or an iPhone app, that person is
engaged in m-commerce. There are a number of content assets that can be bought and sold via a
mobile device such as games, applications, ringtones, subscriptions etc.
How does M-Commerce Work?
Let’s look at some of the points that you need to remember as a business, while engaging in m-
commerce −
Decide Where to Sell
Before you sell your products or services via m-commerce, you need to decide what type of
outlets or stores suit your business best. Let us suppose you have created ringtones − you can sell
them either at specific third-party outlets or to independent aggregators who charge you a
commission for the service.
You can also sell your ringtones on mobile stores or app stores such as Android marketplace or
App store (Apple). These stores are frequently visited by many buyers and hence ideal for
making sales easily and efficiently. Finally, you can also sell via your own mobile store by
creating a mobile website specifically for sales or as by setting-up an m-commerce page on your
main website.
Set up Mobile Billing
Once you have decided where to sell, the next step is to set up your merchant account. For
instance, you can use third-party services such as PayPal. This is ideal for small businesses or
also large companies. A third-party application makes it really easy for you as well as your
customers to make the payments, but then they do charge commission on the transaction.
You can also set-up your own billing and payment gateway, but make sure that you make it
really easy for users. Mobile users do not use keyboards or a mouse so make sure that the design
of your m-commerce site is intuitive, with easy navigation tools and the right display sizes.
Basically, make your m-commerce site optimized for Smartphone users.
Benefits of M-Commerce
The major benefit of engaging in m-commerce is the sheer size of potential sales. The probability
of your potential customers owning a Smartphone is very high, so you can safely assume that
you will get much more positive response from mobile devices than your website. M-commerce
is recommended for every business irrespective of its type, scale, and size.
Advantages of M-commerce
1. Global reach
2. Hassle-free store access
3. Quick & hassle-free extensive order processing
4. Elevate Business Quickly
5. Real-time analysis of user data
Disadvantages of M-commerce
1. Fraud uncertainties & security concerns
2. Lack of familiarity with product/services/brands in rural people
3. It demands technology access
4. Trust issues with Shipment Companies
5. Less customer interaction
Mobile Payment System
An Electronic Payment System is defined as a mode of payment over an electronic network,
such as the Internet. The Indian economy has developed at a rapid pace since the growth of e-
commerce, electronic payments, and digital payments have gone a long way. Electronic
payments have been rising since the implementation of demonetization and will continue to do
so with the current government ensuring that these types of payments are promoted.
Geeky Takeaways:
 Electronic Payment System allows customers to pay for goods and services electronically
without the use of cheques or cash.
 Businesses need a strong and secure electronic payment system in online dealings.
 Electronic Payment System is regulated in India by the RBI.
 The system is safe, speedy, and cost-effective in comparison with paper-based payment
systems.
Types of Electronic Payment System
India, being the fastest-growing economy and a developing nation, has witnessed significant
growth in various types of Electronic Payment Systems, driven by technological advancements
and efforts to promote a cashless economy. The prominent types of Electronic Payment Systems
in India range from the Unified Payments Interface (UPI) to Debit and Credit cards. Listed below
are the types of Electronic Payment Systems:
1. Unified Payments Interface (UPI):
UPI has become a widely adopted and popular electronic payment system in India. It enables
users to link multiple bank accounts to a single mobile application, allowing seamless and instant
fund transfers between individuals and merchants.
2. Mobile Wallets:
Mobile Wallet services like Paytm, PhonePe, and Google Pay have gained widespread
acceptance. Users can load money into these digital wallets and use the balance for various
transactions, including mobile recharge, bill payments, and online shopping.
3. Debit and Credit Cards:
Debit and Credit card usage is prevalent in India, with various banks issuing these cards for
electronic transactions. Cards are commonly used for Point-of-Sale (POS) transactions, online
purchases, and cash withdrawals from ATMs.
4. Immediate Payment Service (IMPS):
IMPS enables instant interbank electronic fund transfers through mobile phones, internet
banking, or ATMs. It is particularly useful for peer-to-peer transactions and small-value
payments.
5. National Electronic Funds Transfer (NEFT):
NEFT is a nationwide electronic payment system that facilitates one-to-one funds transfer
between bank accounts. It operates on a deferred settlement basis and is widely used for both
individual and corporate transactions.
6. Real-Time Gross Settlement (RTGS):
RTGS is another electronic fund transfer system that allows real-time settlement of large-value
transactions. It is typically used for high-value interbank transfers.
7. Prepaid Instruments:
Prepaid Instruments, including prepaid cards and gift cards, provide users with a convenient way
to make electronic payments with a pre-loaded amount.
Advantages of Electronic Payment System
 24/7 Accessibility: Electronic Payments can be made at any time, providing round-the-
clock access to financial transactions.
 Global Accessibility: Users can make payments and transfer funds globally without
being restricted by geographical boundaries.
 Instant Transactions: Electronic Payments are processed quickly, allowing for near-
instantaneous transfer of funds between accounts.
 Faster Settlement: Compared to traditional payment methods, electronic transactions
often result in faster settlement times.
 Record-Keeping and Tracking: Electronic Payment Systems facilitate easy record-
keeping for both businesses and individuals.
 Encryption and Authentication: Electronic Payment Systems employ robust encryption
and authentication protocols to secure transactions and protect sensitive information.
Disadvantages of Electronic Payment System
 Security Concerns: Electronic Payment Systems are susceptible to security breaches,
including hacking, phishing, and identity theft.
 Technical Issues: Electronic Payment Systems rely on technology, and technical glitches
or system failures can disrupt transactions.
 Fraud Risk: Despite security measures, Electronic Payment Systems are not immune to
fraud. Unauthorized transactions, stolen credentials, or fraudulent activities can occur,
leading to financial losses for individuals and businesses.
 Privacy Concerns: Users may be concerned about the collection and storage of personal
information by electronic payment providers.
 Transaction Fees: Some electronic payment systems impose transaction fees, which can
add up over time.
6. What is Mobile Application Security?
We call mobile application security the systems and techniques used to prevent mobile
applications from being exposed to dangers, risks, and unauthorized exchanges. It is a
combination of different approaches and methods that are designed to keep mobile apps secure
and provide resistance to any potential attacks.
Here are some primary factors of mobile application security.
Authentication and Authorization: This refers to the authentication of users and permitting
them to access only the app settings and requisite data they are entitled. These include
approaches like MFA or RBAC which are widely implemented.
Data Encryption: Securing sensitive information by encrypting at rest (stored on the device)
and in transit (transmitted over the networks) is a key step to reduce risks such as unauthorized
access and leakage of data. A powerful encryption algorithm like Advanced Encryption
Standard (AES) is advisable.
Secure Communication Protocols: Mobile apps should be built using communication protocols
such as HTTPS protocol for data transmission between the app and servers. It contributes to
preventing middle man-in-the-middle attack (MITM) where the attackers intrude between two
communication parties and alter it.
Secure Code Practices: The code base of the app must be developed in adherence to secure
coding practices so that the developers can reduce the number of vulnerabilities in the code of
the app. Such things are data input verification to prevent injection attacks, no hardcoded
credentials, and regular auditing with functional testing for security flaws.
Secure Storage: Holding private data including passwords, tokens, and private keys in safety
subject to the device is necessary. Technologies such as utilizing the device's safe storage APIs
and encryption for delicate data give security the needed improvement.
App Permissions: The mobile platforms grant an app access to specific data and device features
through permission-based systems for the whole user control. Apps should only request
permissions when it is necessary and at the same time, the apps should present clear explanations
to users on why some permissions are requisite.
Unit II
1. Introduction to Android Development
Android is a mobile operating system based on a modified version of the Linux kernel and other
open-source software, designed primarily for touchscreen mobile devices such as smartphones
and tablets. Android is developed by a partnership of developers known as the Open Handset
Alliance and commercially sponsored by Google.

Features of Android
Android is a powerful open-source operating system that open-source provides immense features
and some of these are listed below.

 Android Open Source Project so we can customize the OS based on our requirements.
 Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth, etc.
for telephonic conversation or data transfer.
 Using wifi technology we can pair with other devices while playing games or using other
applications.
 It contains multiple APIs to support location-tracking services such as GPS.
 We can manage all data storage-related activities by using the file manager.
 It contains a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play or
record a variety of audio/video.
 It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.
 It supports multimedia hardware control to perform playback or recording using a camera
and microphone.
 Android has an integrated open-source WebKit layout-based web browser to support
User Interfaces like HTML5, and CSS3.
 Android supports multi-tasking means we can run multiple applications at a time and can
switch between them.
 It provides support for virtual reality or 2D/3D Graphics.
Programming Languages used in Developing Android Applications
1. Java
2. Kotlin
Developing the Android Application using Kotlin is preferred by Google, as Kotlin is made
an official language for Android Development, which is developed and maintained by
JetBrains.
Advantages of Android Development
 The Android is an open-source Operating system and hence possesses a vast community
for support.
 The design of the Android Application has guidelines from Google, which becomes
easier for developers to produce more intuitive user applications.
 Fragmentation gives more power to Android Applications. This means the application
can run two activities on a single screen.
 Releasing the Android application in the Google play store is easier when it is compared
to other platforms.
Disadvantages of Android Development
 Fragmentation provides a very intuitive approach to user experience but it has some
drawbacks, where the development team needs time to adjust to the various screen sizes
of mobile smartphones that are now available in the market and invoke the particular
features in the application.
 The Android devices might vary broadly. So the testing of the application becomes more
difficult.
 As the development and testing consume more time, the cost of the application may
increase, depending on the application’s complexity and features.
Android Architecture

1. Applications

An application is the top layer of the android architecture. The pre-installed applications like
camera, gallery, home, contacts, etc., and third-party applications downloaded from the play store
like games, chat applications, etc., will be installed on this layer.

It runs within the Android run time with the help of the classes and services provided by the
application framework.

2. Application framework

Application Framework provides several important classes used to create an Android application.
It provides a generic abstraction for hardware access and helps in managing the user interface with
application resources. Generally, it provides the services with the help of which we can create a
particular class and make that class helpful for the Applications creation.

It includes different types of services, such as activity manager, notification manager, view system,
package manager etc., which are helpful for the development of our application according to the
prerequisite.
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:

o Activity Manager: Controls all aspects of the application lifecycle and activity stack.
o Content Providers: Allows applications to publish and share data with other applications.
o Resource Manager: Provides access to non-code embedded resources such as strings,
colour settings and user interface layouts.
o Notifications Manager: Allows applications to display alerts and notifications to the user.
o View System: An extensible set of views used to create application user interfaces.

3. Application runtime

Android Runtime environment contains components like core libraries and the Dalvik virtual
machine (DVM). It provides the base for the application framework and powers our application
with the help of the core libraries.

Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based virtual
machine designed and optimized for Android to ensure that a device can run multiple instances
efficiently.

It depends on the layer Linux kernel for threading and low-level memory management. The core
libraries enable us to implement android applications using the
standard JAVA or Kotlin programming languages.

4. Platform libraries

The Platform Libraries include various C/C++ core libraries and Java-based libraries such as
Media, Graphics, Surface Manager, OpenGL, etc., to support Android development.

o app: Provides access to the application model and is the cornerstone of all Android
applications.
o content: Facilitates content access, publishing and messaging between applications and
application components.
o database: Used to access data published by content providers and includes SQLite
database, management classes.
o OpenGL: A Java interface to the OpenGL ES 3D graphics rendering API.
o os: Provides applications with access to standard operating system services, including
messages, system services and inter-process communication.
o text: Used to render and manipulate text on a device display.
o view: The fundamental building blocks of application user interfaces.
o widget: A rich collection of pre-built user interface components such as buttons, labels,
list views, layout managers, radio buttons etc.
o WebKit: A set of classes intended to allow web-browsing capabilities to be built into
applications.
o media: Media library provides support to play and record an audio and video format.
o surface manager: It is responsible for managing access to the display subsystem.
o SQLite: It provides database support, and FreeType provides font support.
o SSL: Secure Sockets Layer is a security technology to establish an encrypted link between
a web server and a web browser.
5. Linux Kernel

Linux Kernel is the heart of the android architecture. It manages all the available drivers such as
display, camera, Bluetooth, audio, memory, etc., required during the runtime.

The Linux Kernel will provide an abstraction layer between the device hardware and the other
android architecture components. It is responsible for the management of memory, power, devices
etc. The features of the Linux kernel are:

o Security: The Linux kernel handles the security between the application and the system.
o Memory Management: It efficiently handles memory management, thereby providing the
freedom to develop our apps.
o Process Management: It manages the process well, allocates resources to processes
whenever they need them.
o Network Stack: It effectively handles network communication.
o Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.

Eclipse Installation steps

Installing Eclipse is straightforward. Here are the steps:

Step 1: Download Eclipse

1. Go to the Eclipse Downloads page.


2. Choose the version of Eclipse you need (e.g., Eclipse IDE for Java Developers).
3. Select the appropriate download for your operating system (Windows, macOS, or Linux).

Step 2: Extract the Downloaded File

1. Once the download is complete, locate the downloaded file (usually a .zip or .tar.gz).
2. Extract the contents to a directory of your choice. On Windows, you can right-click and
select "Extract All." On macOS and Linux, you can use built-in tools or command line.

Step 3: Run Eclipse

1. Navigate to the extracted Eclipse folder.


2. Locate the Eclipse executable file (eclipse.exe on Windows, Eclipse.app on macOS, or
eclipse on Linux).
3. Double-click the executable to start Eclipse.
Step 4: Configure Workspace

1. Upon first launch, you'll be prompted to select a workspace. This is the directory where
your projects will be stored.
2. Choose a location or use the default and click "Launch."

Step 5: Install Additional Plugins (Optional)

 You can install additional plugins via the Eclipse Marketplace by going to Help >
Eclipse Marketplace.

Step 6: Set Up Your Development Environment

 Depending on your development needs, you might want to configure settings, add JDKs,
or install other language support.

Step 7: Start Coding

 Create a new project by going to File > New > Project, and you’re ready to start coding!

Android Installation Steps

To set up an Android development environment, you’ll primarily need to install Android Studio.
Here are the steps:

Step 1: Download Android Studio

1. Go to the Android Studio Download page.


2. Click on the download link for your operating system (Windows, macOS, or Linux).
3. Accept the terms and conditions and download the installer.

Step 2: Install Android Studio


Windows:

1. Run the downloaded .exe file.


2. Follow the setup wizard to install Android Studio and the Android SDK.
3. Choose the default options unless you have specific needs.

macOS:

1. Open the downloaded .dmg file.


2. Drag and drop Android Studio into the Applications folder.
3. Launch Android Studio from the Applications folder.
Linux:

1. Unpack the downloaded .zip file into a suitable location.


2. Open a terminal and navigate to the unpacked directory.
3. Run the studio.sh script to start Android Studio.

Step 3: Set Up Android Studio

1. On first launch, choose whether to import settings from a previous installation.


2. Follow the setup wizard, which will guide you through downloading the necessary SDK
components.

Step 4: Install Additional SDK Components (if prompted)

1. During the setup, you may be prompted to install additional components. Ensure you
have the latest SDK tools, platforms, and emulator.
2. You can also configure an Android Virtual Device (AVD) for testing.

Step 5: Configure Android Studio

1. Go to File > Settings (or Android Studio > Preferences on macOS).


2. Set up your SDK path, JDK, and other preferences as needed.

Step 6: Create a New Project

1. Click on Start a new Android Studio project.


2. Choose a project template (e.g., Empty Activity) and click Next.
3. Configure your project settings (name, package name, save location, etc.) and click
Finish.

Step 7: Start Coding

 Once your project is set up, you can start coding your Android app!

Step 8: Run Your App

 You can run your app on an emulator or a physical device. Make sure USB debugging is
enabled on your device if you’re using one.

Additional Tools (Optional)

 Consider installing additional tools like Git for version control, and Java Development
Kit (JDK) if not included in your installation.

Java For Android - Building Your First Android App


Android app development can play a major role in writing the app functionalities using Java
programming. Every activity can be designed with Java programming. Android apps are
developed using the Android Studio IDE, which provides the environment for Java
development for Android programming.

Prerequisites

 Java Programming

 Android Studio in your System

 Emulator for testing App

 Basics of Android

 Basics of XML for UI Design

Key Terminologies

 Activity: Activity can represent the Android screens with a user interface; by default,
create the MainActivity, which is the parent activity of the Android app.

 Layouts: This layer can represent the user interface structure using XML. By default, the
activity_main layout can be created for the MainActivity screen of the Android app.

 Manifest File: This is the information file of the Android app, containing the essential
information about the Android app.

 Resources: This folder contains the Android resource files, which include images, strings,
and other assets used in the Android app.

 Intent: It can send messages that allow components to request functionality from others.

 Views: Views can be defined as the UI elements of the screen, such as buttons, text
fields, images, etc.; they can be displayed in the activity layout.

Step by Step Implementation

We can develop the first simple Android app using Java. In this application, the user gives
the details of their name and education. After that, clicking submit shows the user's details
for another activity.

Step 1: If you want to build the Android app using Java. First, install Android Studio on your
system.
Step 2: Once you have installed Android Studio, open it and create your first new Android
project. For a better understanding, refer to the below image.

Step 3: Once you fill in the details of the project, click on the finish button. After that, select
the activity for use in your app. In our case, we can use an empty activity. Once you select
the activity, click on Next. Refer to the below image.

Step 4: Once the project is completed, the file structure looks like the below image. Now we
are working on creating the first android app using java programming
Step 5: Open activity_main.xml for UI design; it will be located in the layout folder of your
project. In this file, we can design the edit texts and one button for submit.

Go to app > layouts > activity_main.xml and enter the below code.

activity_main.xml

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


<LinearLayout>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10sp"
android:text="Enter Text: "
android:textSize="20sp" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10sp"
android:hint="Enter Text Here" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Here"
android:gravity="center"/>
</LinearLayout>
Step 6: Main Acitivity file is the one shich
MainAcitivity.java
package com.gfg.myapplication;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button1);
EditText editText1 = findViewById(R.id.editText1);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String text = editText1.getText().toString();
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
} }); }}

Step 7: Once runs(refer Android app run) your app is successful. After that, your app can be
opened in the emulator. Finally, you can build your first Android app using Java. Your app looks
like the below image.

Components of an Android Application/ Anatomy of an Android Application

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.

JavaKotlin

public class MainActivity extends Activity {

To read more, refer to the article: Introduction to Activities in Android

Also, to fully understand how to structure an app with Kotlin, from basic components to
advanced architecture, the Android Mastery with Kotlin: Beginner to Advanced course offers
a comprehensive guide to Android app development.

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:

JavaKotlin
public class ServiceName extends Service {

To read more, refer to the article: Services in Android with Example

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.

JavaKotlin

public class contentProviderName extends ContentProvider {

public void onCreate(){}

To read more, refer to the article: Content Providers in Android with Example

4. 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.

To read more, refer to the article: Broadcast Receiver in Android With Example

5. 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.

To read more, refer to the article: Intent and Intent Filters

6. Widgets

These are the small visual application components that you can find on the home screen of the
devices. They are a special variation of Broadcast Receivers that allow us to create dynamic,
interactive application components for users to embed on their Home Screen.
7. 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.

Unit III
BASIC TERMINOLOGIES OF ANDROID
Android is an ‘Open-source’ operating system used to develop an application for mobile devices.
It is a Linux based operating system. Initially, it was tenured by ‘Open alliance handset’ and in
2007 it was occupied by google. The source code published by Google is under the Apache
License version 2.0. Android smartphones are used by millions of people worldwide. Under
researches, researchers say that around 3 million people are using an android smartphone. The
android application completely transforms the way to communicate and interact with each other
even in the miles of distance.
Architecture of Android
The android architecture is the combination of four layers. However, one layer is partitioned into
two sections so, it consists of five sections in all.
 LINUX KERNEL:
It is the lowest layer of android architecture. It serves as the abstraction between the hardware
level of the device and contains all the required hardware drivers.
 LIBRARIES:
It holds libraries for storing the data along the libraries uses for internet security purposes.
 ANDROID RUNTIME:
This section has the libraries which enable the developer to write the code of android application
using any standard programming language.
 APPLICATION FRAMEWORK:
It is the third layer. It serves the services to the application layer in the form of java classes.
 Application:
It is the foremost layer that is used to install the applications in the devices.
Essential Tools for android application development
The most important tools required for application development are:
 JDK: Java Development kit that is the combination of two premier tools JAVA
VIRTUAL MACHINE and JAVA RUNTIME ENVIRONMENT. It helps in compiling
and running the java program.
 ANDROID STUDIO: The primary goal to introduce the android studio is to develop the
android applications in the most stable tool. At first android applications were developed
in eclipse but, app developers face multiple issues in eclipse. Then in 2007, google brings
the android studio that is used particularly introduced for android.
Terminologies Correlated to Android
 XML file
The preeminent file is used for the structure of an android project. It has complete information
about all the components and packages. It initializes the API that is further used by an
application.
 View
It is the component of the User Interface that occupies the rectangular area on the screen.
 Layout
It properly aligned the views on the screen.
 Activity
Activity is a User interface screen through which the user interacts. Users have a right to place
the UI elements in any way according to the Users choice.
 Emulator
The emulator is the virtual device smartphone provided with an android studio. You can run your
created application on the emulator and test its UI and function according to the needs.
 Intent
It acts as a communicating object. You can establish a communication between two or more than
two components as services, broadcast receivers. It is used to start and end the activity and
services components.
 Services
It is used to run the process even in the background. There is no defined UI for service. Any
component can start the service and end the services. You can easily switch between the
applications even if the services are running the background.
 Content Provider
It implemented in two ways:
1. You can use implement the existing content provider in your application.
2. However, you can also create a new content provider that will provide or share the data
with other applications.
There are some basic terminologies used in android. Apart from the mentioned terminologies,
there are other terms which will frequently use with the android. Once you start learning android,
there are a lot of attributes from which you will become aware soon.

What is Context?
A Context gives us information about the current state of an application. It allows us to interact
with Android Components. It allows us to access files and other resources such as pictures,
Activities, Fragments and Services. The Context Class provides access to several resources and
services that are needed to build an Android application including −
 Resources − The resources such as layouts, images and strings which are stored in
resource objects are accessed through the Context.
 System Services − It provides access to system services such as Power Manger,
Notification Manager and Location Manager.
 Preference − The Preference is used to store and retrieve data in key value pair which can
be accessed through Context.
 Asset Manager − It is used to access raw asset files that are packaged with the
application.
 Databases − it provides access to the database used by the application.
What are the two types of Context?
There are two types of context which are as follows −
 Activity Context
 Application Context
In Android, both “Activity” and “Application” are subclasses of the “Context”class, which
provides access to application-specific resources and classes.
The primary difference between both of this context is that “Activity” context is tied to the
lifecycle of an “Activity”, while “Application” context is tied to the lifecycle of the entire
application
What is Activity Context in Android?
When you use any “Activity” context, it is tied to the activity that you are currently in. This
means that if the activity is destroyed, the context will also be destroyed. An activity context
should be used when you need access to resources or classes that are tied to a specific activity,
such as views or resources that are specific to that activity.
Functionalities Provided by Activity Context
 Launching Intent − It is used to start a new activity or services using startActivity() or
startActivityForResult() method.
 Resource Access − It provides access to resources such as strings, layouts and images
through getResources() method.
 View Inflation − Activity Context is used to inflate views with the help of LayoutInflator.
 Dialog Creation − It is used to create Alert Dialog Box and Progress Dialog Box.
 Action Bar − It is used to manage Action Bar such as setting title, icons and navigation.
What is Application Context in Android?
On the other hand, “Application” context is tied to the application itself and remains alive as
long as the application is running. This means that it can be used across multiple activities, and is
useful for accessing global resources and classes that are not tied to any specific activity, such as
shared preferences or database helpers.
Functionalities Provided by Application Context
 Resource Access − It provides access to application resources such as layouts,
dimensions, strings through Resource class.
 Application level - information access − It provides information related to the application
such as package name, application name, application version through Package Manager
class.
 Application-level-Broadcasts − It is used to send and receive application-level broadcasts
using registerReceiver() and sendBroadCast() methods.
 Resource Caching − It uses resources such as layouts and drawables to improve the
application performance.
Difference between Activity Context and Application Context

Activity Context Application Context

Application Context is created when the applic


Activity Context has a shorter life cycle than Application Context.
starts and remains till the application gets
It is created and destroyed with the Activity.
terminated.

Application Context has a longer life cycle and


Activity Context has a shorter life cycle and can be
remains in the memory throughout the lifetime
destroyed with the activity.
of an application.

Application Context is available to the entire


Activity Context is limited to current
application including all activities and
Activity such as Fragments and Views.
their components.

Conclusion
In summary, if you need to access resources that are tied to a specific activity, use the Activity
context. If you need to access resources that are not tied to any specific activity, use the
Application context.
What is Intent in Android?
In Android, it is quite usual for users to witness a jump from one application to another as a part
of the whole process, for example, searching for a location on the browser and witnessing a
direct jump into Google Maps or receiving payment links in Messages Application (SMS) and on
clicking jumping to PayPal or GPay (Google Pay). This process of taking users from one
application to another is achieved by passing the Intent to the system. Intents , in general, are
used for navigating among various activities within the same application, but note, is not limited
to one single application, i.e., they can be utilized from moving from one application to another
as well.
Intents could be Implicit, for instance, calling intended actions, and explicit as well, such as
opening another activity after some operations like onClick or anything else. Below are some
applications of Intents:
1. Sending the User to Another App
2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity
The collaborative nature of Android applications only results in a better user experience. The
question here is if the intent is for an application that is not present in the device, what’s the next
call?
To master the use of intents and other fundamental Android concepts, consider enrolling in
the Android Development with Kotlin course . This course provides comprehensive training
on building Android apps with Kotlin, helping you to implement smooth and efficient
communication between app components.
Some Important Method of Intent and their Description

Methods Description

This is to launch a new activity or get an existing activity to be


Context.startActivity()
action.

This is to start a new service or deliver instructions for an existing


Context.startService()
service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.

Deep Linking
Deep Link is an URL that redirects the device to the API of that Missing Application and then
the service is run on the system to check if a version of that application exists on the device. For
time being, let’s assume that the application is not available on the device and no previous
versions ever existed. This service then makes a call to the Play Store from the device and the
application appears, just a matter of download.
Not deviating from the topic, there are a few examples that already exist in Android Studio for
redirecting to other applications, for example, Dialing Numbers, Sending SMSs, Opening
Settings, etc. Everyday examples include redirecting to YouTube, Maps, WhatsApp, Facebook,
etc. Android community, especially the Kotlin Community is at its zenith every single
impending day. Kotlin has witnessed a huge amount of sudden growth in the past few years and
could be one of the vital tools in the future replacing Java & possibly Julia also.
Types of Android Intents
There are two types of intents in android
1. Implicit
2. Explicit
Implicit Intent
Implicit Intent doesn’t specify the component. In such a case, intent provides information on
available components provided by the system that is to be invoked. For example, you may write
the following code to view the webpage.
Syntax:
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.geeksforgeeks.org/"));
startActivity(intent);
For Example: In the below images, no component is specified, instead, an action is performed
i.e. a webpage is going to be opened. As you type the name of your desired webpage and click on
the ‘CLICK’ button. Your webpage is opened.

Explicit Intent
Explicit Intent specifies the component. In such a case, intent provides the external class to be
invoked.
Syntax:
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
For Example: In the below example, there are two activities (FirstActivity, and
SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ Button in the
FirstActivity, then you move to the SecondActivity. When you click on the ‘GO TO HOME
ACTIVITY’ button in the SecondActivity, then you move to the first activity. This is getting
done through Explicit Intent.
Broadcast Receiver in Android With Example
Broadcast in android is the system-wide events that can occur when the device starts, when a
message is received on the device or when incoming calls are received, or when a device goes to
airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.
Broadcast Receivers allow us to register for the system and application events, and when that
event happens, then the register receivers get notified. There are mainly two types of Broadcast
Receivers:
 Static Broadcast Receivers: These types of Receivers are declared in the manifest file
and works even if the app is closed.
 Dynamic Broadcast Receivers: These types of receivers work only if the app is active
or minimized.
Understanding and implementing Broadcast Receivers is crucial for developing responsive and
well-integrated Android applications. To further enhance your Android development skills using
Kotlin, consider enrolling in the Android Development with Kotlin course . This course offers
in-depth knowledge and practical experience in building Android apps, including working with
essential components like Broadcast Receivers.
Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so
we have implemented dynamic receivers in our sample project given below. There are some
static fields defined in the Intent class which can be used to broadcast different events. We have
taken a change of airplane mode as a broadcast event, but there are many events for which
broadcast register can be used. Following are some of the important system-wide generated
intents:-

Intent Description Of Event

Indicates low battery condition


android.intent.action.BATTERY_LOW :
on the device.

This is broadcast once after the


android.intent.action.BOOT_COMPLETED
system has finished booting

To perform a call to someone


android.intent.action.CALL
specified by the data

Indicates that the date has


android.intent.action.DATE_CHANGED
changed

Indicates that the device has


android.intent.action.REBOOT
been a reboot

The mobile network or wifi


android.net.conn.CONNECTIVITY_CHANGE
connection is changed(or reset)

This indicates that airplane


android.intent.ACTION_AIRPLANE_MODE_CHANGED mode has been switched on or
off.

The two main things that we have to do in order to use the broadcast receiver in our application
are:
Creating the Broadcast Receiver:
class AirplaneModeChangeReceiver:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// logic of the code needs to be written here }}
Registering a BroadcastReceiver:
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
// receiver is the broadcast receiver that we have registered
// and it is the intent filter that we have created
registerReceiver(receiver,it) }
Example
Below is the sample project showing how to create the broadcast Receiver and how to register
them for a particular event and how to use them in the application.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in
Android Studio .
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for
the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Working with the MainActivity file
Go to the MainActivity file and refer to the following code. Below is the code for
the MainActivity file. Comments are added inside the code to understand the code in more
detail.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
AirplaneModeChangeReceiver airplaneModeChangeReceiver = new
AirplaneModeChangeReceiver();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}
Step 4: Create a new class
Go to app > java > your package name(in which the MainActicity is present) > right-click >
New > Kotlin File/Class and name the files as AirplaneModeChangeReceiver . Below is the
code for the AirplaneModeChangeReceiver file. Comments are added inside the code to
understand the code in more detail.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;
public class AirplaneModeChangeReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off", Toast.LENGTH_SHORT).show();
}
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
Android Manifest File in Android
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located
in the root directory of its project hierarchy. The manifest file is an important part of our app
because it defines the structure and metadata of our application, its components, and its
requirements. This file includes nodes for each of the Activities, Services, Content Providers,
and Broadcast Receivers that make the application, and using Intent Filters and Permissions
determines how they coordinate with each other and other applications.
The manifest file also specifies the application metadata, which includes its icon, version
number, themes, etc., and additional top-level nodes can specify any required permissions, and
unit tests, and define hardware, screen, or platform requirements. The manifest comprises a root
manifest tag with a package attribute set to the project’s package. It should also include an
xmls:android attribute that will supply several system attributes used within the file. We use the
versionCode attribute is used to define the current application version in the form of an integer
that increments itself with the iteration of the version due to update. Also, the versionName
attribute is used to specify a public version that will be displayed to the users. To master
managing your Android app’s configuration, including how to handle permissions and app
components with Kotlin, the Android Mastery with Kotlin: Beginner to Advanced course
provides a detailed breakdown of Android’s architecture, including effective usage of the
manifest file.
We can also specify whether our app should install on an SD card of the internal memory using
the installLocation attribute. A typical manifest file looks as:
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.geeksforgeeks"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="preferExternal">

<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="27" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>

</manifest>

A manifest file includes the nodes that define the application components, security settings, test
classes, and requirements that make up the application. Some of the manifest sub-node tags that
are mainly used are:
1. manifest
The main component of the AndroidManifest.xml file is known as manifest. Additionally, the
packaging field describes the activity class’s package name. It must contain an <application>
element with the xmlns:android and package attribute specified.
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.geeksforgeeks">

<!-- manifest nodes -->

<application>

</application>
</manifest>
2. uses-sdk
It is used to define a minimum and maximum SDK version by means of an API Level integer
that must be available on a device so that our application functions properly, and the target SDK
for which it has been designed using a combination of minSdkVersion, maxSdkVersion, and
targetSdkVersion attributes, respectively. It is contained within the <manifest> element.
XML
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="27" />
3. uses-permission
It outlines a system permission that must be granted by the user for the app to function properly
and is contained within the <manifest> element. When an application is installed (on Android
5.1 and lower devices or Android 6.0 and higher), the user must grant the application
permissions.
XML
<uses-permission
android:name="android.permission.CAMERA"
android:maxSdkVersion="18" />
4. application
A manifest can contain only one application node. It uses attributes to specify the metadata for
your application (including its title, icon, and theme). During development, we should include a
debuggable attribute set to true to enable debugging, then be sure to disable it for your release
builds. The application node also acts as a container for the Activity, Service, Content Provider,
and Broadcast Receiver nodes that specify the application components. The name of our custom
application class can be specified using the android:name attribute.
XML
<application
android:name=".GeeksForGeeks"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@drawable/gfgIcon"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@android:style/Theme.Light"
android:debuggable="true"
tools:targetApi="31">

<!-- application nodes -->


</application>
5. uses-library
It defines a shared library against which the application must be linked. This element instructs
the system to add the library’s code to the package’s class loader. It is contained within the
<application> element.
XML
<uses-library
android:name="android.test.runner"
android:required="true" />
6. activity
The Activity sub-element of an application refers to an activity that needs to be specified in the
AndroidManifest.xml file. It has various characteristics, like label, name, theme, launchMode,
and others. In the manifest file, all elements must be represented by <activity>. Any activity that
is not declared there won’t run and won’t be visible to the system. It is contained within the
<application> element.
XML
<activity
android:name=".MainActivity"
android:exported="true">
</activity>
7. intent-filter
It is the sub-element of activity that specifies the type of intent to which the activity, service, or
broadcast receiver can send a response. It allows the component to receive intents of a certain
type while filtering out those that are not useful for the component. The intent filter must contain
at least one <action> element.
XML
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
8. action
It adds an action for the intent-filter. It is contained within the <intent-filter> element.
XML
<action android:name="android.intent.action.MAIN" />
9. category
It adds a category name to an intent-filter. It is contained within the <intent-filter> element.
XML
<category android:name="android.intent.category.LAUNCHER" />
10. uses-configuration
The uses-configuration components are used to specify the combination of input mechanisms
that are supported by our application. It is useful for games that require particular input controls.
XML
<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
android:reqKeyboardType=”qwerty”/>

<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
android:reqKeyboardType=”twelvekey”/>
11. uses-features
It is used to specify which hardware features your application requires. This will prevent our
application from being installed on a device that does not include a required piece of hardware
such as NFC hardware, as follows:
XML
<uses-feature android:name=”android.hardware.nfc” />
12. permission
It is used to create permissions to restrict access to shared application components. We can also
use the existing platform permissions for this purpose or define your own permissions in the
manifest.
XML
<permission
android: name=”com.paad.DETONATE_DEVICE”
android:protectionLevel=“dangerous”
android:label=”Self Destruct”
android:description=”@string/detonate_description”>
</permission>
Unit IV
Android UI Layouts
Layouts in Android is used to define the user interface that holds the UI controls or widgets that
will appear on the screen of an android application or activity screen. Generally, every
application is a combination of View and ViewGroup. As we know, an android application
contains a large number of activities and we can say each activity is one page of the application.
So, each activity contains multiple user interface components and those components are the
instances of the View and ViewGroup. All the elements in a layout are built using a hierarchy
of View and ViewGroup objects.
View
A View is defined as the user interface which is used to create interactive UI components such
as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and
drawing. They are Generally Called Widgets.

View
A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or
ViewGroups and to define the layout properties. They are Generally Called layouts.
ViewGroup
The Android framework will allow us to use UI elements or widgets in two ways:
 Use UI elements in the XML file
 Create elements in the Kotlin file dynamically
Types of Android Layout
 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child
View elements one by one either in a particular direction either horizontally or vertically
based on the orientation property.
 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the
position of child View elements relative to each other like (A to the right of B) or relative
to the parent (fix to the top of the parent).
 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to
specify the position of layout constraints for every child View relative to other views
present. A ConstraintLayout is similar to a RelativeLayout, but having more power.
 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the
position of View elements it contains on the top of each other to display only a single
View inside the FrameLayout.
 Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child
View elements in rows and columns.
 Android Web View: WebView is a browser that is used to display the web pages in our
activity layout.
 Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in
a single column.
 Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of
items in a grid view of rows and columns.

Use UI Elements in the XML file


Here, we can create a layout similar to web pages. The XML layout file contains at least one root
element in which additional layout elements or widgets can be added to build a View hierarchy.
Following is the example:
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http:// schemas.android.com/apk/res/android"
xmlns:tools="http:// schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--EditText with id editText-->


<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Input"
android:inputType="text"/>

<!--Button with id showInput-->


<Button
android:id="@+id/showInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="show"
android:backgroundTint="@color/colorPrimary"
android:textColor="@android:color/white"/>

</LinearLayout>

Load XML Layout File and its elements from an Activity


When we have created the layout, we need to load the XML layout resource from our
activity onCreate() callback method and access the UI element from the XML
using findViewById.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// finding the button


val showButton = findViewById<Button>(R.id.showInput)

// finding the edit text


val editText = findViewById<EditText>(R.id.editText)

Here, we can observe the above code and finds out that we are calling our layout using
the setContentView method in the form of R.layout.activity_main. Generally, during the
launch of our activity, the onCreate() callback method will be called by the android framework
to get the required layout for an activity.
Create elements in the Kotlin file Dynamically
We can create or instantiate UI elements or widgets during runtime by using the custom View
and ViewGroup objects programmatically in the Kotlin file. Below is the example of creating a
layout using LinearLayout to hold an EditText and a Button in an activity programmatically.
Kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import android.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// create the button


val showButton = Button(this)
showButton.setText("Submit")

// create the editText


val editText = EditText(this)

val linearLayout = findViewById<LinearLayout>(R.id.l_layout)


linearLayout.addView(editText)
linearLayout.addView(showButton)

// Setting On Click Listener


showButton.setOnClickListener
{
// Getting the user input
val text = editText.text

// Showing the user input


Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
}
}

Animation in Android with Example


Animation is the process of adding a motion effect to any view, image, or text. With the help of
an animation, you can add motion or can change the shape of a specific view. Animation in
Android is generally used to give your UI a rich look and feel. The animations are basically of
three types as follows:
1. Property Animation
2. View Animation
3. Drawable Animation
Animations add a dynamic touch to Android apps, improving user experience. If you’re looking
to master animations and bring your Kotlin-based apps to life with advanced techniques,
the Android Mastery with Kotlin: Beginner to Advanced course offers in-depth tutorials on
creating engaging animations in Android
1. Property Animation
Property Animation is one of the robust frameworks which allows animation almost everything.
This is one of the powerful and flexible animations which was introduced in Android 3.0.
Property animation can be used to add any animation in the CheckBox, RadioButtons, and
widgets other than any view.
2. View Animation
View Animation can be used to add animation to a specific view to perform tweened animation
on views. Tweened animation calculates animation information such as size, rotation, start point,
and endpoint. These animations are slower and less flexible. An example of View animation can
be used if we want to expand a specific layout in that place we can use View Animation. The
example of View Animation can be seen in Expandable RecyclerView.
3. Drawable Animation
Drawable Animation is used if you want to animate one image over another. The simple way to
understand is to animate drawable is to load the series of drawable one after another to create an
animation. A simple example of drawable animation can be seen in many apps Splash screen on
apps logo animation.
Important Methods of Animation

Methods Description

startAnimation() This method will start the animation.

This method will clear the animation running on a


clearAnimation()
specific view.

Example of Implementation Android Animation


Now we will see the Simple Example to add animations to ImageView. Note that we are going
to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in
Android Studio. Note that select Java as the programming language.
Step 2: Working with the strings.xml file
Strings.xml can be found from the app > res > values > strings.xml.

Below is the snippet for the strings.xml file.


strings.xml
<resources>
<string name="app_name">GFG App</string>
<string name="blink">BLINK</string>
<string name="clockwise">ROTATE</string>
<string name="fade">FADE</string>
<string name="move">MOVE</string>
<string name="slide">SLIDE</string>
<string name="zoom">ZOOM</string>
<string name="stop_animation">STOP ANIMATION</string>
<string name="course_rating">Course Rating</string>
<string name="course_name">Course Name</string>
</resources>

Step 3: Working with the activity_main.xml file


Create ImageView in the activity_main.xml along with buttons that will add animation to the
view. Navigate to the app > res > layout > activity_main.xml.
Below is the code for the activity_main.xml file.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
android:id="@+id/imageview"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:contentDescription="@string/app_name"
android:src="@drawable/gfgimage" />

<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/imageview"
android:layout_marginTop="30dp"
android:orientation="horizontal"
android:weightSum="3">

<!--To start the blink animation of the image-->


<Button
android:id="@+id/BTNblink"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/blink"
android:textColor="@color/white" />

<!--To start the rotate animation of the image-->


<Button
android:id="@+id/BTNrotate"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/clockwise"
android:textColor="@color/white" />

<!--To start the fading animation of the image-->


<Button
android:id="@+id/BTNfade"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/fade"
android:textColor="@color/white" />

</LinearLayout>
<LinearLayout
android:id="@+id/linear2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/linear1"
android:layout_marginTop="30dp"
android:orientation="horizontal"
android:weightSum="3">

<!--To start the move animation of the image-->


<Button
android:id="@+id/BTNmove"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/move"
android:textColor="@color/white" />
<!--To start the slide animation of the image-->
<Button
android:id="@+id/BTNslide"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/slide"
android:textColor="@color/white" />

<!--To start the zoom animation of the image-->


<Button
android:id="@+id/BTNzoom"
style="@style/TextAppearance.AppCompat.Widget.Button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_weight="1"
android:padding="3dp"
android:text="@string/zoom"
android:textColor="@color/white" />

</LinearLayout>

<!--To stop the animation of the image-->


<Button
android:id="@+id/BTNstop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/linear2"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:layout_marginRight="30dp"
android:text="@string/stop_animation" />

</RelativeLayout>

Step 4: Create 6 different types of animation for ImageView


To create new animations we have to create a new directory for storing all our animations.
Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as
“anim”. Inside this directory, we will create our animations. For creating a new anim right click
on the anim directory >> Animation Resource file and give the name to your file. Below is the
code snippet for 6 different animations.
1. Blink Animation
blink_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="500"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>

2. Fade Animation
fade_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator">

<!-- duration is the time for which animation will work-->


<alpha
android:duration="1000"
android:fromAlpha="0"
android:toAlpha="1" />

<alpha
android:duration="1000"
android:fromAlpha="1"
android:startOffset="2000"
android:toAlpha="0" />

</set>

3. Move Animation
move_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">

<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="700" />
</set>

4. Rotate Animation
rotate_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:duration="6000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />

<rotate
android:duration="6000"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="5000"
android:toDegrees="0" />

</set>

5. Slide Animation
slide_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>

6. Zoom Animation
zoom_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >

<scale
android:interpolator="@android:anim/linear_interpolator"
android:duration = "1000"
android:fromXScal = "1"
android:fromYScale = "1"
android:pivotX = "50%"
android:pivotY = "50%"
android:toXScale = "2"
android:toYScale = "2"/>
</set>

Step 5: Working with the MainActivity.java file


Add animation to the ImageView by clicking a specific Button. Navigate to the app > java >
your apps package name >> MainActivity.java.
Below is the implementation of MainActivity file:
MainActivity.javaMainActivity.kt
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

// Declare ImageView and Buttons


ImageView imageView;
Button blinkBTN, rotateBTN, fadeBTN, moveBTN, slideBTN, zoomBTN, stopBTN;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize ImageView and Buttons using their IDs


imageView = findViewById(R.id.imageview);
blinkBTN = findViewById(R.id.BTNblink);
rotateBTN = findViewById(R.id.BTNrotate);
fadeBTN = findViewById(R.id.BTNfade);
moveBTN = findViewById(R.id.BTNmove);
slideBTN = findViewById(R.id.BTNslide);
zoomBTN = findViewById(R.id.BTNzoom);
stopBTN = findViewById(R.id.BTNstop);

// Set up click listener for blink button to start blink animation


blinkBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load blink animation and start it on the ImageView
Animation animation = AnimationUtils.loadAnimation(getApplicationContext()
, R.anim.blink_animation);
imageView.startAnimation(animation);
}
});

// Set up click listener for rotate button to start rotate animation


rotateBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load rotate animation and start it on the ImageView
Animation animation = AnimationUtils.loadAnimation(getApplicationContext()
, R.anim.rotate_animation);
imageView.startAnimation(animation);
}
});

// Set up click listener for fade button to start fade animation


fadeBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load fade animation and start it on the ImageView
Animation animation = AnimationUtils.loadAnimation(getApplicationContext()
, R.anim.fade_animation);
imageView.startAnimation(animation);
}
});

// Set up click listener for move button to start move animation


moveBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load move animation and start it on the ImageView
Animation animation = AnimationUtils.loadAnimation(getApplicationContext()
, R.anim.move_animation);
imageView.startAnimation(animation);
}
});

// Set up click listener for slide button to start slide animation


slideBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load slide animation and start it on the ImageView
Animation animation = AnimationUtils.loadAnimation(getApplicationContext()
, R.anim.slide_animation);
imageView.startAnimation(animation);
}
});

// Set up click listener for zoom button to start zoom animation


zoomBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Load zoom animation and start it on the ImageView
Animation animation = AnimationUtils.loadAnimation(getApplicationContext()
, R.anim.zoom_animation);
imageView.startAnimation(animation);
}
});

// Set up click listener for stop button to clear any ongoing animation
stopBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Clear the animation on the ImageView
imageView.clearAnimation();}});}}
MediaPlayer Class in Android
MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It
can also be used to play audio or video streams over the network. So in this article, the things
discussed are:
 MediaPlayer State diagram
 Creating a simple audio player using MediaPlayer API. Have a look at the following
image. Note that we are going to implement this project using the Kotlin language.
State Diagram of the MediaPlayer Class
 The playing of the audio or video file using MediaPlayer is done using a state machine.
 The following image is the MediaPlayer state diagram.

 In the above MediaPlayer state diagram, the oval shape represents the state of the
MediaPlayer instance resides in.

 There are two types of arcs showing in the state diagram. One with the single arrowhead
represents the synchronous method calls of the MediaPlayer instance and one with the
double arrowhead represents the asynchronous calls.

 The release method which is one of the important element in the MediaPlayer API. This
helps in releasing the Memory resources allocated for the Mediaplayer instance when it is
not needed anymore. Refer to How to Clear or Release Audio Resources in Android? to
know how the memory allocated by the Mediaplayer can be released. So that the memory
management is done accordingly.
 If the stop() method is called using Mediaplayer instance, then it needs to prepared for the
next playback.
 The MediaPlayer can be moved to the specific time position using seekTo() method so
that the MediaPlayer instance can continue playing the Audio or Video playback from
that specified position.
 The focus of the audio playback should be managed accordingly using the AudioManager
service which is discussed in the article How to Manage Audio Focus in Android?.
 The following image is the summarised version of the MediaPlayer state diagram.
Steps to create a simple MediaPlayer in Android
Step 1: Create an empty activity project
 Create an empty activity Android Studio project. And select Kotlin as a programming
language.
 Refer to Android | How to Create/Start a New Project in Android Studio? to know how to
create an empty activity Android Studio project.
Step 2: Create a raw resource folder
 Create a raw resource folder under the res folder and copy one of the .mp3 file extension.
Video Player
00:00
00:16
Step 3: Working with the activity_main.xml file
 The layout of the application consists of three buttons PLAY, PAUSE, and STOP mainly,
which is used to control the state of the MediaPlayer instance.
 Invoke the following code inside the activity_main.xml file to implement the UI.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">

<TextView
android:id="@+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="MEDIA PLAYER"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/headingText"
android:layout_marginTop="16dp"
android:gravity="center_horizontal">

<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:backgroundTint="@color/colorPrimary"
android:text="STOP"
android:textColor="@android:color/white" />

<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:backgroundTint="@color/colorPrimary"
android:text="PLAY"
android:textColor="@android:color/white" />

<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimary"
android:text="PAUSE"
android:textColor="@android:color/white" />

</LinearLayout>

</RelativeLayout>
Output UI:
Step 4: Working with the MainActivity.kt file
 The MediaPlayer instance needs the attributes needs to be set before playing any audio or
video file.
 Invoke the following inside the MainActivity.kt file. Comments are added for better
understanding.
Android Camera Tutorial
Camera is mainly used to capture picture and video. We can control the camera by using
methods of camera api.
Android provides the facility to work on camera by 2 ways:
1. By Camera Intent
2. By Camera API
Understanding basic classes of Camera Intent and API
There are mainly four classes that we are going to discuss.
Intent
By the help of 2 constants of MediaStore class, we can capture picture and video without
using the instance of Camera class.
PauseNext
Mute
Current Time 0:57
/
Duration 18:10
Loaded: 11.01%

Fullscreen
1. ACTION_IMAGE_CAPTURE
2. ACTION_VIDEO_CAPTURE

Camera
It is main class of camera api, that can be used to take picture and video.

SurfaceView
It represents a surface view ore preview of live camera.

MediaRecorder
It is used to record video using camera. It can also be used to record audio files as we have
seen in the previous example of media framework.

Android camera app example by camera intent


In this example, we are writing the simple code to capture image using camera and
displaying the image using imageview.
Unit V
Storage System to Store Data in Android
We employ some form of storage in Android to retain the data permanently (until destroyed)
for future reference. Android Storage System is the name given to these storage systems.
Internal storage, external storage, shared preferences, database, and shared storage are some
of the storage options offered by Android. However, many users are unsure when to use
which storage. So, in this blog, we’ll discover when to use which storage unit. Let’s begin
with the internal storage system. We create several variables for storing various data that are
used in an Android application when developing it. For example, we can utilize a variable to
save data from a remote database and then use that variable throughout the application. These
variables, however, are in-app storage, which means they will be visible to you while the app
is operating. When the application is ended, all of the data in the variable is wiped, and you
are left with nothing. Those variables will be created again when you start the application,
and new values can be saved in those variables.
1. Storage on the Inside
When you install an app on your phone, the Android operating system will give you some
form of secret internal storage where the app can store its private data. No other application
has access to this information. When you uninstall an application, all of the data associated
with it is also removed.
To save a file to the internal storage, you must first obtain it from the internal directory. You
can do this by calling the getFilesDir() or getCacheDir() methods. The getFilesDir() method
returns the absolute path to the directory where files are created on the filesystem.
getCacheDir() returns the absolute path to the filesystem’s application-specific cache
directory.
When Should Internal Storage Be Used?
The internal storage can be used when you need some confidential data for your application.
Another thing to keep in mind is that if your app is storing data that may be utilized by other
apps, you should avoid using internal storage since when you remove the app, all of your
data will be gone, and other apps will never have access to that data. For instance, if your app
is downloading a pdf or storing an image or video that might be used by other apps, you
shouldn’t use internal storage.
2. External Hard Drives
Most Android devices have relatively low internal storage. As a result, we keep our data on
an external storage device. These storage units are accessible to everyone, which means they
can be accessed by all of your device’s applications. You can also access the storage by
connecting your mobile device to a computer. You must obtain the READ EXTERNAL
STORAGE permission from the user in order to gain access to the external storage. As a
result, any application with this permission has access to your app’s data.
When is it appropriate to use external storage?
You can use external storage if the data that your application stores can be used by other
applications. Additionally, if the file stored by your application is huge, such as a video, you
can save it to external storage. You can use external storage to keep the data even after
uninstalling the application.
3. Using the Shared Preferences
You can use the shared preferences if you only have a little amount of data to keep and don’t
want to use the internal storage. Shared Preferences are used to store data in a key-value
format, which means you’ll have one key and the associated data or value will be stored
depending on that key. The data saved in the shared preferences will remain with the
application until you delete it from your phone. All shared preferences will be deleted from
the device if you uninstall the application.
When Should Shared Preferences Be Used?
You can utilize the shared preference in your application when the data you want to store is
relatively little. It’s not a good idea to save more than 100 kilobytes of data in shared
preferences. In addition, if you wish to keep tiny and private data, you can use Android’s
shared preferences.
4. Using Android Database
Databases are collections of data that are organized and saved for future use. Using a
Database Management System, you can store any type of data in your database. All you have
to do is establish the database and use one query to perform all of the operations, such as
insertion, deletion, and searching. The query will be passed to the database, which will return
the desired output. In Android, an SQLite database is an example of a database.
When should you utilize a database?
A database is useful when you need to keep track of structured data. A database can hold any
type of information. So, if your data is large and you want to retrieve it quickly, you can use
a database and store it in a structured style.
Android SQLite Tutorial
SQLite is an open-source relational database i.e. used to perform database operations on
android devices such as storing, manipulating or retrieving persistent data from the database.
It is embedded in android bydefault. So, there is no need to perform any database setup or
administration task.
Here, we are going to see the example of sqlite to store and fetch the data. Data is displayed
in the logcat. For displaying data on the spinner or listview, move to the next page.
SQLiteOpenHelper class provides the functionality to use the SQLite database.
SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation and
version management. For performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.
Constructors of SQLiteOpenHelper class
There are two constructors of SQLiteOpenHelper class.
Methods of SQLiteOpenHelper class
There are many methods in SQLiteOpenHelper class. Some of them are as follows:

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Step by Step Implementation


Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in
Android Studio. Note that select Java as the programming language.

Step 2: Adding permissions to access the storage in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml and add the below code to it.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file.

Below is the code for the activity_main.xml file.

Step 4: Creating a new Java class for performing SQLite operations

Navigate to the app > java > your app’s package name > Right-click on it > New > Java
class and name it as DBHandler and add the below code to it. Comments are added inside the
code to understand the code in more detail.

Step 5: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for
the MainActivity.java file. Comments are added inside the code to understand the code in more
detail.

Content Providers in Android with Example

In Android , Content Providers are a very important component that serves the purpose of a
relational database to store the data of applications. The role of the content provider in the android
system is like a central repository in which data of the applications are stored, and it facilitates
other applications to securely access and modifies that data based on the user requirements.
Android system allows the content provider to store the application data in several ways. Users
can manage to store the application data like images, audio, videos, and personal contact
information by storing them in SQLite Database , in files , or even on a network . In order to
share the data, content providers have certain permissions that are used to grant or restrict the rights
to other applications to interfere with the data.
Content URI

Content URI(Uniform Resource Identifier) is the key concept of Content providers. To access
the data from a content provider, URI is used as a query string.

Structure of a Content URI: content://authority/optionalPath/optionalID

Details of different parts of Content URI:

 content:// – Mandatory part of the URI as it represents that the given URI is a Content
URI.

 authority – Signifies the name of the content provider like contacts, browser, etc. This part
must be unique for every content provider.

 optionalPath – Specifies the type of data provided by the content provider. It is essential
as this part helps content providers to support different types of data that are not related to
each other like audio and video files.

 optionalID – It is a numeric value that is used when there is a need to access a particular
record.

If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based URI.

For a deeper understanding of how to implement Content Providers and other critical Android
components using Kotlin, consider enrolling in the Android Development with Kotlin course .
This course is designed to equip you with the skills necessary to build advanced Android
applications, leveraging Kotlin’s features to enhance your development process.
Operations in Content Provider

Four fundamental operations are possible in Content Provider namely Create , Read , Update ,
and Delete . These operations are often termed as CRUD operations .

 Create: Operation to create data in a content provider.

 Read: Used to fetch data from a content provider.

 Update: To modify existing data.

 Delete: To remove existing data from the storage.

Working of the Content Provider

UI components of android applications like Activity and Fragments use an


object CursorLoader to send query requests to ContentResolver. The ContentResolver object
sends requests (like create, read, update, and delete) to the ContentProvider as a client. After
receiving a request, ContentProvider process it and returns the desired result. Below is a diagram
to represent these processes in pictorial form.

Creating a Content Provider

Following are the steps which are essential to follow in order to create a Content Provider:

 Create a class in the same directory where the that MainActivity file resides and this class
must extend the ContentProvider base class.
 To access the content, define a content provider URI address.

 Create a database to store the application data.

 Implement the six abstract methods of ContentProvider class.

 Register the content provider in AndroidManifest.xml file using <provider> tag .

Following are the six abstract methods and their description which are essential to override
as the part of ContenProvider class:

Abstract Method Description

A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.

To insert a new row in the database of the content provider.


insert()
It returns the content URI of the inserted row.

This method is used to update the fields of an existing row.


update()
It returns the number of rows updated.

This method is used to delete the existing rows.


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail Extension(MIME)


getType()
type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate()
this method immediately to initialise the provider.

Example

The prime purpose of a content provider is to serve as a central repository of data where users can
store and can fetch the data. The access of this repository is given to other applications also but in
a safe manner in order to serve the different requirements of the user. The following are the steps
involved in implementing a content provider. In this content provider, the user can store the name
of persons and can fetch the stored data. Moreover, another application can also access the stored
data and can display the data.

Networking and API Integration in Android

Networking is a great way to connect your application with the world. Yes, before going straight
into our topic, let's first try to find its necessity in your application. Networking is an essential
aspect of modern applications, allowing them to connect with servers, databases, APIs, and other
applications across the globe.

 Efficient Data Exchange: Networking allows you to exchange data efficiently with
browsers, databases, and other applications. APIs provide a modern approach for two or
more disparate applications to communicate or talk to each other.
We will explain this later.

 Global Reach: Through networking, the application meets with a global audience who can
access its resources and services from anywhere in the world.

 Scalability: Networking supports the scalability of the applications.

 Integration: Networking allows applications to integrate with third-party APIs.

API Integration in Android

Most of the applications have some backend interaction. For example:

 The App needs to back up the data.

 The App needs to send and receive data from the back end (web service).

 The App needs to access location-based services to complete some of the functionality.

These functionalities are one of the crucial parts of your app, based on the requirements of the
application. The best way to implement these functionalities is to use a separate interface, which
can act as a storeroom, contains various properties and functions, and provides as per our needs,
such Interfaces are called Application Programming Interfaces (APIs).

Request and Request Libraries

Now slowly we are coming towards the goal of the article. Now the question arisen how can we
access the store-room? Is it available for everyone? If it is, then it might cause security
issues. Well, these APIs have their protocols. HTTP (Hyper Text Transfer Protocol ) and HTTPS
(Hyper Text Transfer Protocol Secure). With these protocols, we can send access requests to these
APIs. We will discuss Restful Web Services here, as nowadays most Android applications
implement networking through Restful Web Services.
Restful Web Services for Android Networking

We can use HTTP methods like GET, POST, PUT, and DELETE to create a new request to these
APIs and can perform the following operations:

 GET: Fetch data from API.

 POST: Adding new data to API.

 PUT: Updating existing data.

 DELETE: Deleting data on the server.

Restful web services often transmit data in JSON or XML format. Let us start with Rest API
integration with Android application.

Project Overview

Last.fm, The world's largest online music service, provides. The Last.fm API allows developers
to access a vast database of music-related data and build their own applications using this data.
We will create our application with this API. The name of our application will
be MusicWiki. MusicWiki is an unofficial Last.fm app that contains information about different
music genres, the albums, artists and tracks listed under the genre or tag.

Goal:

Through this project we will going to cover the following topics:

 Rest API integration with Retrofit Library.

 Learn how to thrott API Documentation.

 Authentication Handling

 Error Handling and Analytics

 Third Party Libraries.

Step by Step Implementation

Step 1: Download the Project

We will download the Project, In order to proceed further.

Step 2: Set up your last.fm account in order to get API key


Step 3: Prepare your Android Application for API integration

Android TelephonyManager Tutorial

The android.telephony.TelephonyManager class provides information about the telephony


services such as subscriber id, sim serial number, phone network type etc. Moreover, you can
determine the phone state etc.

Android TelephonyManager Example

Let's see the simple example of TelephonyManager that prints information of the telephony
services.
activity_main.xml

Drag one textview from the pallete, now the xml file will look like this.

File: activity_main.xml

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity" >

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"

android:layout_marginLeft="38dp"

android:layout_marginTop="30dp"

android:text="Phone Details:" />

</RelativeLayout>

Activity class

Now, write the code to display the information about the telephony services.

File: MainActivity.java

package com.javatpoint.telephonymanager;

import android.os.Bundle;

import android.app.Activity;

import android.content.Context;

import android.telephony.TelephonyManager;

import android.view.Menu;

import android.widget.TextView;

public class MainActivity extends Activity {

TextView textView1;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

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

//Get the instance of TelephonyManager

TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY
_SERVICE);

//Calling the methods of TelephonyManager the returns the information

String IMEINumber=tm.getDeviceId();

String subscriberID=tm.getDeviceId();

String SIMSerialNumber=tm.getSimSerialNumber();

String networkCountryISO=tm.getNetworkCountryIso();

String SIMCountryISO=tm.getSimCountryIso();

String softwareVersion=tm.getDeviceSoftwareVersion();

String voiceMailNumber=tm.getVoiceMailNumber();

//Get the phone type

String strphoneType="";

int phoneType=tm.getPhoneType();

switch (phoneType)
{

case (TelephonyManager.PHONE_TYPE_CDMA):

strphoneType="CDMA";

break;

case (TelephonyManager.PHONE_TYPE_GSM):

strphoneType="GSM";

break;

case (TelephonyManager.PHONE_TYPE_NONE):

strphoneType="NONE";

break;

//getting information if phone is in roaming

boolean isRoaming=tm.isNetworkRoaming();

String info="Phone Details:\n";

info+="\n IMEI Number:"+IMEINumber;

info+="\n SubscriberID:"+subscriberID;

info+="\n Sim Serial Number:"+SIMSerialNumber;

info+="\n Network Country ISO:"+networkCountryISO;

info+="\n SIM Country ISO:"+SIMCountryISO;

info+="\n Software Version:"+softwareVersion;

info+="\n Voice Mail Number:"+voiceMailNumber;


info+="\n Phone Network Type:"+strphoneType;

info+="\n In Roaming? :"+isRoaming;

textView1.setText(info);//displaying the information in the textView

AndroidManifest.xml

You need to provide READ_PHONE_STATE permission in the AndroidManifest.xml file.

File: AndroidManifest.xml

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

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

package="com.javatpoint.telephonymanager"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity >

android:name="com.javatpoint.telephonymanager.MainActivity"

android:label="@string/app_name" >

<intent-filter>

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

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

</intent-filter>

</activity>

</application>

</manifest>

You might also like