Mobile Application Development
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
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.
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.
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."
You can install additional plugins via the Eclipse Marketplace by going to Help >
Eclipse Marketplace.
Depending on your development needs, you might want to configure settings, add JDKs,
or install other language support.
Create a new project by going to File > New > Project, and you’re ready to start coding!
To set up an Android development environment, you’ll primarily need to install Android Studio.
Here are the steps:
macOS:
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.
Once your project is set up, you can start coding your Android 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.
Consider installing additional tools like Git for version control, and Java Development
Kit (JDK) if not included in your installation.
Prerequisites
Java Programming
Basics of Android
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.
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
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.
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
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 {
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
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
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
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
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:-
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" />
</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">
<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">
<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.
</LinearLayout>
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
Methods Description
<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">
</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">
</LinearLayout>
</RelativeLayout>
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">
<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>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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.
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
There are many methods in SQLiteDatabase class. Some of them are as follows:
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.
Navigate to the app > AndroidManifest.xml and add the below code to it.
Navigate to the app > res > layout > activity_main.xml and add the below code to that file.
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.
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.
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.
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.
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 .
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.
Following are the six abstract methods and their description which are essential to override
as the part of ContenProvider class:
A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.
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 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.
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).
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:
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:
Authentication Handling
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"
</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;
TextView textView1;
@Override
setContentView(R.layout.activity_main);
textView1=(TextView)findViewById(R.id.textView1);
TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPHONY
_SERVICE);
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();
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;
boolean isRoaming=tm.isNetworkRoaming();
info+="\n SubscriberID:"+subscriberID;
AndroidManifest.xml
File: AndroidManifest.xml
<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>
</intent-filter>
</activity>
</application>
</manifest>