Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
48 views71 pages

MCAD Ch-1 & Ch-2 Notes by Jimil

The document provides an overview of mobile application development, discussing various types of mobile apps including native, progressive web, and cross-platform applications. It outlines the technologies and frameworks used for development, such as React Native, Flutter, and Ionic, along with their benefits. Additionally, it explains the components of Android applications, including activities, services, content providers, and broadcast receivers, emphasizing the structure and functionality of mobile apps.

Uploaded by

opdynin9
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)
48 views71 pages

MCAD Ch-1 & Ch-2 Notes by Jimil

The document provides an overview of mobile application development, discussing various types of mobile apps including native, progressive web, and cross-platform applications. It outlines the technologies and frameworks used for development, such as React Native, Flutter, and Ionic, along with their benefits. Additionally, it explains the components of Android applications, including activities, services, content providers, and broadcast receivers, emphasizing the structure and functionality of mobile apps.

Uploaded by

opdynin9
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/ 71

Jimilraj Vala Mobile Computing and App Development

Here’s some important information before you begin reading these notes!

 These notes are for learning purposes only and are not affiliated with or provided by
any college faculty.

Highlighting Guide:

Yellow – Main content or definition of the topic.


Blue – Additional points to enhance understanding.
Pink – Key takeaways and important points.
Green – Syntax or code examples.
Jimilraj Vala Mobile Computing and App Development
UNIT-1

Introduction of Mobile Applications

1.1 Introduction

Talking about the mobile applications, the first thing that comes to mind are the apps
like WhatsApp, Instagram, swigy, etc that we use in our everyday life.
Ever thought about how these apps are made? Which technology is used? Let’s discuss
what technologies or frameworks can be used to develop a mobile application.

Mobile Apps are majorly developed for 3 Operating System:


 Android
 IOS
 Windows
There are 3 different ways to develop Mobile apps: –
1. 1st Party Native App development: These types of apps normally run in the
native devices, that is, it runs only in the OS that it is specifically designed for it.
These apps cannot be used on different devices using a different OS. The apps that
are developed for android are normally coded using Java or Kotlin languages. The
IDE normally used for android app development is Android Studio which provides
all features and the apps that are developed for IOS are generally coded in Swift
language or Objective- C.
The IDE suggested for IOS App Development is XCode.

Example:
Here’s an example of a 1st party native app:
A retail company wants to improve the in-store shopping experience for its
customers. They develop a 1st party native app that allows customers to:
 Browse the store’s inventory and product information
 Create a shopping list
 Scan barcodes to view product information and reviews
 Locate items in the store using an interactive map
 Pay for items directly through the app, without having to wait in line at the
register
 The app is only available to the company’s customers and can only be used
in their physical stores. The app is designed to integrate with the company’s
existing systems, such as inventory management and point-of-sale systems.
 This app is developed by the retail company for their own use, to improve
the in-store customer experience, increase sales and gain insights from the
customer’s behaviour.
Jimilraj Vala Mobile Computing and App Development

In this example, the retail company is the 1st party, and the app is a native app, because it is developed
for the specific platform (iOS or Android) and can take full advantage of the device’s capabilities and
features.
2. Progressive web Application: Progressive web apps are essentially a website which runs locally on
your device. The technologies used are Microsoft Blazor, React, Angular JS, Native Script, Iconic.
These technologies normally used for web development propose. The apps’ UI is developed the same
way as they are developed while developing the website. This category has many ups and downs let’s
start with the advantages of Progressive web apps.
Example:
Here’s an example of a Progressive Web App:
A news website wants to provide its users with a better mobile experience. They develop a Progressive
Web App that:
 Allows users to access the website offline by storing content on the user’s device
 Sends push notifications to users to alert them of breaking news
 Can be installed on the user’s home screen like a native app
 Provides a fast and smooth browsing experience
 Has a responsive design that adapts to different screen sizes
 Users can access the PWA by visiting the website on their mobile browser. They are prompted
to install the PWA on their home screen, which allows them to access the website offline and
receive push notifications.
In this example, the news website is the 1st party and the app is a Progressive web app, because it can
be accessed through a web browser and can be installed on the user’s device like a native app. It also
allows users to access the content offline and have a fast and smooth experience.
3. Cross-Platform Application: These are frameworks that allow developing total native applications
which have access to all the native features of IOS and Android but with the same code base. These
apps run on both Android and IOS. So normally the development speeds of these apps are very fast
and the maintenance cost is low. The performance speed is comparatively low to 1st party native apps
but faster than PWA.
Xamarin is Microsoft cross-platform solution that uses the programming languages like .NET, C#, F#.
The IDE preferred is Visual Studio. The UI/UX is totally native giving access to all features. This
technology is having a wide community. And whenever an update is released by Android and IOS the
same updates are released by Microsoft through Visual Studio.
React Native is Facebook’s cross-platform solution which uses the language JavaScript And the
preferred IDE is WebStrome & Visual Studio Code. Same like Xamarin React Native has totally native
UI/UX and gives access to all features. And the updates are released the same day by Facebook as
Android and IOS.
Flutter is Google’s cross-platform solution which uses the language, Dart. The IDE preferred is
Android Studio, IntelliJ IDE, and Visual Studio Code. The UI/UX is bespoke and Flutters has to come
up with their new libraries whenever Android and IOS comes up with an update to mimic those update.
The community is fast growing.
Jimilraj Vala Mobile Computing and App Development

Example:
Here’s an example of a cross-platform application:
A project management company wants to create a project management tool that can be used by teams
on different platforms. They develop a cross-platform application that Can be used on Windows, Mac,
iOS, and Android devices:
 Allows users to create and assign tasks, set deadlines, and track progress
 Integrates with popular tools such as Google Calendar and Trello
 Has a user-friendly interface that works seamlessly across all platforms
 The application can be downloaded from the company’s website or from different app stores
such as App Store, Google Play Store, Microsoft Store, and Mac App Store, depending on the
platform.
This example illustrates how the company developed a project management tool that can be used by
teams on different platforms, Windows, Mac, iOS and Android, which is a cross-platform application.
It allows teams to collaborate and manage their projects seamlessly, regardless of the platform they
use.

1.2 Mobile Development Framework


A mobile development framework is a software framework that is designed to support mobile app
development. It is a software library that provides a fundamental structure to support the development of
applications for a specific environment.
Frameworks can be in three categories: native frameworks for platform-specific development, mobile web
app frameworks, and hybrid apps, which combine the features of both native and mobile web app
frameworks.
Mobile App Development Framework is a library that offers the required fundamental structure to create
mobile applications for a specific environment. In short, it acts as a layout to support mobile app
development. There are various advantages of Mobile App Development frameworks such as cost-
effectiveness, efficiency, and many more. Moreover, mobile application frameworks can be classified
majorly into 3 categories: Native Apps, Web Apps & Hybrid Apps.
Before moving further, let’s take a quick look at all three categories of mobile development apps.

 Native Apps: A Native App is an application specifically designed for a particular platform or
device.
Jimilraj Vala Mobile Computing and App Development

 Web Apps: A Web App is concerned with an application that is designed to deliver web pages on
different web platforms for any device.
 Hybrid Apps: A Hybrid App is a combination of both native & web applications. It can be
developed for any platform from a single code base.

1.2.1 React Native


React Native is one of the most recommended Mobile App Frameworks in the development industry. The
framework, created by Facebook, is an open-source framework that offers you to develop mobile
applications for Android & iOS platforms. The React Native framework is based on React and JavaScript
that aims to develop native applications over hybrid applications that run on a web view. Moreover, it is a
cross-platform development framework that uses a single code base for both Android & iOS applications.
Some of the major benefits of React Native are mentioned below:
 Code Re-usability & Cost-Effective
 Compatible with third-party plugins
 Re-usable components for optimal performance
 Provides hot deployment features
 Ease of Maintenance
1.2.2 Flutter
Flutter, developed by Google, is a UI toolkit to build native applications for mobile apps, desktop & web
platforms. Flutter is a cross-platform mobile app development framework that works on one code base
to develop Android as well as iOS applications. The framework provides a large range of fully customizable
widgets that helps to build native applications in a shorter span. Moreover, Flutter uses the 2D rendering
engine called Skia for developing visuals and its layered architecture ensures the effective functioning of
components. Some of the major benefits of Flutter are mentioned below:
 Provides Full Native Performance
 Flexible User interface (UI)
 Provides Strong Widget Support
 Offers Built-in Material Design
 Fast Application Development
1.2.3 Ionic
Ionic, developed in 2013, is an open-source framework that allows you to build cross-platform for mobile
apps using web technologies like HTML, CSS & JavaScript. The application built through the Ionic
framework can work on Android, iOS & Windows platforms. The framework offers numerous default UI
components such as forms, action sheets, filters, navigation menus, and many more for attractive and
worthwhile design. Moreover, Ionic has its own command-line interface and various other in-built features
such as Ionic Native, Cordova-Based App packages, etc. Some of the major benefits of Ionic for mobile
development apps are mentioned below: Refer all for better understanding
 Faster Application Development.
Jimilraj Vala Mobile Computing and App Development

 Availability of Cordova Plugins


 Built-in UI components
 Platform Independent
 Based on AngularJS
Android Framework(Platform) Make sure to refer this whole figure including all components
Android is an open source, Linux-based software stack created for a wide array of devices and form factors.
Figure shows the major components of the Android Framework/Platform.

It follows bottom-up approach.


Jimilraj Vala Mobile Computing and App Development

Figure. The Android software stack.


Linux kernel
The foundation of the Android platform is the Linux kernel. For example, the Android Runtime (ART) relies
on the Linux kernel for underlying functionalities such as threading and low-level memory management.
Using a Linux kernel lets Android take advantage of key security features and lets device manufacturers
develop hardware drivers for a well-known kernel.
Hardware abstraction layer (HAL)
The hardware abstraction layer (HAL) provides standard interfaces that expose device hardware capabilities
to the higher-level Java API framework. The HAL consists of multiple library modules, each of which
implements an interface for a specific type of hardware component, such as
the camera or Bluetooth module. When a framework API makes a call to access device hardware, the
Android system loads the library module for that hardware component.
Android runtime
For devices running Android version 5.0 (API level 21) or higher, each app runs in its own process and with
its own instance of the Android Runtime (ART). ART is written to run multiple virtual machines on low-
memory devices by executing Dalvik Executable format (DEX) files, a bytecode format designed
specifically for Android that's optimized for a minimal memory footprint. Build tools, such as d8, compile
Java sources into DEX bytecode, which can run on the Android platform.
Some of the major features of ART include the following: Refer the points once!
 Ahead-of-time (AOT) and just-in-time (JIT) compilation
 Optimized garbage collection (GC)
 On Android 9 (API level 28) and higher, conversion of an app package's DEX files to more compact
machine code
 Better debugging support, including a dedicated sampling profiler, detailed diagnostic exceptions
and crash reporting, and the ability to set watchpoints to monitor specific fields
Prior to Android version 5.0 (API level 21), Dalvik was the Android runtime. If your app runs well on ART,
then it can work on Dalvik as well, but the reverse might not be true.
Android also includes a set of core runtime libraries that provide most of the functionality of the Java
programming language, including some Java 8 language features, that the Java API framework uses.
Native C/C++ libraries
Many core Android system components and services, such as ART and HAL, are built from native code
that requires native libraries written in C and C++. The Android platform provides Java framework APIs to
expose the functionality of some of these native libraries to apps. For example, you can access OpenGL
ES through the Android framework’s Java OpenGL API to add support for drawing and manipulating 2D
and 3D graphics in your app.
If you are developing an app that requires C or C++ code, you can use the Android NDK to access some of
these native platform libraries directly from your native code.
Java API framework
Jimilraj Vala Mobile Computing and App Development

The entire feature-set of the Android OS is available to you through APIs written in the Java language.
These APIs form the building blocks you need to create Android apps by simplifying the reuse of core,
modular system components and services, which include the following: These points are important! Refer all
 A rich and extensible view system you can use to build an app’s UI, including lists, grids, text boxes,
buttons, and even an embeddable web browser
 A resource manager, providing access to non-code resources such as localized strings, graphics, and
layout files
 A notification manager that enables all apps to display custom alerts in the status bar
 An activity manager that manages the lifecycle of apps and provides a common navigation back
stack
 Content providers that enable apps to access data from other apps, such as the Contacts app, or to
share their own data
Developers have full access to the same framework APIs that Android system apps use.
System apps
Android comes with a set of core apps for email, SMS messaging, calendars, internet browsing, contacts,
and more. Apps included with the platform have no special status among the apps the user chooses to install.
So, a third-party app can become the user's default web browser, SMS messenger, or even the default
keyboard. Some exceptions apply, such as the system's Settings app.
The system apps function both as apps for users and to provide key capabilities that developers can access
from their own app. For example, if you want your app to deliver SMS messages, you don't need to build
that functionality yourself. You can instead invoke whichever SMS app is already installed to deliver a
message to the recipient you specify.

1.3 Components of 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.
class MainActivity : AppCompatActivity() {
}
Jimilraj Vala Mobile Computing and 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:
class ServiceName : 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.
class contentProviderName : ContentProvider()
{ override fun onCreate(): Boolean {}
}
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.

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.

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.
Jimilraj Vala Mobile Computing and App Development

1.4 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.
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:

Example: XML Refer the main tags and attributes

<?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.application"
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"
Jimilraj Vala Mobile Computing and App Development

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 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.application">
<!-- 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.
Jimilraj Vala Mobile Computing and App Development

<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.
<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.
<application
android:name=".Application"
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.
<uses-library
Jimilraj Vala Mobile Computing and App Development

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.
<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.
<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.
<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.
<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.
<uses-configuration
android:reqTouchScreen=”finger”
android:reqNavigation=”trackball”
android:reqHardKeyboard=”true”
Jimilraj Vala Mobile Computing and App Development

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
<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.
<permission
android: name=”com.paad.DETONATE_DEVICE”
android:protectionLevel=“dangerous”
android:label=”Self Destruct”
android:description=”@string/detonate_description”>
</permission>

1.5. Permission Model of Android


If your app offers functionality that might require access to restricted data or restricted actions, determine
whether you can get the information or perform the actions without needing to declare permissions. You can
fulfill many use cases in your app, such as taking photos, pausing media playback, and displaying relevant
ads, without needing to declare any permissions.

If you decide that your app must access restricted data or perform restricted actions to fulfill a use case, declare
the appropriate permissions. Some permissions, known as install-time permissions, are automatically granted
when your app is installed. Other permissions, known as runtime permissions, require your app to go a step
further and request the permission at runtime.
Jimilraj Vala Mobile Computing and App Development

Refer and understand properly!

Types of permission:
1. Install-time permissions
Install-time permissions give your app limited access to restricted data or let your app perform restricted
actions that minimally affect the system or other apps. When you declare install-time permissions in your app,
an app store presents an install-time permission notice to the user when they view an app's details page, as
shown in figure 2. The system automatically grants your app the permissions when the user installs your app.

2.Normal permissions
These permissions allow access to data and actions that extend beyond your app's sandbox but present very
little risk to the user's privacy and the operation of other apps.

3. Signature permissions
The system grants a signature permission to an app only when the app is signed by the same certificate as the
app or the OS that defines the permission.
Applications that implement privileged services, such as autofill or VPN services, also make use of signature
permissions. These apps require service-binding signature permissions so that only the system can bind to the
services.

4. Runtime permissions
Runtime permissions, also known as dangerous permissions, give your app additional access to restricted data
or let your app perform restricted actions that more substantially affect the system and other apps. Therefore,
you need to request runtime permissions in your app before you can access the restricted data or perform
restricted actions. Don't assume that these permissions have been previously granted—check them and, if
needed, request them before each access.
When your app requests a runtime permission, the system presents a runtime permission prompt.
Jimilraj Vala Mobile Computing and App Development

Many runtime permissions access private user data, a special type of restricted data that includes potentially
sensitive information. Examples of private user data include location and contact information.

5.Special permissions
Special permissions correspond to particular app operations. Only the platform and OEMs can define special
permissions. Additionally, the platform and OEMs usually define special permissions when they want to
protect access to particularly powerful actions, such as drawing over other apps.
The Special app access page in system settings contains a set of user-toggleable operations. Many of these
operations are implemented as special permissions.

6. Permission groups
Permissions can belong to permission groups. Permission groups consist of a set of logically related
permissions. For example, permissions to send and receive SMS messages might belong to the same group,
as they both relate to the application's interaction with SMS.
Permission groups help the system minimize the number of system dialogs that are presented to the user when
an app requests closely related permissions. When a user is presented with a prompt to grant permissions for
an application, permissions belonging to the same group are presented in the same interface. However,
permissions can change groups without notice, so don't assume that a particular permission is grouped with
any other permission.

1.6. Downloading and Installing SDK


Install the SDK
1. Click Tools > SDK Manager.
2. In the SDK Platforms tab, select Android UpsideDownCake Preview.
3. In the SDK Tools tab, select Android SDK Build-Tools 29.
4. Click OK to install the SDK.

1.7. Exploring the Development Environment


Android Studio is the official Integrated Development Environment (IDE) for Android app development.
Android Studio offers even more features that enhance your productivity when building Android apps, such
as:
 A flexible Gradle-based build system
 A fast and feature-rich emulator
 A unified environment where you can develop for all Android devices
 Live Edit to update composables in emulators and physical devices in real time
Jimilraj Vala Mobile Computing and App Development

 Code templates and GitHub integration to help you build common app features and import sample
code
 Extensive testing tools and frameworks
 Lint tools to catch performance, usability, version compatibility, and other problems
 C++ and NDK support
 Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and
App Engine.
Make sure to refer all directories
Get to know the Android Studio UI especially the Gradle, xml, and kotlin

1. Toolbar: Carry out a wide range of actions, including running your app and launching Android tools.
2. Navigation bar: Navigate through your project and open files for editing. It provides a more compact
view of the structure visible in the Project window.
3. Editor window: Create and modify code. Depending on the current file type, the editor can change.
For example, when viewing a layout file, the editor displays the Layout Editor.
4. Tool window bar: Use the buttons on the outside of the IDE window to expand or collapse individual
tool windows.
Jimilraj Vala Mobile Computing and App Development

5. Tool windows: Access specific tasks like project management, search, version control, and more. You
can expand them and collapse them.
6. Status bar: Display the status of your project and the IDE itself, as well as any warnings or messages.

Tool windows

To expand or collapse a tool window, click the tool’s name in the tool window bar. You can
also drag, pin, unpin, attach, and detach tool windows.

To return to the default layout of the current tool window, click Window > Restore Default
Layout. To customize your default layout, click Window > Store Current Layout as Default.

To show or hide the entire tool window bar, click the window in the bottom left-hand
corner of the Android Studio window.

To locate a specific tool window, hover over the window icon and select the tool window
from the menu.

1.8 Build Your First Android App in Kotlin


1. Install Android Studio
2. Create your first project
click Start a new Android Studio project.

Select Basic Activity (not the default). Click Next.


Jimilraj Vala Mobile Computing and App Development

Give your application a name, such as My First App.


Make sure the Language is set to Kotlin.
Leave the defaults for the other fields.
Click Finish.
Get your screen set up
If there's a Gradle window open on the right side, click on the minimize button (—) in the
upper right corner.

Depending on the size of your screen, consider resizing the pane on the left showing the project
folders to take up less space.
Jimilraj Vala Mobile Computing and App Development

Explore the project structure and layout


Jimilraj Vala Mobile Computing and App Development

Double-click the app (1) folder to expand the hierarchy of app files. (See (1) in the screenshot.)
If you click Project (2), you can hide or show the Project view.
The current Project view selection is Project > Android.
Create a virtual device (emulator)
In Android Studio, select Tools > AVD Manager, or click the AVD Manager icon in the toolbar.
1ef215721ed1bd47.png
Click +Create Virtual Device. (If you have created a virtual device before, the window shows
all of your existing devices and the +Create Virtual Device button is at the bottom.) The Select
Hardware window shows a list of pre-configured hardware device definitions.
Choose a device definition, such as Pixel 2, and click Next. (For this codelab, it really doesn't
matter which device definition you pick).
In the System Image dialog, from the Recommended tab, choose the latest release. (This does
matter.)
If a Download link is visible next to a latest release, it is not installed yet, and you need to
download it first. If necessary, click the link to start the download, and click Next when it's
done. This may take a while depending on your connection speed.
In the next dialog box, accept the defaults, and click Finish.
The AVD Manager now shows the virtual device you added.
If the Your Virtual Devices AVD Manager window is still open, go ahead and close it.

Run your app on your new emulator]

In Android Studio, select Run > Run ‘app', or click the Run icon in the toolbar. The icon
changes once your app is running
In Run > Select Device, under Available devices, select the virtual device that you just
configured. A dropdown menu also appears in the toolbar.

Once your app builds and the emulator is ready, Android Studio uploads the app to the
emulator and runs it. You should see your app as shown in the following screenshot.
Jimilraj Vala Mobile Computing and App Development
Jimilraj Vala Mobile Computing and App Development

UNIT-2

Designing Application

2.1 Working with activity

In Android, an activity is referred to as one screen in an application. It is very similar to a single window of
any desktop application. An Android app consists of one or more screens or activities.
Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when a new
activity starts, the previous one always remains below it. There are four stages of an activity.
If an activity is in the foreground of the screen i.e at the top of the stack, then it is said to be active or running.
This is usually the activity that the user is currently interacting with.
If an activity has lost focus and a non-full-sized or transparent activity has focused on top of your activity. In
such a case either another activity has a higher position in multi-window mode or the activity itself is not
focusable in the current window mode. Such activity is completely alive.
If an activity is completely hidden by another activity, it is stopped or hidden. It still retains all the information,
and as its window is hidden thus it will often be killed by the system when memory is needed elsewhere.
The system can destroy the activity from memory by either asking it to finish or simply killing its process.
When it is displayed again to the user, it must be completely restarted and restored to its previous state.
For each stage, android provides us with a set of 7 methods that have their own significance for each stage in
the life cycle. The image shows a path of migration whenever an app switches from one state to another.

Activity Lifecycle in Android:


There are 7 different method in activity lifecycle: –
1. onCreate(): It is called when the activity is first created. This is where all the static work is done like
creating views, binding data to lists, etc. This method also provides a Bundle containing its previous
frozen state, if there was one.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


{ super.onCreate(savedInstanceState)

// Bundle containing previous frozen state


Jimilraj Vala Mobile Computing and App Development

setContentView(R.layout.activity_main)

// The content view pointing to the id of layout


// in the file activity_main.xml
val toast = Toast.makeText(applicationContext, "onCreate Called",
Toast.LENGTH_LONG).show()
}
}
Refer this diagram. It's one of most important topic

}
Jimilraj Vala Mobile Computing and App Development

2. onStart(): It is invoked when the activity is visible to the user. It is followed by onResume() if the
activity is invoked from the background. It is also invoked after onCreate() when the activity is first
started.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


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

val toast = Toast.makeText(applicationContext, "onCreate Called",


Toast.LENGTH_LONG).show()
}

override fun onStart()


{ super.onStart()
// It will show a message on the screen
// then onStart is invoked
val toast = Toast.makeText(applicationContext, "onStart Called",
Toast.LENGTH_LONG).show()
}
}

3. onRestart(): It is invoked after the activity has been stopped and prior to its starting stage and thus is
always followed by onStart() when any activity is revived from background to on-screen.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
Jimilraj Vala Mobile Computing and App Development

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


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

val toast = Toast.makeText(applicationContext, "onCreate Called",


Toast.LENGTH_LONG).show()
}

override fun onRestart()


{ super.onRestart()
// It will show a message on the screen
// then onRestart is invoked
val toast = Toast.makeText(applicationContext, "onRestart Called",
Toast.LENGTH_LONG).show()
}
}

4. onResume(): It is invoked when the activity starts interacting with the user. At this point, the activity
is at the top of the activity stack, with a user interacting with it. Always followed by onPause() when
the activity goes into the background or is closed by the user.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


{ super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Jimilraj Vala Mobile Computing and App Development

val toast = Toast.makeText(applicationContext, "onCreate Called",


Toast.LENGTH_LONG).show()
}

override fun onResume()


{ super.onResume()
// It will show a message on the screen
// then onResume is invoked
val toast = Toast.makeText(applicationContext, "onResume Called",
Toast.LENGTH_LONG).show()
}
}

5. onPause(): It is invoked when an activity is going into the background but has not yet been killed. It
is a counterpart to onResume(). When an activity is launched in front of another activity, this callback
will be invoked on the top activity (currently on screen). The activity, under the active activity, will
not be created until the active activity’s onPause() returns, so it is recommended that heavy processing
should not be done in this part.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


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

val toast = Toast.makeText(applicationContext, "onCreate Called",


Toast.LENGTH_LONG).show()
}

override fun onPause()


{ super.onPause()
Jimilraj Vala Mobile Computing and App Development

// It will show a message on the screen


// then onPause is invoked
val toast = Toast.makeText(applicationContext, "onPause Called",
Toast.LENGTH_LONG).show()
}
}

6. onStop(): It is invoked when the activity is not visible to the user. It is followed by onRestart() when
the activity is revoked from the background, followed by onDestroy() when the activity is closed or
finished, and nothing when the activity remains on the background only.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


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

val toast = Toast.makeText(applicationContext, "onCreate Called",


Toast.LENGTH_LONG).show()
}

override fun onStop()


{ super.onStop()
// It will show a message on the screen
// then onStop is invoked
val toast = Toast.makeText(applicationContext, "onStop Called",
Toast.LENGTH_LONG).show()
}
}
Jimilraj Vala Mobile Computing and App Development

7. onDestroy():The final call received before the activity is destroyed. This can happen either because
the activity is finishing (when finish() is invoked) or because the system is temporarily destroying this
instance of the activity to save space.
Example:
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)


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

val toast = Toast.makeText(applicationContext, "onCreate Called",


Toast.LENGTH_LONG).show()
}

override fun onDestroy()


{ super.onDestroy()
// It will show a message on the screen
// then onDestroy is invoked
val toast = Toast.makeText(applicationContext, "onDestroy Called",
Toast.LENGTH_LONG).show()
}
}

2.2 Redirecting to another activity and passing data


How to “Send the data from one activity to second activity using Intent”. In this example, we have two
activities, activity_first which are the source activity, and activity_second which is the destination activity.
We can send the data using the putExtra() method from one activity and get the data from the second activity
using the getStringExtra() method.

Step by Step Implementation:


Step1: Create a New Project in Android Studio
Jimilraj Vala Mobile Computing and App Development

Step2: Working with the XML Files


Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for
the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Open the “activity_first_activity.xml” file and add the following widgets in a Relative Layout.
 An EditText to Input the message
 A Button to send the data
Also, Assign the ID to each component along with other attributes as shown in the image and the code
below. The assigned ID on a component helps that component to be easily found and used in the Java/Kotlin
files.

Syntax:
 android:id="@+id/id_name"
 Send Button: send_button_id

 input EditText: send_text_id


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=".first_activity">

<EditText
android:id="@+id/send_text_id"
Jimilraj Vala Mobile Computing and App Development

android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:hint="Input"
android:textSize="25dp"
android:textStyle="bold" />

<Button
android:id="@+id/send_button_id"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="150dp"
android:text="send"
android:textStyle="bold" />
</RelativeLayout>

This will make the UI of the Application


Jimilraj Vala Mobile Computing and App Development

Step3: 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. Now, after the UI, this step will
create the Backend of the App. For this, open the “first_activity” file and instantiate the components made
in the XML file (EditText, send Button) using findViewById() method. This method binds the created object
to the UI Components with the help of the assigned ID.
Syntax: General
ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);
Syntax: for components used is as follows:
Button send_button= findViewById(R.id.send_button_id);
send_text = findViewById(R.id.send_text_id);
Setting up the Operations for the Sending and Receiving of Data.
These Operations are as follows:
Add the listener to the send button and this button will send the data.
This is done as follows:
send_button.setOnClickListener(v -> {}
after clicking this button following operation will be performed. Now create the String type variable to store
the value of EditText which is input by the user. Get the value and convert it to a string.
This is done as follows:
String str = send_text.getText().toString();
Now create the Intent object First_activity.java class to Second_activity class.
This is done as follows:
Intent intent = new Intent(getApplicationContext(), Second_activity.class);
where getApplicationContext() will fetch the current activity. Put the value in the putExtra method in the
key-value pair then start the activity.
This is done as follows:
intent.putExtra("message_key", str);
startActivity(intent);
where “str” is the string value and the key is “message_key” this key will use to get the str value

Example:
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
Jimilraj Vala Mobile Computing and App Development

import androidx.appcompat.app.AppCompatActivity

class first_activity : AppCompatActivity() {

// define the variable


lateinit var send_button: Button
lateinit var send_text: EditText

override fun onCreate(savedInstanceState: Bundle?)


{ super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first_activity)

send_button = findViewById(R.id.send_button_id)
send_text = findViewById(R.id.send_text_id)

// add the OnClickListener in sender button after clicked this button following Instruction will run
send_button.setOnClickListener {
// get the value which input by user in EditText and convert it to string
val str = send_text.text.toString()
// Create the Intent object of this class Context() to Second_activity class
val intent = Intent(applicationContext, Second_activity::class.java)
// now by putExtra method put the value in key, value pair key is
// message_key by this key we will receive the value, and put the string
intent.putExtra("message_key", str)
// start the Intent
startActivity(intent)
}
}
}

Step4: Creating Second_Activity to Receive the Data.


The steps to create the second activity are as follows:
Jimilraj Vala Mobile Computing and App Development

android project > File > new > Activity > Empty Activity

Step5: Working with the Second XML File


Add TextView to display the received messages. assign an ID to Textview.
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="org.geeksforgeeks.navedmalik.sendthedata.Second_activity">
<TextView
android:id="@+id/received_value_id"
android:layout_width="300dp"
Jimilraj Vala Mobile Computing and App Development

android:layout_height="50dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:textSize="40sp"
android:textStyle="bold"
android:layout_marginStart="40dp" />
</RelativeLayout>

The Second Activity is shown below:

Step6: Working with the SecondActivity File


Define the TextView variable, use findViewById() to get the TextView as shown above.
receiver_msg = (TextView) findViewById(R.id.received_value_id);
Now In the second_activity.java file create the object of getIntent to receive the value in String type variable
by the getStringExtra method using message_key.
Intent intent = getIntent();
String str = intent.getStringExtra("message_key");
The received value set in the TextView object of the second activity XML file
receiver_msg.setText(str);

Kotlin:
import android.os.Bundle
import android.widget.TextView
Jimilraj Vala Mobile Computing and App Development

import androidx.appcompat.app.AppCompatActivity

class Second_activity : AppCompatActivity() {

lateinit var receiver_msg: TextView

override fun onCreate(savedInstanceState: Bundle?)


{ super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second_activity)

receiver_msg = findViewById(R.id.received_value_id)
// create the get Intent object
val intent = intent
// receive the value by getStringExtra() method and
// key must be same which is send by first activity
val str = intent.getStringExtra("message_key")
// display the string into textView
receiver_msg.text = str
}
}

Toast

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space
required for the message and the current activity remains visible and interactive. Toasts automatically
disappear after a timeout.

For example, clicking Send on an email triggers a "Sending message..." toast, as shown in the following
screen capture:
Jimilraj Vala Mobile Computing and App Development

If your app targets Android 12 (API level 31) or higher, its toast is limited to two lines of text and shows
the application icon next to the text. Be aware that the line length of this text varies by screen size, so it's
good to make the text as short as possible.

Instantiate a Toast object

Use the makeText() method, which takes the following parameters:

1. The activity Context.

2. The text that should appear to the user.

3. The duration that the toast should remain on the screen.

The makeText() method returns a properly initialized Toast object.

Show the toast

To display the toast, call the show() method, as demonstrated in the following example:

val text = "Hello toast!"


val duration = Toast.LENGTH_SHORT

val toast = Toast.makeText(this, text, duration) // in Activity


toast.show()

2.3 Layouts:
Android Layout 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.

Size, padding, and margins


Jimilraj Vala Mobile Computing and App Development

The size of a view is expressed with a width and height. A view has two pairs of width and height values.

The first pair is known as measured width and measured height. These dimensions define how big a view
wants to be within its parent. You can obtain the measured dimensions by
calling getMeasuredWidth() and getMeasuredHeight().

The second pair is known as width and height, or sometimes drawing width and drawing height. These
dimensions define the actual size of the view on screen, at drawing time and after layout. These values might,
but don't have to, differ from the measured width and height. You can obtain the width and height by
calling getWidth() and getHeight().

To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the
left, top, right and bottom parts of the view. You can use padding to offset the content of the view by a specific
number of pixels. For instance, a left padding of two pushes the view's content two pixels to the right of the
left edge. You can set padding using the setPadding(int, int, int, int) method and query it by
calling getPaddingLeft(), getPaddingTop(), getPaddingRight(), and getPaddingBottom().

Although a view can define a padding, it doesn't support margins. However, view groups do support margins.
See ViewGroup and ViewGroup.MarginLayoutParams for more information.

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.

1. LinearLayout:
Jimilraj Vala Mobile Computing and App Development

Android 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. We can specify the linear
layout orientation using android:orientation attribute.

All the child elements arranged one by one in multiple rows and multiple columns.

1. Horizontal list: One row, multiple columns.

2. Vertical list: One column, multiple rows.

LinearLayout in activity_main.xml file:


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

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="16dp"

android:text="Enter your name here:"

android:textSize="24dp"

android:id="@+id/txtVw"/>

<EditText

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="16dp"

android:hint="Name"
Jimilraj Vala Mobile Computing and App Development

android:inputType="text"/>

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

2. RelativeLayout: Refer all attributes

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

Instead of using LinearLayout, we have to use RelativeLayout to design the user interface and keep our
hierarchy flat because it improves the performance of the application.

Attributes Description
layout_alignParentLeft It is set “true” to match the left edge of view to the left edge of parent.
layout_alignParentRight It is set “true” to match the right edge of view to the right edge of parent.
layout_alignParentTop It is set “true” to match the top edge of view to the top edge of parent.
layout_alignParentBottom It is set “true” to match the bottom edge of view to the bottom edge of
parent.
layout_alignLeft It accepts another sibling view id and align the view to the left of the
specified view id
layout_alignRight It accepts another sibling view id and align the view to the right of the
specified view id.
layout_alignStart It accepts another sibling view id and align the view to start of the
specified view id.
layout_alignEnd It accepts another sibling view id and align the view to end of
specified view id.
layout_centerInParent When it is set “true”, the view will be aligned to the center of parent.
layout_centerHorizontal When it is set “true”, the view will be horizontally centre aligned
within its parent.
layout_centerVertical When it is set “true”, the view will be vertically centre aligned within
its parent.
layout_toLeftOf It accepts another sibling view id and places the view left of the
specified view id.
layout_toRightOf It accepts another sibling view id and places the view right of the
specified view id.
Jimilraj Vala Mobile Computing and App Development

layout_toStartOf It accepts another sibling view id and places the view to start of the
specified view id.
layout_toEndOf It accepts another sibling view id and places the view to end of the
specified view id.
layout_above It accepts another sibling view id and places the view above the
specified view id.
layout_below It accepts another sibling view id and places the view below the
specified view id.

RelativeLayout in activity_main.xml file:


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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="10dp"

android:paddingRight="10dp">

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:text="First name:"

android:layout_marginTop="20dp"

android:textSize="20dp"/>

<EditText

android:id="@+id/editText1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_toRightOf="@id/textView1"

android:layout_marginTop="8dp"/>

<TextView

android:id="@+id/textView2"

android:layout_width="wrap_content"
Jimilraj Vala Mobile Computing and App Development

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_below="@+id/textView1"

android:layout_marginTop="10dp"

android:text="Last name:"

android:textSize="20dp"/>

<EditText

android:id="@+id/editText2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_toRightOf="@id/textView2"

android:layout_marginTop="45dp"/>

<Button

android:id="@+id/btn4"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_below="@id/textView2"

android:layout_marginTop="20dp"

android:text="Submit" />

</RelativeLayout>

3. ConstraintLayout: Refer all attributes!

ConstraintLayout is similar to that of other View Groups which we have seen in Android such
as RelativeLayout, LinearLayout, and many more. In this article, we will take a look at using
ConstraintLayout in Android.

Attributes Description
android:id This is used to give a unique id to the layout.
app:layout_constraintBottom_toBottomOf This is used to constrain the view with respect to the
bottom position.
Jimilraj Vala Mobile Computing and App Development

app:layout_constraintLeft_toLeftOf This attribute is used to constrain the view with


respect to the left position.
app:layout_constraintRight_toRightOf This attribute is used to constrain the view with
respect to the right position.
app:layout_constraintTop_toTopOf This attribute is used to constrain the view with
respect to the top position.
Advantages of using ConstraintLayout in Android:
 ConstraintLayout provides you the ability to completely design your UI with the drag and drop feature
provided by the Android Studio design editor.
 It helps to improve the UI performance over other layouts.
 With the help of ConstraintLayout, we can control the group of widgets through a single line of code.
 With the help of ConstraintLayout, we can easily add animations to the UI components which we used
in our app.

Disadvantages of using ConstraintLayout:


 When we use the Constraint Layout in our app, the XML code generated becomes a bit difficult to
understand.
 In most of the cases, the result obtain will not be the same as we got to see in the design editor.
 Sometimes we have to create a separate layout file for handling the UI for the landscape mode.

Working with the activity_main.xml file:


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:gravity="center"
android:padding="10dp"
android:text="Geeks for Geeks"
Jimilraj Vala Mobile Computing and App Development

android:textColor="@color/black"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. Table Layout: Refer all attributes


Android TableLayout is a ViewGroup subclass which is used to display the child View elements in rows
and columns. It will arrange all the children elements into rows and columns and does not display any
border lines in between rows, columns or cells.
The working of TableLayout is almost similar to HTML table and it contains as many columns as row with
the most cells.
Attributes Description
android:id This is the ID which uniquely identifies the layout.
android:collapseColumns This specifies the zero-based index of the columns
to collapse. The column indices must be separated
by a comma: 1, 2, 5.
android:shrinkColumns The zero-based index of the columns to shrink. The
column indices must be separated by a comma: 1,
2, 5.
android:stretchColumns The zero-based index of the columns to stretch. The
column indices must be separated by a comma: 1,
2, 5.

How to declare TableLayout and TableRow?


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:paddingLeft="5dp"
android:paddingRight="5dp">

// Add Table rows here


</TableLayout>
<TableRow android:background="#51B435" android:padding="10dp">
Jimilraj Vala Mobile Computing and App Development

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rank" />
</TableRow>

activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:paddingLeft="5dp"
android:paddingRight="5dp">
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ICC Ranking of Players:"
android:textSize = "20dp"
android:textStyle="bold">
</TextView>
<TableRow android:background="#51B435" android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rank" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
Jimilraj Vala Mobile Computing and App Development

android:text="Player" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Team" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Points" />
</TableRow>
<TableRow android:background="#F0F7F7" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Virat Kohli" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="IND" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
Jimilraj Vala Mobile Computing and App Development

android:text="895" />
</TableRow>
<TableRow android:background="#F0F7F7" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Rohit Sharma" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="IND" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="863" />
</TableRow>
<TableRow android:background="#F0F7F7" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="3" />
<TextView
android:layout_width="wrap_content"
Jimilraj Vala Mobile Computing and App Development

android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Faf du Plessis" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="PAK" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="834" />
</TableRow>
<TableRow android:background="#F0F7F7" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Steven Smith" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="AUS" />
<TextView
android:layout_width="wrap_content"
Jimilraj Vala Mobile Computing and App Development

android:layout_height="wrap_content"
android:layout_weight="1"
android:text="820" />
</TableRow>
<TableRow android:background="#F0F7F7" android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Ross Taylor" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="NZ" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="817" />
</TableRow> </TableLayout>

2.4 Fragments

In Android, the fragment is the part of Activity which represents a portion of User Interface(UI) on the
screen. It is the modular section of the android activity that is very helpful in creating UI designs that are
flexible in nature and auto-adjustable based on the device screen size. The UI flexibility on all devices
improves the user experience and adaptability of the application. Fragments can exist only inside an activity
as its lifecycle is dependent on the lifecycle of host activity. For example, if the host activity is paused, then
Jimilraj Vala Mobile Computing and App Development

all the methods and operations of the fragment related to that activity will stop functioning, thus fragment is
also termed as sub-activity. Fragments can be added, removed, or replaced dynamically i.e., while activity
is running.

<fragment> tag is used to insert the fragment in an android activity layout. By dividing the activity’s layout
multiple fragments can be added in it.

Below is the pictorial representation of fragment interaction with the activity: Refer for better understanding

Fragment Lifecycle: Very important. Make sure to refer it


Jimilraj Vala Mobile Computing and App Development

Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to, the fragment
lifecycle is influenced by the activity’s lifecycle.
Methods of the Android Fragment
1. onAttach(): once during the lifetime of a fragment.. When we attach fragment(child) to Main(parent)
activity then it call first and then not call this method any time(like you run an app and close and
reopen) simple means that this method call only one time.
2. onCreate(): This method initializes the fragment by adding all the required attributes and components.
3. onCreateView(): System calls this method to create the user interface of the fragment. The root of the
fragment’s layout is returned as the View component by this method to draw the UI. You should inflate
your layout in onCreateView but shouldn’t initialize other views using findViewById in onCreateView.
4. onViewCreated(): It indicates that the activity has been created in which the fragment exists. View
hierarchy of the fragment also instantiated before this function call.
5. onStart(): The system invokes this method to make the fragment visible on the user’s device.
6. onResume(): This method is called to make the visible fragment interactive.
7. onPause(): It indicates that the user is leaving the fragment. System call this method to commit the
changes made to the fragment.
8. onStop(): Method to terminate the functioning and visibility of fragment from the user’s screen.
9. onDestroyView(): System calls this method to clean up all kinds of resources as well as view hierarchy
associated with the fragment. It will call when you can attach new fragment and destroy existing
fragment Resoruce
10. onDestroy(): It is called to perform the final clean up of fragment’s state and its lifecycle.
11. onDetach(): The system executes this method to disassociate the fragment from its host activity.
It will call when your fragment Destroy(app crash or attach new fragment with existing fragment)

Example:
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it).
You can do it with 2 ways, First Create a class and extended with Fragment class and create resource layout
file.
OR
Second ways is Right Click on Package -> New -> Fragment -> Fragments (Blank)
then give Fragment Name , check Fragment Layout Name – > Finish
Jimilraj Vala Mobile Computing and App Development

Step 1. Create an android project in the android studio


Step 2. Create 2 Fragments and its resource layout. Follow upper section #Creating a Fragment
First fragment resource file fragment_first.xml, Outer Layout is FrameLayout, you can use the choice of your
layout (LinearLayout, RelativeLayout or ConstraintLayout etc)
<FrameLayout 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"
android:background="#C0C0C0"
tools:context="in.eyehunt.androidfragmentexample.FirstFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="First Fragment"
android:textSize="16sp" />
Jimilraj Vala Mobile Computing and App Development

</FrameLayout>
FirstFragment.kotlin
package `in`.eyehunt.androidfragmentexample

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class FirstFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,


savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}

}// Required empty public constructor


Second fragment resource file fragment_second.xml, Both fragments layout containing TextView widget to
show text.
<FrameLayout 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="in.eyehunt.androidfragmentexample.SecondFragment">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Second Fragment"
android:textSize="16sp" /> </FrameLayout>
Jimilraj Vala Mobile Computing and App Development

Output screenshot Android Fragment example app :

2.5 Themes
A theme is a collection of attributes that's applied to an entire app, activity, or view hierarchy—not just an
individual view. When you apply a theme, every view in the app or activity applies each of the theme's
attributes that it supports. Themes can also apply styles to non-view elements, such as the status bar and
window background.

Styles and themes are declared in a style resource file in res/values/, usually named styles.xml.

Figure - Two themes applied to the same activity: Theme.AppCompat (left)


and Theme.AppCompat.Light (right).
Jimilraj Vala Mobile Computing and App Development

Syntax : <manifest ... >


<application android:theme="@style/ThemeAppCompat" ... >
</application>
</manifest>

Themes versus styles

Themes and styles have many similarities, but they are used for different purposes. Themes and styles have
the same basic structure—a key-value pair that maps attributes to resources.

A style specifies attributes for a particular type of view. For example, one style might specify a button's
attributes. Every attribute you specify in a style is an attribute you can set in the layout file. Extracting all the
attributes to a style makes it easy to use and maintain them across multiple widgets.

A theme defines a collection of named resources that can be referenced by styles, layouts, widgets, and so
on. Themes assign semantic names, like colorPrimary, to Android resources.

Styles and themes are meant to work together. For example, you might have a style that specifies that one
part of a button is colorPrimary, and another part is colorSecondary. The actual definitions of those colors
are provided in the theme. When the device goes into night mode, your app can switch from its "light"
theme to its "dark" theme, changing the values for all those resource names. You don't need to change the
styles, since the styles are using the semantic names and not specific color definitions.

Refer this diagram for better understanding


Jimilraj Vala Mobile Computing and App Development

 Android developers witness the ambiguity in styles and themes. The reason is that in Android there
are only tag names <style>, there is no <theme> tag available.
 Style is a collection of attributes that define the appearance of a single view. The style attributes are
the font, color, size, background color, etc. For example, the font size may be different for heading
and body.
 Theme, on the contrary, is applied to the entire app, or activity, or view hierarchy, not just for
individual views. Themes can also apply styles to non-view elements such as status bar, window
background, etc. For example, the colorPrimary is applied to all the Floating Action Buttons or
Normal Buttons of the entire application. One can get the difference in the following image.

2.6 Notifications
Android Notification provides short, timely information about the action happened in the application, even it
is not running. The notification displays the icon, title and some amount of the content text.
Notifications could be of various formats and designs depending upon the developer. In General, one must
have witnessed these four types of notifications:
1. Status Bar Notification (appears in the same layout as the current time, battery percentage)
2. Notification drawer Notification (appears in the drop-down menu)
3. Heads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages)
4. Lock-Screen Notification (I guess you know it)

Set Android Notification Properties:


 setSmallIcon(): It sets the icon of notification.
 setContentTitle(): It is used to set the title of notification.
 setContentText(): It is used to set the text message.
 setAutoCancel(): It sets the cancelable property of notification.
 setPriority(): It sets the priority of notification.
Jimilraj Vala Mobile Computing and App Development

Example:
Step1: Working with the activity_main.xml file
<?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">

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Send Notification" />
</RelativeLayout>

Step2: Create a new empty activity


Name the activity as afterNotification. When someone clicks on the notification, this activity will open up in
our app that is the user will be redirected to this page. Below is the code for the
activity_after_notification.xml file.
<?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=".afterNotification">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Jimilraj Vala Mobile Computing and App Development

android:layout_centerInParent="true"
android:text="Welcome To userdefine Notification"
android:textSize="15sp"
android:textStyle="bold" />

</RelativeLayout>

Step3: Working with the MainActivity.kt file


import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat

class MainActivity : AppCompatActivity() {


lateinit var notificationManager: NotificationManager
lateinit var notificationChannel: NotificationChannel
lateinit var builder: NotificationCompat.Builder
private val channelId = "i.apps.notification"
private val channelName = "NChannel"
private val channelDescription = "Test Notification"

override fun onCreate(savedInstanceState: Bundle?)


{ super.onCreate(savedInstanceState)
Jimilraj Vala Mobile Computing and App Development

setContentView(R.layout.activity_main)
Toast.makeText(applicationContext,"On Create Called", Toast.LENGTH_LONG).show();

//Because you must create the notification channel before posting any notifications on Android 8.0 and
later, execute this code as soon as your app starts. I
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_DEFAULT
notificationChannel = NotificationChannel(channelId, channelName, importance).apply
{ description = channelDescription
}
// notificationChannel.enableLights(true)
// notificationChannel.lightColor = Color.GREEN
// notificationChannel.enableVibration(false)
// notificationManager.createNotificationChannel(notificationChannel)

// Register the channel with the system.


notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
}
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
val intent = Intent(this, MainActivity3::class.java)
val pendingIntent = PendingIntent.getActivity(this, 2, intent,
PendingIntent.FLAG_UPDATE_CURRENT)

builder = NotificationCompat.Builder(this, channelId)


.setContentTitle("My notification")
.setContentText("Much longer text that cannot fit one line...")
.setSmallIcon(R.drawable.ic_launcher_background)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
Jimilraj Vala Mobile Computing and App Development

notificationManager.notify(1234,builder.build())

}
override fun onStart()
{ super.onStart()
Toast.makeText(applicationContext,"On Start Called", Toast.LENGTH_LONG).show();
}
override fun onResume()
{ super.onResume()
Toast.makeText(applicationContext,"On Resume Called", Toast.LENGTH_LONG).show();
}
override fun onStop()
{ super.onStop()
Toast.makeText(applicationContext,"On onStop method Called", Toast.LENGTH_LONG).show();
}
fun onClickSubmit(view: View) {

val msg = "Hello from Main Activity"


// Create the text message with a string.
val sendIntent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, msg)
type = "text/plain"
}
val callIntent = Intent(Intent.ACTION_DIAL,Uri.parse("tel:9898989898"))//.apply {data =
Uri.parse("tel:9898989898")}

val mapIntentn = Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=Ahmedabad, Gujarat"))


val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.android.com"))
val intent = Intent(applicationContext, MainActivity2::class.java)
intent.putExtra("msg", msg);
intent.putExtra("msg2", "hello");
Jimilraj Vala Mobile Computing and App Development

// Try to invoke the intent.


try {
startActivity(sendIntent)
} catch (e: ActivityNotFoundException) {
// Define what your app should do if no activity can handle the intent.
Toast.makeText(applicationContext,"Activity Not Found", Toast.LENGTH_LONG).show();
}
Toast.makeText(applicationContext,"btn clicked", Toast.LENGTH_LONG).show();
}
//if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) !=
PackageManager.PERMISSION_GRANTED)
//{
// ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE) , 1);
//}

Step4: NotificationView.kt
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class NotificationView extends AppCompatActivity


{ TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_view);
textView = findViewById(R.id.textView);
//getting the notification message
String message=getIntent().getStringExtra("message");
textView.setText(message);
}
}
Jimilraj Vala Mobile Computing and App Development

2.7 Invoking Built-in Applications


In Android, you can invoke built-in applications using Intents. Intents are a fundamental part of the Android
system that allows components (such as activities, services, and broadcast receivers) to request actions or
interactions with other components. There are two types of intents: implicit and explicit.

1. Implicit Intent

Using implicit Intent, components can’t be specified. An action to be performed is declared by implicit
intent. Then android operating system will filter out components that will respond to the action. For
Example,

In the above example, 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.

Step by Step Implementation

Creating an Android App to Open a Webpage Using Implicit Intent

Step 1: Create a New Project in Android Studio

Step 2: Working with the XML Files


Jimilraj Vala Mobile Computing and App Development

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for
the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

Syntax:

android:id="@+id/id_name"

XML

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

<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<EditText

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

<Button

android:id="@+id/btn"

android:text="Search"
Jimilraj Vala Mobile Computing and App Development

android:onClick="search"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity File

Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the
component (Button) created in the XML file using the findViewById() method. This method binds the
created object to the UI Components with the help of the assigned ID.

Syntax:

ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);

Kotlin

import android.content.Intent

import android.net.Uri

import android.os.Bundle

import android.widget.Button

import android.widget.EditText

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity()

{ lateinit var editText: EditText

override fun onCreate(savedInstanceState: Bundle?)

{ super.onCreate(savedInstanceState)
Jimilraj Vala Mobile Computing and App Development

setContentView(R.layout.activity_main)

editText = findViewById(R.id.editText)

fun search() {

val url = editText.text.toString()

val urlIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))

startActivity(urlIntent)

}}

2. Explicit Intent

Using explicit intent any other component can be specified. In other words, the targeted component is
specified by explicit intent. So only the specified target component will be invoked. For Example:

In the above example, There are two activities (FirstActivity, and SecondActivity). When you click on the
‘GO TO OTHER ACTIVITY’ button in the first activity, then you move to the second activity. When you
click on the ‘GO TO HOME ACTIVITY’ button in the second activity, then you move to the first activity.
This is getting done through Explicit Intent.
Jimilraj Vala Mobile Computing and App Development

Step by Step Implementation

How to create an Android App to move to the next activity using Explicit Intent(with Example)

Step 1: Create a New Project in Android Studio

Step 2: Working with the activity_main.xml File

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for
the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

Syntax:

android:id="@+id/id_name"

XML

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

<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Welcome to GFG Home Screen"

android:textAlignment="center"

android:textSize="28sp"

app:layout_constraintBottom_toBottomOf="parent"
Jimilraj Vala Mobile Computing and App Development

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.0"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

<Button

android:id="@+id/btn1"

android:text="Go to News Screen"

android:onClick="newsScreen"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity File

Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the
component (Button, TextView) created in the XML file using the findViewById() method. This method
binds the created object to the UI Components with the help of the assigned ID.

Syntax:

ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);

Intent i = new Intent(getApplicationContext(), <className>);

startActivity(i);

Kotlin

import android.content.Intent

import android.os.Bundle
Jimilraj Vala Mobile Computing and App Development

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?)

{ super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)}

fun newsScreen() {

val i = Intent(applicationContext, MainActivity2::class.java)

startActivity(i); } }

Step 4: Working with the activity_main2.xml File

Now we have to create a second activity as a destination activity. The steps to create the second activity
are File > new > Activity > Empty Activity.
Jimilraj Vala Mobile Computing and App Development

Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for
the activity_main2.xml file. Comments are added inside the code to understand the code in more detail.

XML

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

<androidx.constraintlayout.widget.ConstraintLayout
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:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity2">

<TextView

android:id="@+id/editText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Welcome to GFG News Screen"

android:textAlignment="center"

android:textSize="28sp"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.0"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />
Jimilraj Vala Mobile Computing and App Development

<Button

android:id="@+id/btn2"

android:text="Go to Home Screen"

android:onClick="homeScreen"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widgext.ConstraintLayout>

Step 5: Working with the MainActivity2 File

Now, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the
component (Button, TextView) created in the XML file using the findViewById() method. This method
binds the created object to the UI Components with the help of the assigned ID.

Syntax:

ComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);

Intent i = new Intent(getApplicationContext(), <className>);

startActivity(i);

Kotlin

import android.content.Intent

import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity

class MainActivity2 : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {


Jimilraj Vala Mobile Computing and App Development

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main2)

fun homeScreen() {

val i = Intent(applicationContext, MainActivity::class.java)

startActivity(i)

You might also like