0% found this document useful (0 votes)
5 views394 pages

Questions: List Plso - V9S8C6Fqtib6Olje4F-Mvtw-Hnwa6

The document outlines a comprehensive curriculum for mobile application development, specifically focusing on Android. It covers various units that include topics such as Android SDK features, UI design, data storage, networking, and application lifecycle. Additionally, it poses numerous questions for each unit to facilitate learning and understanding of Android app development concepts and practices.

Uploaded by

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

Questions: List Plso - V9S8C6Fqtib6Olje4F-Mvtw-Hnwa6

The document outlines a comprehensive curriculum for mobile application development, specifically focusing on Android. It covers various units that include topics such as Android SDK features, UI design, data storage, networking, and application lifecycle. Additionally, it poses numerous questions for each unit to facilitate learning and understanding of Android app development concepts and practices.

Uploaded by

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

Mobile Application Services

- Wei-Meng Lee, Beginning Android’" 4 Application Development, 2012 by John Wiley &
Sons

https://www.youtube.com/playlist? Android Telephony.


list=PLsO_V9s8C6fqtib6olJE4F-MvTW-hNWa6 Notifications and Alarms: Performance,
Performance and Memory Management,
Android Notifications and Alarms,
Graphics,
Performance and multi-threading,
Unit 1: Graphics and UI Performance,
Introduction: Introduction to Mobile Computing, Android Graphics
Introduction to Android Development Environment,
Factors in Developing Mobile Applications, Unit4:
Mobile Software Engineering, Putting It All Together Packaging and Deploying,
Frameworks and Tools, Performance Best Practices,
Generic UI Development Android User Android Field Service App,
Location Mobility and Location Based Services
Unit 2: Android Multimedia: Mobile Agents and Peer-to-Peer
More on Uis: VUIs and Mobile Apps, Architecture,
Text-to-Speech Techniques, Android Multimedia
Designing the Right UI,
Multichannel and Multimodal UIs,
Unit 5:
Storing and Retrieving Data,
Synchronization and Replication of Mobile Data, Platforms and Additional Issues Development
Getting the Model Right,
Process,
Android Storing and Retrieving Data,
Working with a Content Provider Architecture, Design,
Technology Selection,
Unit 3: Mobile App Development Hurdles,
Communications via Network and the Web: State Testing,
Machine, Security and Hacking,
Correct Communications Model, Active Transactions,
Android Networking and Web, More on Security,
Telephony Deciding Scope of an App,
Hacking Android
Wireless Connectivity and Mobile Apps,

Questions
Unit 1

1. Write about Android SDK Features


2. What Android Has That Other Platforms Don’t Have? Explain?
3. Explain Android Software Stack framework with neat figure.
4. What is virtual device and SDK manager? Explain.
5. What is manifest? Write application of manifest.
6. Explain the steps for creating the Virtual device.
7. Explain the view provides quick access to your project's key files.
8. What is android? Why develop apps for android?
9. With neat diagram, show the major components of Android stack.
10. With neat diagram, explain the high-level picture of Android app development
process.
11. List and explain the steps for starting and using the Android studio.
12. How do you run app on virtual device and app on physical device.
13. What is Activity navigation? Explain 2 forms of navigation strategies.
14. Explain XML attributes using TextView as example.
15. Explain the Passing of data between activities with intents.
16. Discuss about Android Application Lifecycle
17. Describe the life cycle of an Android activity with neat sketch?
18. List and Explain the Resource files.
19. Discuss the framework of Android studio.
20. Explain the activity life cycle.
21. How does Mobile Computing work? Discuss Mobile Software Engineering?
22. Discuss in detail different mobile computing techniques in IOT.

Unit 2

1. Define a) View b) View group c) Layout.


2. Explain the following layouts: Relative Layout, Linear Layout
3. Explain Different Layouts available in Android. Explain with Example.
4. What is Fragment? Explain Fragment Lifecycle with Example.
5. Explain how do you design the checkboxes? Along with onSubmit() method
implementation.
6. How do you design toggle button and implement the response to it?
7. Explain how to create Text Input? List out the Attributes for customizing Textview. Write
down the steps for getting the user's input.
8. What is a Menu? List out the types of Menus. Explain implementation of app bar &
options menu.
9. What is screen orientation? Explain its implementation.
10. Explain Event handing. Write a program to display the Messages through Toast.
11. Write about Mobile App UI? How do we use text to speech on Android?
12. Explain Text-to-Speech Techniques with examples.
13. How text-to-speech technology is implemented in mobile app?
14. How synchronization and Replication of Mobile data is performed?

Unit 3

1. What is Intent, intent objects and fields? List and explain types of Intents
2. Explain the steps for sending and receiving the implicit intents.
3. What is Broadcast Receiver? How do you create Broadcast Receiver?
4. How do you make an HTTP connection to connect to internet?
5. What is a Service? How do you implement Started Service and Bound Service? Explain.
6. What is a Notification? Explain the implementation steps for creating Notifications.
7. Explain the Notification design guidelines.
8. List and Explain the Notification Priorities.
9. Define Loader? Explain, how do you start and restart a loader?
10. Explain Image Views to display pictures in Android Mobile.
11. Explain Activity Launch modes using attributes and intent flags.
12. Describe these App components, Intent filters, Content Sharing and Threads.
13. Describe these App components - Intent, Activity and Threads.
14. What is meant by UI architecture explain? What is intent? How many different
intent types are there?
15. How data is accessing and building a content provider? What would be the result
if not have network connectivity?
16. Develop an App having some animations and graphics.
17. Discuss Wireless Communications in Modern Mobile Technologies?
18. Write in detail about recent trends in communication protocols for IOT nodes?
19. Using the Intent Service to Simplify the Earthquake Update Service. Explain?

Unit 4

1. Android Field Service App


2. What is a Peer-to-Peer (P2P) architecture?
3. How to Save Data using the SharedPreferences Object. Explain?
4. Write a code to store one line in file which resides in sdcard?
5. Create a simple registration form using EditText, Radio Button, and store the user value
in SharedPreference.
6. Define Shared preferences. List and explain data storage options available.
7. Differentiate between internal storage and external storage.
8. What is SQLite database? How to provide database connection using SQLite database.
9. What is SQLite database? Write code for adding, updating and removing data from
SQLite database.
10. Write an android application for login & registration using SQLite database
connectivity.
11. How to Store and Retrieve all contacts from the Table Using Database
Programmatically. Explain?
12. Define SQLite. Explain example table for SQLite store data in tables.
13. What is a Cursor? Explain cursor classes and methods.
14. What is Content Provider? What are the Operations supported by a Content
Provider?
15. How the packaging and deploying is done to make apps available on play store?
16. Write a note on Android multimedia and android agents.
17. Explain performance best practices in android location mobility. What are the
issues will face in location mobility?
18. Discuss how Android Stores and Retrieves data through SQL Applications?
19. How data is stored and retrieved in android?
20. Give an overview of Mobile Agents? Discuss location-based services in Android?
21. Write a program to display the Current Location?
22. Write a Program to how to display Current Location on the Map in Mobile
Application?
23. Write a Program to how to update the Current Location in the Map?
24. Discuss the directory structure of an Android Project.

Unit 5

1. Write about How to Creating, Setting, and Cancelling Alarms


2. Create a Simple Own Service to start and stop the service in Android?
3. What is a web service? Why it is required? How a web service can be consumed in an
Android application?
4. What is Action Bar? Write a program to Add items in ActionBar?
5. Explain about Internet download Manager Usage in Android Mobile Application?
6. How to Publishing your application on the Android Market. Explain?
7. Explain different skills required for Android Developer?
8. Discuss the architecture and working of Windows Phone.
9. Discuss about windows phone and its platform.
10. Explain in detail the importance of delivery of Mobile Application?
11. Describe the process of mobile application for integration with GPS.
12. What are the various hurdles that are faced during the mobile app development?
13. What is framework? Write various hurdles in Mobile App Development?
14. What are testing methodologies and deployment process in Mobile Software
Engineering?
15. How performance, scalability and security address in mobile applications?
16. Explain myths of security and hacking of Android application with a suitable
example.
17. Discuss the need of permissions in Android. Describe the permissions to set
system functionalities like bluetooth, camera.
18. Develop an App to control Camera and WiFi.

**********************************************************************
******

Unit 1

Write about Android SDK Features


Android SDK
Android SDK is a collection of libraries and Software Development tools that are essential for
Developing Android Applications. Whenever Google releases a new version or update of
Android Software, a corresponding SDK also releases with it. In the updated or new version of
SDK, some more features are included which are not present in the previous version. Android
SDK consists of some tools which are very essential for the development of Android
Application. These tools provide a smooth flow of the development process from developing
and debugging. Android SDK is compatible with all operating systems such as Windows,
Linux, macOS, etc.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.
Components of Android SDK
If you’re keen on mastering the Android SDK and learning to use its components efficiently,
consider enrolling in the Android Development with Kotlin course by GeeksforGeeks.
This course will help you build a solid foundation in Kotlin and Android app development,
enabling you to create professional and efficient applications. Android SDK Components play
a major role in the Development of Android applications. Below are the important
components:

1. Android SDK Tools

Android SDK tool is an important component of Android SDK. It consists of a complete set of
development and debugging tools. Below are the SDK developer tools:

 Android SDK Build tool.

 Android Emulator.

 Android SDK Platform-tools.

 Android SDK Tools.

These are shown below :

2. Android SDK Build-Tools

Android SDK build tools are used for building actual binaries of Android App. The main
functions of Android SDK Build tools are built, debug, run and test Android applications. The
latest version of the Android SDK Build tool is 30.0.3. While downloading or updating
Android in our System, one must ensure that its latest version is download in SDK
Components.

3. Android Emulator

An Android Emulator is a device that simulates an Android device on your system. Suppose
we want to run our android application that we code. One option is that we will run this on
our Android Mobile by Enabling USB Debugging on our mobile. Another option is using
Android Emulator. In Android Emulator the virtual android device is shown on our system on
which we run the Android application that we code.

Thus, it simply means that without needing any physical device Android SDK component
“Android Emulator” provides a virtual device on the System where we run our Application.
The emulator’s come with the configuration for Various android phones, tablets, Wear OS,
and Android TV devices.

In Android Virtual Emulator all functions that are feasible on real Android mobile is works on
virtual Device like:

 phone calls, text messages.

 stimulate different network speeds.

 specify the location of a device

 access on google play store and lot’s more.

But there is one disadvantage of this emulator is that. It is very slow when System’s PC has
less RAM. It works fine when a maximum GB of RAM is present on our device.

4. Android SDK Platform-tools

Android SDK Platform-tools is helpful when we are working on Project and they will show the
error messages at the same time. It is specifically used for testing. It includes:

 Android Debug Bridge (ADB), is a command-line tool that helps to communicate with
the device. It allows us to perform an action such as Installing App and Debugging App
etc.

 Fastboot allows you to flash a device with a new system image.

 Systrace tools help to collect and inspect timing information. It is very crucial for App
Debugging.

5. Android SDK Tools

Android SDK tool is a component of SDK tool. It consists of a set of tools which and other
Utilities which are crucial for the development of Android Application. It contains the
complete set of Debugging and Development tools for android.

6. SDK Platforms

For Each Android Software, one SDK platform is available as shown below:
Like in this Android 11.0(R) is installed.

These are numbered according to the android version. The new version of the SDK platform
has more features and more compatible but the old version is less compatible with fewer
features. Like in Android 11.0(R) have more compatible and have more feature but the below
versions like Android 10.0(Q), Android4.4(KitKat) have less feature and is less compatible.

7. SDK Update Sites

In SDK Update Sites, some sites are embedded in it which will check for Android SDK Updates
Tools. In this, one must ensure we don’t unclick the button below because these are checked
by default which will check for updates if we will unclick it then it doesn’t check updates for
those.

What Android Has That Other Platforms Don’t Have? Explain?


Android offers several unique features and capabilities that differentiate it from other mobile
operating systems like iOS, Windows Phone (which is no longer actively supported), or even
emerging platforms. While all platforms have their strengths, Android stands out in various
areas due to its flexibility, customization, and open nature.

Here’s a breakdown of what Android has that other platforms might not offer:
1. Open-Source Nature (Android Open Source Project - AOSP)

Android is based on the Android Open Source Project (AOSP), meaning that its source code is
open for modification, allowing manufacturers, developers, and even enthusiasts to
customize the operating system to their needs.

 Custom ROMs: Android users can install custom ROMs (like LineageOS, Pixel
Experience, etc.), which provide personalized experiences, features, and tweaks that
are not available in the stock version of the OS.

 Wide Customization: Developers can create custom Android operating systems, and
users have the flexibility to change almost every aspect of the OS, including themes,
UI, and behavior.

 Community-driven Improvements: Because of its open-source nature, Android


benefits from a vast, active community that continuously contributes to the platform’s
development.

2. Multiple Device Manufacturers

Unlike iOS, which is exclusive to Apple, Android runs on devices from a wide range of
manufacturers, including Samsung, Google, Xiaomi, OnePlus, LG, Motorola, and many others.

 Variety of Devices: Users can choose from a broad selection of devices in terms of
price, design, features, and functionality. Whether you're looking for budget-friendly
phones or high-end flagship devices, Android has something for everyone.

 Hardware Variety: Android also works on a range of hardware, including


smartphones, tablets, wearables (like smartwatches), smart TVs, and even cars (via
Android Auto).

 Innovative Features from Manufacturers: Many Android device manufacturers add


unique features to their devices (e.g., Samsung's One UI, Xiaomi’s MIUI, Huawei’s
EMUI), which users can enjoy in addition to the stock Android experience.

3. Google Integration

Google is deeply embedded in Android, offering a range of unique services and features that
enhance the user experience:

 Google Assistant: Android offers native access to Google Assistant, one of the most
powerful voice-activated virtual assistants. It is integrated into the Android system,
making it highly functional and versatile for daily tasks, navigation, home automation,
and more.

 Google Play Store: The Google Play Store offers a vast selection of apps, games, and
media, with better integration of services like Google Play Music, Movies, and News.
Android users also have access to a more open app ecosystem.

 Google Services: Android comes pre-integrated with Google's suite of services,


including Gmail, Google Maps, Google Photos, Google Drive, Google Docs, Google
Calendar, etc. These apps are fully optimized for the Android ecosystem and
seamlessly sync across devices.
4. Customization

Android allows extensive customization options that are much more advanced compared to
iOS and other platforms:

 Home Screen Customization: Android provides an immense degree of flexibility in


customizing home screens with widgets, icon packs, launchers, and more. Users can
freely rearrange icons, resize widgets, and install third-party launchers like Nova
Launcher or Action Launcher to change the look and feel of their device.

 Custom Lock Screens: In addition to home screens, Android offers a variety of lock
screen options, allowing users to modify or add widgets, shortcuts, and notifications.

 Default Apps: Android allows users to set third-party apps as defaults (e.g., changing
the default browser, SMS app, or dialer), something that’s much more restricted on iOS.

 Advanced Themes and Skins: Many manufacturers offer unique themes, skins, and
wallpapers that users can apply to further personalize their devices.

5. File Management and Access

Android provides a file system with extensive access for users and apps:

 Full File System Access: Android allows file managers and apps to access the file
system more freely. Users can browse and manage their files using built-in file
managers or third-party apps.

 External Storage Support: Android supports external storage devices like microSD
cards, USB drives, and OTG devices. This feature is often not available or severely
limited on iOS devices.

 File Sharing: Android's built-in file-sharing options, such as the ability to send files via
Bluetooth, NFC, or Wi-Fi Direct, offer a broader range of sharing capabilities compared
to other platforms.

6. App Distribution Flexibility

Android allows more flexibility in app distribution:

 Third-Party App Stores: Apart from the official Google Play Store, Android allows
apps to be distributed from third-party app stores like Amazon Appstore, Aptoide, or
even direct APK (Android Package) installations. Users can download and install apps
from sources outside the Play Store, although this comes with security risks if not done
carefully.

 APK Installation: Unlike iOS, which is locked to the App Store for app installation,
Android allows the installation of APK files directly from the internet, enabling users to
try apps not yet available on the Play Store or sideload apps for testing purposes.

 App Signing and Distribution for Developers: Android allows developers more
control over app distribution. Developers can distribute APKs directly to users or via
private channels, making it easier to test and deploy apps without needing to go
through an app store approval process.
7. Multiple App Background Processing

Android provides more robust background processing capabilities compared to other


platforms:

 Background Services: Android has a rich API for running background services (such
as Service or JobScheduler), which are crucial for long-running tasks like syncing data,
playing music, or updating location. iOS offers background tasks but with more
limitations.

 Push Notifications: Android supports push notifications and background tasks more
flexibly, allowing apps to wake up or trigger specific actions even when they're not
running in the foreground.

8. Diverse Connectivity Options

Android supports a broad range of connectivity options that can be utilized across various
devices:

 NFC: Android devices can use NFC (Near Field Communication) for tasks such as
contactless payments, data transfer, or pairing devices.

 Android Auto: Android Auto allows users to seamlessly connect their Android device
to their car’s infotainment system, providing access to apps like navigation, music, and
messaging.

 Chromecast Integration: Android supports Chromecast, allowing users to cast


content to TVs and smart devices. While iOS also has AirPlay, Android’s integration with
Chromecast is more widespread and supported by a larger number of devices.

9. Hardware Innovation and Support

Android devices are diverse and support many hardware configurations:

 Customization by OEMs: Android allows manufacturers to innovate and provide


unique hardware features. For example, OnePlus offers fast charging with its Warp
Charge technology, while Samsung provides features like foldable screens and high-
refresh-rate displays.

 Wide Hardware Support: Android supports a range of devices from smartphones to


tablets, smartwatches (Wear OS), TVs (Android TV), and even cars (via Android Auto).
This level of hardware variety is not matched by other platforms.

10. App Development Flexibility

Android offers more flexibility to developers in terms of app development and distribution:

 Java and Kotlin: Android development can be done using Java or Kotlin (which is
officially preferred by Google). This provides flexibility in choosing programming
languages compared to iOS, which is limited to Swift and Objective-C.

 Native Code Support (NDK): Android supports the use of native code (C, C++)
through the Android NDK (Native Development Kit), allowing for more performance-
intensive applications (e.g., games or apps that require low-level hardware access).
Explain Android Software Stack framework with neat figure.
Platform architecture

bookmark_border

Android is an open source, Linux-based software stack created for a wide array of devices
and form factors. Figure 1 shows the major components of the Android platform.

Figure 1. 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:

 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

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:

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

What is virtual device and SDK manager? Explain.


1. Virtual Device
A Virtual Device (also called an Android Virtual Device (AVD)) is an emulator that
simulates a physical Android device on your computer. It enables developers to test their
applications on different Android devices without needing the actual hardware.

AVDs are used to mimic different types of Android devices, screen sizes, resolutions, Android
versions, and hardware configurations, allowing developers to test their apps in a variety of
environments.

Key Features of Virtual Devices:

 Emulation of Hardware and OS: Virtual devices simulate the device’s screen,
buttons, sensors, and other hardware components, allowing the developer to run
Android applications on them.

 Multiple Configurations: You can create multiple virtual devices with different
hardware profiles and Android versions to test the app's compatibility with a variety of
devices.

 Testing Without Physical Device: AVDs allow developers to test apps on different
Android versions or screen sizes without having to buy different physical devices.

Creating and Using a Virtual Device (AVD):

To create and run a Virtual Device in Android Studio:

1. Open Android Studio: Launch Android Studio on your computer.

2. Navigate to AVD Manager: You can open the AVD Manager from the toolbar by
clicking on the "Tools" menu and selecting AVD Manager, or by clicking the "Device
Manager" icon on the toolbar.

3. Create a New Virtual Device: In the AVD Manager window, click the Create Virtual
Device button.

o Choose Device Type: Select the device you want to emulate (e.g., Pixel 4,
Nexus 5X).
o Select System Image: Choose the system image (Android version) that you
want the AVD to run. You can select different Android OS versions (such as
Android 10, 11, etc.).

o Configure AVD: Adjust the settings for the device (RAM, CPU architecture, SD
card size, etc.).

4. Run the Virtual Device: Once the AVD is created, click the green Play button next to
the device to launch the emulator.

Example:

Testing an app designed for tablets and phones with different screen sizes can be done by
creating multiple virtual devices with different screen dimensions and resolutions.

2. SDK Manager
The SDK Manager is a tool used in Android Studio to manage the Android Software
Development Kit (SDK) components, which include the necessary libraries, tools, platform
versions, and documentation required to develop Android applications. It helps you install
and update the SDK, as well as manage system images, APIs, and other Android tools.

Key Features of SDK Manager:

 Install and Update SDK Components: It allows you to download and update Android
SDK tools and APIs, including libraries, build tools, and different versions of Android
(such as Android 9, 10, etc.).

 Managing SDK Platforms: The SDK Manager helps you manage different versions of
Android, ensuring that your development environment has the necessary Android
platform(s) for building apps that work across various devices.

 Add-ons and Extras: You can also install additional tools and add-ons like Google Play
services, Android support libraries, and device drivers.

 Monitoring SDK Health: It shows you the installed components and available updates
or missing components to ensure the environment is up-to-date and complete for
development.

Using SDK Manager in Android Studio:

1. Open Android Studio: Launch Android Studio.

2. Navigate to SDK Manager: Click on Tools > SDK Manager in the top menu, or click
the "SDK Manager" icon on the toolbar.

3. Manage SDK Components:

o The SDK Manager window will open, showing you various tabs like SDK
Platforms and SDK Tools.

o SDK Platforms Tab: You can download different Android versions (API levels). If
you need an older version of Android (like 5.0), you can select it and install it.

o SDK Tools Tab: You can install and update essential SDK tools like Android SDK
Build-Tools, Android Emulator, and other developer tools.

4. Install or Update Components: To install or update specific components, simply


select the ones you need and click Apply.
Example:

If you are developing an app targeting Android 10 (API Level 29), you would go to the SDK
Platforms tab in the SDK Manager and check Android 10. Then, in the SDK Tools tab,
ensure that the "Android Emulator" and other relevant tools are installed for testing your app.

Differences Between AVD (Virtual Device) and SDK Manager:

 AVD Manager is focused on managing and running virtual devices (emulators) to test
Android apps, simulating the behavior of an actual device.

 SDK Manager is used to manage the SDK tools, platforms, and libraries necessary for
Android development, ensuring you have the proper components installed to build and
run apps on different Android versions and devices.

What is manifest? Write application of manifest.


What is a Manifest in Android?
In Android, the Manifest refers to the AndroidManifest.xml file, a crucial part of every
Android application. The AndroidManifest.xml file provides essential information about the
application to the Android operating system and the Android build system.

It serves as a declaration of the app’s components, permissions, and other necessary


configurations. The Manifest file is automatically generated when you create a new Android
project in Android Studio, and it is located in the app/src/main/ directory of the project.

Structure of the Manifest File


The AndroidManifest.xml file contains several important elements, which define the
structure and behavior of the application. Some key sections include:

1. Package Declaration:

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

package="com.example.myapp"

android:versionCode="1"

android:versionName="1.0">

o The package attribute specifies the unique identifier for the application (usually
in reverse domain format).

o The android:versionCode and android:versionName attributes define the


versioning information for the app.

2. Application Tag: The <application> tag encloses all components of the application,
such as activities, services, and broadcast receivers. This tag also specifies global
configurations like icons, themes, and the application name.

<application

android:name=".MyApplication"
android:icon="@mipmap/ic_launcher"

android:label="@string/app_name">

3. Permissions: The <uses-permission> tag is used to declare the permissions that the
app requires to access certain resources or perform specific actions (e.g., accessing the
internet, using the camera).

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

4. Activities, Services, and Broadcast Receivers: Each component of the app (such
as Activity, Service, BroadcastReceiver, etc.) must be declared inside the <application>
tag to let the system know about them.

<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>

5. Intents and Filters: The <intent-filter> tag is used to declare the types of intents an
activity or service can handle. For example, a launcher activity typically has an intent
filter with the MAIN action and LAUNCHER category.

<intent-filter>

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

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

</intent-filter>

6. Other Configurations: Additional configurations, such as defining hardware and


software features the app needs, setting up themes, or declaring background services,
are also specified in the manifest.

Applications of the Android Manifest File


The AndroidManifest.xml file plays a vital role in defining the structure and behavior of an
Android application. Below are some of the primary applications of the Manifest file:

1. Declaring Application Components

The Manifest file is used to declare all components of the application, such as:

 Activities: The screens or UI components of the app (e.g., MainActivity).

 Services: Background services that handle tasks such as music playback, network
requests, etc.

 Broadcast Receivers: Components that listen to and respond to system-wide or app-


specific broadcast messages.

 Content Providers: Used for sharing data between applications.

For example:
<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>

2. Specifying Permissions

The Manifest file is used to request permissions that are required by the application. For
example, if your app needs to access the camera, storage, or internet, you must specify
these permissions in the manifest.

Example:

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

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

Without declaring necessary permissions in the manifest, the app will not have access to
these resources and will not function as expected.

3. Declaring Minimum SDK Version and Target SDK Version

The Manifest allows you to specify the minimum SDK version (minSdkVersion) and the
target SDK version (targetSdkVersion) that the application supports. This ensures
compatibility with different Android versions.

Example:

<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="30"/>

 minSdkVersion: Specifies the minimum Android version your app can run on.

 targetSdkVersion: Specifies the Android version your app is optimized for (i.e., the
version you’ve tested against).

4. Handling Intents and Filters

The Manifest is responsible for mapping intents to the appropriate activities or services.
By using <intent-filter>, the manifest file defines what actions the app can perform and how
it can interact with other apps or the system.

Example:

<intent-filter>

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

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

</intent-filter>
This allows the app to handle specific types of intents, such as opening a specific URL or
responding to a particular action (e.g., opening the app via a link).

5. Declaring Hardware and Software Features

In the Manifest, you can specify the hardware and software features required by the
application. For example, if your app requires a camera, accelerometer, or GPS, you can
declare this in the manifest so that the system knows about the app's requirements.

Example:

<uses-feature android:name="android.hardware.camera" android:required="true"/>

<uses-feature android:name="android.hardware.location.gps"/>

This ensures that the app will only be available to users with the appropriate device features.

6. Defining the App Theme and Icon

The Manifest also contains metadata about the overall app, such as the app's name, icon,
theme, and splash screen.

Example:

<application

android:name=".MyApplication"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme">

This defines the theme and icon that will be displayed when the app is installed.

7. Defining App Startup Behavior

The Manifest defines the main entry point of the application using an <activity> tag with an
intent filter. The MainActivity is typically defined as the entry point of the app, which is
launched when the app is opened.

Example:

<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>
Explain the steps for creating the Virtual device.
Creating a Virtual Device (AVD) in Android Studio allows you to emulate an Android device
on your computer for testing and development purposes. Here are the detailed steps to
create a Virtual Device:

Steps to Create a Virtual Device in Android Studio:

1. Open Android Studio:

o Launch Android Studio on your computer. Make sure you have installed Android
Studio and the necessary SDK tools.

2. Open the AVD Manager:

o In Android Studio, go to the top menu bar and click on Tools > AVD Manager.

o Alternatively, you can click on the "Device Manager" icon located on the
toolbar, which also opens the AVD Manager.

This will open the Android Virtual Device Manager window.

3. Create a New Virtual Device:

o In the AVD Manager window, click the Create Virtual Device button. This starts
the process of creating a new AVD.

4. Select the Hardware (Device Configuration):

o You will be presented with a list of hardware profiles for different devices.
These profiles include various phones, tablets, wearables, and TVs.

o Choose a device model (e.g., Pixel 4, Nexus 5X, Android TV, etc.) that closely
matches the kind of device you want to test.

o After selecting the device, click Next.

Tip: If you need to create a custom device profile, you can click on "New Hardware Profile"
to define your custom configuration, including screen size, resolution, and other hardware
characteristics.

5. Select the System Image:

o The next step involves choosing a system image (Android version) that your
virtual device will run. The system image includes the Android operating system
and other essential components like Google APIs.

o You will see a list of available system images, including different versions of
Android (e.g., Android 10, Android 11, etc.).

o Select a system image based on the Android version you want to test. For
instance, you can select Android 10 (Q) or Android 11 (R).

o If you haven’t downloaded the system image yet, click on the Download link
next to the version, and it will automatically download and install it.

o Once downloaded, click Next.

6. Configure AVD Settings:

o After selecting the system image, you will be presented with the AVD
Configuration screen. Here, you can adjust the settings for your virtual device.
o Device Orientation: Set whether you want your device to be in portrait or
landscape mode.

o RAM and CPU settings: You can configure the RAM, VM heap, and CPU
architecture (ARM, x86, etc.) based on your system's capabilities.

o SD Card: Optionally, you can configure the SD Card size for your virtual device
if needed.

o Device Storage: Set the internal storage size of the device.

You can also click on Show Advanced Settings to modify other options like Network
Latency, Graphics, Emulated Performance, and more.

Once satisfied with the configuration, click Finish.

7. Launch the Virtual Device:

o Your newly created virtual device will now appear in the AVD Manager window
under "Virtual Devices".

o To run the virtual device, click the green Play button next to the device you just
created. This will launch the Android Emulator with the virtual device you
configured.

8. Wait for the Emulator to Start:

o The emulator will take some time to boot up, depending on your computer’s
specifications and the device you selected. Once the emulator is started, it will
appear as a virtual Android device on your screen.

o You can interact with the device just like a real Android device.

Optional: Customize Your Virtual Device

After creating your virtual device, you can always make changes or create additional AVDs:

1. Edit the Virtual Device Configuration:

o In the AVD Manager, click on the pencil icon next to your device name to edit its
configuration. You can modify settings like system images, memory, and storage
size.

2. Delete the Virtual Device:

o If you no longer need the virtual device, you can click on the trash can icon in
the AVD Manager to delete it.

Explain the view provides quick access to your project's key


files.
In Android Studio, the Project View is a crucial feature that provides a structured overview
of your project files and folders. It allows developers to quickly navigate and access key files
necessary for app development. The Project View organizes the files in a hierarchical format,
helping you locate and manage the various resources within your Android project, such as
source code, layouts, manifests, and configurations.
Key Features of the Project View in Android Studio

1. File Structure Overview:

o The Project View displays your project files in a hierarchical structure. This
structure represents the different directories and subdirectories that make up
your project. You can expand and collapse these directories to view their
contents.

The default project structure looks something like this:

ProjectName/

├── app/

│ ├── src/

│ │ ├── main/

│ │ │ ├── java/

│ │ │ │ └── com/

│ │ │ │ └── example/

│ │ │ │ └── myapp/

│ │ │ │ └── MainActivity.java

│ │ │ ├── res/

│ │ │ │ ├── layout/

│ │ │ │ │ └── activity_main.xml

│ │ │ │ └── values/

│ │ │ │ └── strings.xml

│ │ │ └── AndroidManifest.xml

│ └── build.gradle

├── build/

├── gradle/

└── settings.gradle

2. Different Views (Android, Project, and Packages): Android Studio offers different
ways to view your project structure:

o Android View: This is the most user-friendly and recommended view for most
Android developers. It simplifies the view by organizing the project files into
logical categories like Java, Resources, Manifests, Gradle Scripts, etc.

 It helps to separate the code, resources, and configuration files into distinct
sections, making it easier to navigate.

o Project View: This view shows the file structure exactly as it is in your file
system, with the complete directory structure. It's useful when you want to see
everything, including hidden files and non-Android-specific configurations.
o Packages View: This is a more traditional view, showing only the Java package
structure. It’s similar to how you would view packages in Java IDEs like IntelliJ or
Eclipse.

3. Quick Access to Key Files: The Project View allows you to quickly access essential
files and directories used in your Android app development:

o Java Code: The src/main/java/ directory contains all the Java files that define
the behavior of your app’s activities, services, and other components.

 Example: MainActivity.java will be found in the


src/main/java/com/example/myapp/ folder.

o Resources: The res/ folder contains various resources like layout XML files,
images, drawables, and values (strings, colors, dimensions).

 Example: activity_main.xml will be found in the res/layout/ folder.

o Manifest: The AndroidManifest.xml file is located in the src/main/ folder and is


essential for declaring the app’s components, permissions, and configuration.

o Gradle Scripts: The build.gradle file, located in the project’s root folder and
app/ folder, is crucial for managing dependencies, plugins, and project
configurations.

4. Search Functionality:

o Android Studio allows you to search for specific files or classes within the Project
View using the Search bar. You can quickly locate any file, class, or resource in
your project.

o To search, simply press Ctrl+Shift+N (or Cmd+Shift+O on macOS), and then


type the name of the file you are looking for.

5. Contextual Operations:

o You can perform many operations directly from the Project View using the right-
click (context) menu. Common operations include:

 New File: You can create new activities, layouts, or other resource files
directly from the Project View.

 Rename: You can rename files or directories.

 Delete: You can delete files or resources no longer needed.

 Show in Explorer/Finder: You can open the selected file or folder in your
system's file explorer.

6. Build and Run Configurations:

o The Gradle Scripts section in the Project View allows you to manage build
configurations, dependencies, and project setup. The build.gradle files define the
behavior of the Gradle build system.

Example of Using the Project View for Quick Access:

Let’s say you want to access the MainActivity.java file and the activity_main.xml layout
file:
1. In Android View:

o Navigate to app > src > main > java > com > example > myapp >
MainActivity.java to find the Java code.

o Navigate to app > src > main > res > layout > activity_main.xml to access
the XML layout.

2. In Project View:

o You can expand the directories to see the file structure exactly as it is on your file
system. This view shows you the raw structure, so you can see files like .gitignore
and build directories as well.

o Right-clicking on the file will allow you to open, delete, or refactor it easily.

What is android? Why develop apps for android?


Android operating system is the largest installed base among various mobile platforms
across the globe. Hundreds of millions of mobile devices are powered by Android in more
than 190 countries of the world. It conquered around 71% of the global market share by the
end of 2021, and this trend is growing bigger every other day. The company named Open
Handset Alliance developed Android for the first time that is based on the modified version
of the Linux kernel and other open-source software. Google sponsored the project at initial
stages and in the year 2005, it acquired the whole company. In September 2008, the first
Android-powered device was launched in the market. Android dominates the mobile OS
industry because of the long list of features it provides. It’s user-friendly, has huge
community support, provides a greater extent of customization, and a large number of
companies build Android-compatible smartphones. As a result, the market observes a sharp
increase in the demand for developing Android mobile applications, and with that companies
need smart developers with the right skill set. At first, the purpose of Android was thought of
as a mobile operating system. However, with the advancement of code libraries and its
popularity among developers of the divergent domain, Android becomes an absolute set of
software for all devices like tablets, wearables, set-top boxes, smart TVs, notebooks, etc.

Features of Android

Android is a powerful open-source operating system that open-source provides immense


features and some of these are listed below.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

 Android Open Source Project so we can customize the OS based on our requirements.

 Android supports different types of connectivity for GSM, CDMA, Wi-Fi, Bluetooth, etc.
for telephonic conversation or data transfer.

 Using wifi technology we can pair with other devices while playing games or using
other applications.

 It contains multiple APIs to support location-tracking services such as GPS.

 We can manage all data storage-related activities by using the file manager.

 It contains a wide range of media supports like AVI, MKV, FLV, MPEG4, etc. to play or
record a variety of audio/video.

 It also supports different image formats like JPEG, PNG, GIF, BMP, MP3, etc.

 It supports multimedia hardware control to perform playback or recording using a


camera and microphone.

 Android has an integrated open-source WebKit layout-based web browser to support


User Interfaces like HTML5, and CSS3.

 Android supports multi-tasking means we can run multiple applications at a time and
can switch between them.

 It provides support for virtual reality or 2D/3D Graphics.

Advantages of Android Development

 The Android is an open-source Operating system and hence possesses a vast


community for support.

 The design of the Android Application has guidelines from Google, which becomes
easier for developers to produce more intuitive user applications.

 Fragmentation gives more power to Android Applications. This means the application
can run two activities on a single screen.

 Releasing the Android application in the Google play store is easier when it is compared
to other platforms.
With neat diagram, show the major components of Android
stack.
Covered above

With neat diagram, explain the high-level picture of Android


app development process.
The Android app development process involves several stages, from conceptualizing an
app idea to deploying it on the Google Play Store or distributing it for use. Here’s a high-level
overview of the Android app development process, which typically follows a structured
workflow to build functional Android applications.

High-Level Picture of the Android App Development Process

Here is a breakdown of the stages involved in Android app development:

1. Idea & Planning:

o Define the app’s purpose: Understand the problem your app is solving or the
functionality it provides.

o Market research: Analyze existing solutions, competitors, and the target


audience.

o Platform considerations: Decide if the app will be Android-only or cross-


platform.

2. Design:

o Wireframing and Prototyping: Design the layout and user interface (UI) of the
app using tools like Figma, Adobe XD, or Sketch.

o User Experience (UX) design: Focus on designing an intuitive and responsive


interface.

o User Interface (UI) design: Create specific UI elements, icons, and app assets.

3. Development:

o Setup Development Environment: Install Android Studio, SDKs, and other


dependencies.

o Code the App:

 Frontend (UI): Develop activities, fragments, and layouts.

 Backend (Logic): Implement app logic, interactions with databases, APIs,


etc.

o Integrate Libraries & APIs: Integrate third-party libraries, SDKs, and services
such as Firebase, Google Maps, etc.

4. Testing:

o Unit Testing: Test individual components of the app (e.g., functions or methods)
using testing frameworks like JUnit.

o Integration Testing: Test how different parts of the app work together.
o UI Testing: Ensure the app’s UI is working as expected with frameworks like
Espresso.

o Manual Testing: Run the app on real devices or emulators to check for bugs or
usability issues.

5. Debugging:

o Use tools like Logcat, Android Profiler, and Breakpoints to find and fix bugs.

6. Building & Packaging:

o Build APK/Bundle: Use Android Studio to compile and package the app into an
APK (Android Package) or App Bundle (AAB) for distribution.

o Signing: Sign the APK or AAB with a private key for security and to allow it to be
installed on devices.

7. Deployment & Distribution:

o Google Play Store: Upload the APK/AAB to the Google Play Store, complete with
app descriptions, screenshots, and other metadata.

o Other Distribution Channels: Optionally distribute the APK via other platforms
or direct links.

8. Maintenance & Updates:

o Monitor App Performance: Track the app’s performance using tools like
Firebase Analytics and Google Play Console.

o Bug Fixes and Updates: Push regular updates to fix bugs, introduce new
features, and maintain compatibility with the latest Android versions.

Diagram of the High-Level Android App Development Process:

Below is a simple diagram illustrating the entire process:


List and explain the steps for starting and using the Android
studio.
Steps for Starting and Using Android Studio
Android Studio is the official Integrated Development Environment (IDE) for Android
development. It provides tools for building, testing, and debugging Android applications,
making it easier to develop high-quality apps. Below are the steps to start and use Android
Studio for developing Android applications:

1. Download and Install Android Studio

Step 1: Download Android Studio

 Go to the official Android Studio website.

 Click on the download button for your operating system (Windows, macOS, or Linux).

 Android Studio provides the latest stable version of the IDE with all the necessary SDKs
and tools.

Step 2: Install Android Studio

 For Windows:

o Run the downloaded .exe file and follow the installation instructions.

o Make sure to select the option to install the Android Virtual Device (AVD) if
prompted, as it is necessary for running your app on an emulator.

 For macOS:

o Open the downloaded .dmg file and drag the Android Studio icon to the
Applications folder.

 For Linux:

o Extract the downloaded .zip file and follow the instructions in the official
documentation.

2. Launch Android Studio

Step 1: Open Android Studio

 Once installed, open Android Studio by clicking on its icon (on Windows, macOS, or
Linux).

Step 2: Initial Setup (First-Time Launch)

 The first time you launch Android Studio, it will ask if you want to import previous
settings (if applicable). You can choose to import or select the "Do not import settings"
option.

 Android Studio will guide you through the setup process. This includes downloading the
necessary SDK components (such as Android SDK, Emulator, and required system
libraries).
3. Configure SDK and Emulator

Step 1: Set Up SDK (Software Development Kit)

 During the first launch, Android Studio will prompt you to install the Android SDK. The
SDK is essential for Android development, as it contains APIs and tools for building
Android applications.

 After installation, you can go to Preferences (macOS) / File > Settings


(Windows/Linux) to manage SDK components.

Step 2: Set Up an Emulator (Optional)

 Create a Virtual Device:

o If you don't have a physical Android device for testing, you can set up a virtual
device using the Android Emulator.

o In Android Studio, navigate to Tools > AVD Manager to create a new Android
Virtual Device (AVD).

o Choose a device type (e.g., Pixel, Nexus) and select the Android version (API
Level) you want to use for testing.

4. Create a New Android Project

Step 1: Start a New Project

 When you open Android Studio, click on Start a new Android Studio project to
create a new app.

Step 2: Choose a Template

 Android Studio provides various templates like Empty Activity, Basic Activity,
Navigation Drawer Activity, etc. Choose a template that best fits the structure of
your app.

Step 3: Configure Your Project

 Enter details about your project, including:

o Name: The name of your app.

o Package name: A unique identifier for your app (usually in reverse domain
format like com.example.myapp).

o Save location: Choose where to store the project on your computer.

o Language: Choose between Java or Kotlin as your programming language.

o Minimum API Level: Choose the lowest version of Android your app will
support.

Step 4: Set Up Project Files

 After the configuration, Android Studio will create the project with the necessary files
(like MainActivity.java or MainActivity.kt, activity_main.xml, etc.).

5. Write Code for Your Application


Step 1: Work on Java/Kotlin Code

 Open the MainActivity.java or MainActivity.kt file in the src folder to write the
functionality for your app. This file typically includes the main logic for starting your
app and handling user interactions.

Step 2: Design the UI

 Open the activity_main.xml file under the res/layout/ folder to design the user
interface.

 You can either write XML code directly or use the Layout Editor in Android Studio to
drag-and-drop elements (like buttons, text fields, etc.).

6. Build and Run Your Application

Step 1: Connect a Device

 If you're using a physical Android device for testing, enable Developer Mode and USB
Debugging on the device, then connect it via USB.

Step 2: Run the Application

 To run the application, click the Run button (the green triangle icon) at the top of
Android Studio.

 Select the device or emulator where you want to run your app.

Step 3: Build the APK/Bundle

 Android Studio automatically builds the APK file (Android Package) when you run the
app. You can also manually build the APK by selecting Build > Build APK from the
menu.

7. Test and Debug Your App

Step 1: Use the Android Emulator or Device

 Test the app on a virtual device (Android Emulator) or a physical Android device.

Step 2: Debugging

 You can debug the app using Logcat (to view logs), breakpoints, and Android
Profiler (to analyze app performance).

 Set breakpoints in the Java/Kotlin code by clicking on the left margin of the editor
window. When running the app in debug mode, it will pause at the breakpoints,
allowing you to inspect variables and step through the code.

8. Modify and Update Your Application

Step 1: Modify Code and UI

 Based on the testing feedback, modify the code or UI components (e.g., add new
features, fix bugs, improve performance).

Step 2: Test Again


 Re-run the app and test the changes to ensure they work correctly.

9. Prepare for Deployment

Step 1: Generate a Signed APK

 To distribute your app (e.g., via Google Play Store), you need to generate a signed
APK or App Bundle.

 Navigate to Build > Generate Signed APK and follow the instructions to create a
signed version of the app with a private key.

Step 2: Upload to Google Play Store (Optional)

 Once the APK is signed, you can upload it to the Google Play Store via the Google Play
Console.

 Fill out metadata (description, screenshots, etc.) for your app on the Play Store.

10. Monitor, Update, and Maintain Your App

 After deploying the app, use Google Analytics or Firebase to monitor the
performance and usage of your app.

 Regularly update your app to add new features, improve performance, and fix any bugs
based on user feedback.

How do you run app on virtual device and app on physical


device.
Running your Android app on both a virtual device (Android Emulator) and a physical
device (real Android device) is essential for testing and debugging your app in different
environments. Below are the steps for running your Android app on both a virtual device
and a physical device.

Running App on Virtual Device (Android Emulator)

1. Set Up Android Emulator:

Before running your app on an Android emulator, you need to have a Virtual Device
configured in Android Studio.

Step 1: Open AVD Manager

o In Android Studio, go to Tools > AVD Manager.

o If you haven't created a virtual device yet, click on Create Virtual Device.

Step 2: Create a Virtual Device

o Select a device from the list of available devices (e.g., Pixel 4, Nexus 5X).

o Click Next.
o Choose a system image (select the Android version you want to use).

o Download the system image if necessary.

o Once the system image is downloaded, click Next.

Step 3: Configure Emulator Settings

o You can modify settings like device orientation, RAM allocation, and graphics
settings if needed.

o Click Finish to create the virtual device.

2. Run App on Emulator:

Step 1: Select the Emulator as the Target Device

o In Android Studio, click on the Run button (green triangle icon) at the top of the
IDE.

o In the Select Deployment Target dialog, you will see your virtual device listed
as an available target device. Choose the virtual device you created earlier and
click OK.

Step 2: Wait for the Emulator to Start

o The emulator will boot up, which may take a few seconds to a few minutes,
depending on your computer’s resources.

o Once the emulator is ready, the app will be launched automatically.

3. Interact with Your App on the Emulator:

o You can now interact with your app on the virtual device. The emulator behaves
like a real Android device, allowing you to test the app’s UI and functionality.

Running App on Physical Device

Running your app on a real Android device is essential to test performance and real-world
interactions.

1. Enable Developer Options and USB Debugging on the Physical Device:

Step 1: Enable Developer Options

o Go to Settings > About phone on your Android device.

o Tap the Build number 7 times to enable Developer Options.

Step 2: Enable USB Debugging

o Once Developer Options is enabled, go to Settings > Developer options.

o Toggle USB debugging to "On".

2. Connect the Physical Device to Your Computer:

o Connect your Android device to your computer via USB cable.

o Ensure that you allow USB debugging on the device if a prompt appears on the
screen (select Allow or OK).
3. Install Device Drivers (if necessary):

o For Windows users, ensure that the correct drivers for your device are installed.
For most popular Android devices, Windows will automatically install the drivers,
but you may need to manually install drivers for some devices.

o You can find the official drivers on the manufacturer's website (e.g., for Samsung,
Google, etc.).

4. Run the App on Your Physical Device:

Step 1: Select the Device as the Target

o In Android Studio, click the Run button (green triangle).

o In the Select Deployment Target window, you should see your connected
physical device listed under Connected Devices.

o Select your physical device and click OK.

Step 2: Wait for the App to Build and Install

o Android Studio will build your app and install it on your physical device.

o Once the process is complete, the app will launch on your Android device.

5. Interact with Your App on the Physical Device:

o You can now test the app on the actual device. This allows you to check the app’s
real-world performance, response time, and device-specific features (like GPS,
sensors, etc.).

Troubleshooting Tips

 Emulator Not Launching: If the emulator doesn't launch, ensure that your system
has sufficient resources (RAM, CPU) and that Intel HAXM or AMD Hypervisor (for
Windows/Linux) is installed.

 Device Not Recognized: Ensure USB debugging is enabled and that the device is
properly connected via USB. Also, make sure the correct drivers are installed.

 Running App Too Slow on Emulator: The emulator may run slower than a physical
device. You can increase performance by enabling hardware acceleration (e.g., using
Intel HAXM on Intel processors) or adjusting the emulator settings (such as reducing
the resolution or limiting background processes).

What is Activity navigation? Explain 2 forms of navigation


strategies.
Activity Navigation in Android

In Android, Activity Navigation refers to the process of managing how users move from one
screen (Activity) to another within an application. An Activity is a single screen in an app
that represents a user interface and handles the interaction between the user and the app.
Managing activity navigation effectively is crucial to providing a smooth, intuitive user
experience.

Android provides several navigation strategies to control the flow of activities and
facilitate user movement between screens. Two common strategies for navigation are:

1. Explicit Navigation

2. Implicit Navigation

Additionally, Android’s Navigation Component (introduced in Android Jetpack) provides


advanced, modular, and flexible navigation capabilities that we will mention later.

1. Explicit Navigation

Explicit Navigation refers to specifying the exact Activity or component to navigate to. This
form of navigation is intent-based and is commonly used when you know exactly which
Activity or component needs to be launched.

How it works:

 You explicitly call an Activity from another Activity using an Intent.

 You specify the exact Activity class that you want to launch.

Example:

// In Activity A, we navigate to Activity B using an explicit intent

Intent intent = new Intent(ActivityA.this, ActivityB.class);

startActivity(intent);

In this example:

 The Intent is created to explicitly navigate from ActivityA to ActivityB.

 startActivity() launches the second activity (ActivityB).

Use Cases:

 Use explicit navigation when you know the destination and want to navigate to a
specific screen.

 Commonly used for navigating between app screens, such as from a login screen to a
dashboard.

2. Implicit Navigation

Implicit Navigation doesn't specify the exact Activity to navigate to. Instead, it relies on the
system to find the appropriate component that can handle a certain action or intent filter.

This is more flexible because it can invoke any Activity or app that is capable of performing
the given action, even if the destination Activity is not known in advance.

How it works:
 Implicit navigation involves using an Intent with a specific action or category, and the
Android system uses the Intent filters defined in the manifest to determine the
appropriate component to handle the request.

Example:

// Implicit intent to open the browser for a URL

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.example.com"));

startActivity(intent);

In this example:

 The ACTION_VIEW intent is implicit, as it doesn't specify which app should handle it.

 The Android system searches for apps with the proper Intent filter (e.g., web browsers)
and opens the URL in one of those apps.

Use Cases:

 Use implicit navigation when you want to perform an action that can be handled by
other apps or when the specific destination is not known at the time of launch.

 Common examples include opening a URL, sending an email, or opening a map.

Two Main Forms of Navigation Strategies in Android

Besides explicit and implicit navigation, Android offers several navigation strategies to
organize app flow, including:

**1. Navigation Drawer

The Navigation Drawer is a common UI pattern that slides in from the left side of the
screen, providing a menu for users to navigate between different sections of the app. It is
often used for global navigation in apps with multiple sections or categories.

 Common in apps like: Gmail, YouTube, and Facebook.

How it works:

 A DrawerLayout is used, and the app defines various navigation options inside the
drawer.

 Users can tap on the items in the drawer to navigate between Activities or fragments.

Example:

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/drawer_layout"

android:layout_width="match_parent"

android:layout_height="match_parent">

<!-- Content of the app (usually a Fragment or Activity) -->

<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragment_container"

android:layout_width="match_parent"

android:layout_height="match_parent"/>

<!-- Navigation Drawer Content -->

<androidx.recyclerview.widget.RecyclerView

android:id="@+id/navigation_drawer"

android:layout_width="wrap_content"

android:layout_height="match_parent"/>

</androidx.drawerlayout.widget.DrawerLayout>

2. Bottom Navigation

The Bottom Navigation is a UI element placed at the bottom of the screen that allows quick
navigation between top-level views in the app. It is especially useful for apps with 3-5 top-
level destinations.

 Common in apps like: Instagram, YouTube, and Spotify.

How it works:

 A BottomNavigationView is used in the layout.

 The app defines items that represent different sections or activities, and users can
switch between these sections by tapping the corresponding icon.

Example:

<com.google.android.material.bottomnavigation.BottomNavigationView

android:id="@+id/bottom_navigation"

android:layout_width="match_parent"

android:layout_height="wrap_content"

app:menu="@menu/bottom_nav_menu"/>

In this example:

 The BottomNavigationView uses a menu resource to define items.

 Each item corresponds to a different activity or fragment.

Explain XML attributes using TextView as example.


In Android, XML attributes are used to define the properties and behavior of UI components
(such as buttons, text fields, and views) in the layout files. These attributes allow you to
customize the appearance, style, and behavior of a UI element.
Let's use the TextView widget as an example to explore various XML attributes and how they
can be used to customize it.

TextView Example:

Here’s a simple example of a TextView in an Android layout file (activity_main.xml):

<TextView

android:id="@+id/myTextView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, Android!"

android:textSize="18sp"

android:textColor="#FF5733"

android:gravity="center"

android:padding="16dp"

android:background="@drawable/rounded_background" />

In this example, the TextView has several XML attributes defined, which are used to style
and customize it. Below are explanations of some of the common attributes used for a
TextView.

Common XML Attributes for TextView:

1. android:id

o Purpose: Defines the unique identifier for the TextView.

o Example: android:id="@+id/myTextView"

o This allows you to reference this TextView in your Java or Kotlin code (e.g.,
findViewById(R.id.myTextView)).

2. android:layout_width and android:layout_height

o Purpose: Specifies the width and height of the TextView.

o Example: android:layout_width="wrap_content" and


android:layout_height="wrap_content"

o These attributes determine the size of the TextView based on its content.

 wrap_content: The size of the TextView will be just enough to fit the content
(e.g., text).

 match_parent: The TextView will expand to fill the available space.

3. android:text

o Purpose: Defines the text that is displayed in the TextView.

o Example: android:text="Hello, Android!"

o This attribute sets the actual text content that will appear in the TextView.
4. android:textSize

o Purpose: Defines the font size of the text.

o Example: android:textSize="18sp"

o This attribute sets the size of the text in scale-independent pixels (sp), which
ensures that text is scaled appropriately for different screen densities and user
preferences.

5. android:textColor

o Purpose: Specifies the color of the text.

o Example: android:textColor="#FF5733"

o You can use either a color code (like #FF5733 for a shade of red) or a predefined
color resource (like @android:color/black) to set the text color.

6. android:gravity

o Purpose: Controls the alignment of the text within the TextView.

o Example: android:gravity="center"

o The value can be one or more of the following:

 left, right, center: Aligns text horizontally.

 top, bottom, center_vertical: Aligns text vertically.

 center: Centers the text both horizontally and vertically.

7. android:padding

o Purpose: Adds space around the content of the TextView.

o Example: android:padding="16dp"

o This attribute adds padding (spacing) on all sides of the text within the TextView.
You can also use more specific padding attributes like android:paddingLeft,
android:paddingRight, etc.

8. android:background

o Purpose: Sets the background of the TextView.

o Example: android:background="@drawable/rounded_background"

o You can set a background color, image, or drawable resource here. In this case, a
drawable resource (rounded_background) is used to set a custom background,
such as a rounded shape.

9. android:maxLines

o Purpose: Defines the maximum number of lines of text that can be displayed.

o Example: android:maxLines="2"

o If the text exceeds the number of lines specified, it will be truncated, and the
extra text will not be shown.

10. android:ellipsize
o Purpose: Controls how to handle text that overflows in a TextView.

o Example: android:ellipsize="end"

o If the text is too long to fit, you can specify that the overflowed part of the text
should be replaced with an ellipsis (...). Other options include start, middle, or
marquee.

Other Useful Attributes for TextView:

1. android:typeface

o Purpose: Sets the font family for the text.

o Example: android:typeface="monospace"

2. android:lineSpacingExtra and android:lineSpacingMultiplier

o Purpose: Controls the spacing between lines of text.

o Example:

 android:lineSpacingExtra="4dp": Adds extra space between lines.

 android:lineSpacingMultiplier="1.2": Increases the space by a factor.

3. android:shadowColor, android:shadowDx, android:shadowDy, and


android:shadowRadius

o Purpose: Adds a shadow effect to the text.

o Example:

android:shadowColor="#66000000"

android:shadowDx="2"

android:shadowDy="2"

android:shadowRadius="4"

Example of a Fully Customized TextView

Here is a more complex example of a TextView with multiple attributes:

<TextView

android:id="@+id/helloTextView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Welcome to Android!"

android:textSize="20sp"

android:textColor="#FF4081"

android:gravity="center"

android:padding="20dp"
android:background="@drawable/rounded_border"

android:maxLines="3"

android:ellipsize="end"

android:typeface="serif"

android:lineSpacingExtra="4dp"

android:shadowColor="#55000000"

android:shadowDx="2"

android:shadowDy="2"

android:shadowRadius="4" />

 This example creates a centered, pink-colored text ("Welcome to Android!") with


shadow effects, padding, a rounded border background, and other customization
options such as line spacing and handling overflow text.

Explain the Passing of data between activities with intents.


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.

Example:

In this example, one EditText is used to input the text. This text is sent to the second activity
when the “Send” button is clicked. For this, Intent will start and the following methods will
run:

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

 putExtra() method is used for sending the data, data in key-value pair key is variable
name and value can be Int, String, Float, etc.
 getStringExtra() method is for getting the data(key) that is sent by the above
method. According to the data type of value, there are other methods
like getIntExtra(), getFloatExtra()

How to Create an Android App to Send and Receive the Data between Two Activity

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New
Project in Android Studio . The code for that has been given in both Java and Kotlin
Programming Language for Android. This will create an XML file and a Java File. Please
refer to the prerequisites to learn more about this step.

Step 2: 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"

Here the given IDs are as follows:

 Send Button: send_button_id

 input EditText: send_text_id

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

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


Step 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the
MainActivity File. Comments are added inside the code to understand the code in more detail.
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

import android.content.Intent;

import android.os.Bundle;

import android.widget.Button;

import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

public class first_activity extends AppCompatActivity {

// define the variable

Button send_button;

EditText send_text;

@Override

protected void onCreate(Bundle savedInstanceState) {

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(v -> {

// get the value which input by user in EditText and convert it to string

String str = send_text.getText().toString();

// Create the Intent object of this class Context() to Second_activity class

Intent intent = new Intent(getApplicationContext(), Second_activity.class);


// 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);

});

Step 4: Creating Second_Activity to Receive the Data.

The steps to create the second activity are as follows:

android project > File > new > Activity > Empty Activity

Step 5: Working with the Second XML File

Add TextView to display the received messages. assign an ID to Textview.

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

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:

Step 6: 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);

import android.content.Intent;

import android.os.Bundle;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class Second_activity extends AppCompatActivity {

TextView receiver_msg;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second_activity);

receiver_msg = findViewById(R.id.received_value_id);

// create the get Intent object

Intent intent = getIntent();

// receive the value by getStringExtra() method and

// key must be same which is send by first activity

String str = intent.getStringExtra("message_key");

// display the string into textView

receiver_msg.setText(str);

Output:
Discuss about Android Application Lifecycle
What Is Android?

Android is a mobile operating system that is based on a modified version of Linux. It was
originally

developed by a startup of the same name, Android, Inc. In 2005, as part of its strategy to
enter the

mobile space, Google purchased Android and took over its development work (as well as its
development

team).

The main advantage of adopting Android is that it offers a unified approach to application
development.

Developers need only develop for Android, and their applications should be able to run on
numerous

different devices, as long as the devices are powered using Android. In the world of
smartphones, applications

are the most important part of the success chain. Device manufacturers therefore see
Android

as their best hope to challenge the onslaught of the iPhone, which already commands a large
base of

applications.

Architecture of Android

In order to understand how Android works, take a look at Figure 1-1, which shows the various
layers

that make up the Android operating system (OS).


The Android OS is roughly divided into five sections in four main layers:

 Linux kernel — This is the kernel on which Android is based. This layer contains all the
lowlevel

device drivers for the various hardware components of an Android device.

 Libraries — These contain all the code that provides the main features of an Android
OS. For

example, the SQLite library provides database support so that an application can use it for

data storage. The WebKit library provides functionalities for web browsing.

 Android runtime — At the same layer as the libraries, the Android runtime provides a
set of core

libraries that enable developers to write Android apps using the Java programming language.
The

Android runtime also includes the Dalvik virtual machine, which enables every Android
application

to run in its own process, with its own instance of the Dalvik virtual machine (Android

applications are compiled into the Dalvik executables). Dalvik is a specialized virtual machine

designed specifically for Android and optimized for battery-powered mobile devices with
limited

memory and CPU.


 Application framework — Exposes the various capabilities of the Android OS to
application

developers so that they can make use of them in their applications.

 Applications — At this top layer, you will find applications that ship with the Android
device

(such as Phone, Contacts, Browser, etc.), as well as applications that you download and
install

from the Android Market. Any applications that you write are located at this layer.

Describe the life cycle of an Android activity with neat sketch?


Activity Lifecycle in Android with Demo App
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.

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

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

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

4. 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. For a deeper understanding and practical experience of
handling lifecycle events in Kotlin, the Android Mastery with Kotlin: Beginner to
Advanced course provides hands-on projects and in-depth lessons
Detailed introduction on each of the method is stated as follows:

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

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.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

// Bundle containing previous frozen state

setContentView(R.layout.activity_main);

// The content view pointing to the id of layout

// in the file activity_main.xml

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();

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.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

// Bundle containing previous frozen state

setContentView(R.layout.activity_main);
// The content view pointing to the id of layout

// in the file activity_main.xml

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();

protected void onStart()

// It will show a message on the screen

// then onStart is invoked

Toast toast = Toast.makeText(getApplicationContext(), "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.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Bundle containing previous frozen state

setContentView(R.layout.activity_main);

// The content view pointing to the id of layout

// in the file activity_main.xml

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();
}

protected void onRestart() {

// It will show a message on the screen

// then onRestart is invoked

Toast toast = Toast.makeText(getApplicationContext(), "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:

JavaKotlin

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

import com.example.share.R;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

// Bundle containing previous frozen state

super.onCreate(savedInstanceState);

// The content view pointing to the id of layout

// in the file activity_main.xml

setContentView(R.layout.activity_main);

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();
}

protected void onResume() {

// It will show a message on the screen

// then onResume is invoked

Toast toast = Toast.makeText(getApplicationContext(), "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.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

// Bundle containing previous frozen state

super.onCreate(savedInstanceState);

// The content view pointing to the id of layout

// in the file activity_main.xml

setContentView(R.layout.activity_main);

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();

}
protected void onPause() {

// It will show a message on the screen

// then onPause is invoked

Toast toast = Toast.makeText(getApplicationContext(), "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. Note that
this method may never be called, in low memory situations where the system does not have
enough memory to keep the activity’s process running after its onPause() method is called.

Example:

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

// Bundle containing previous frozen state

super.onCreate(savedInstanceState);

// The content view pointing to the id of layout

// in the file activity_main.xml

setContentView(R.layout.activity_main);

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();

protected void onStop() {

// It will show a message on the screen


// then onStop is invoked

Toast toast = Toast.makeText(getApplicationContext(), "onStop Called",


Toast.LENGTH_LONG).show();

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. To distinguish between these scenarios, check it
with isFinishing() method.

Example:

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

// Bundle containing previous frozen state

super.onCreate(savedInstanceState);

// The content view pointing to the id of layout

// in the file activity_main.xml

setContentView(R.layout.activity_main);

Toast toast = Toast.makeText(getApplicationContext(), "onCreate Called",


Toast.LENGTH_LONG).show();

protected void onDestroy() {

// It will show a message on the screen

// then onDestroy is invoked

Toast toast = Toast.makeText(getApplicationContext(), "onDestroy Called",


Toast.LENGTH_LONG).show();
}

List and Explain the Resource files.


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

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

Organize resource in Android Studio

Sr.N Directory & Resource Type


o.
1 anim/
XML files that define property animations. They are saved in res/anim/ folder and
accessed from the R.anim class.
2 color/
XML files that define a state list of colors. They are saved in res/color/ and accessed
from the R.color class.
3 drawable/
Image files like .png, .jpg, .gif or XML files that are compiled into bitmaps, state lists,
shapes, animation drawable. They are saved in res/drawable/ and accessed from
the R.drawable class.
4 layout/
XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.
5 menu/
XML files that define application menus, such as an Options Menu, Context Menu, or
Sub Menu. They are saved in res/menu/ and accessed from the R.menu class.
6 raw/
Arbitrary files to save in their raw form. You need to
call Resources.openRawResource() with the resource ID, which is R.raw.filename to
open such raw files.
7 values/
XML files that contain simple values, such as strings, integers, and colors. For
example, here are some filename conventions for resources you can create in this
directory −
 arrays.xml for resource arrays, and accessed from the R.array class.
 integers.xml for resource integers, and accessed from the R.integer class.
 bools.xml for resource boolean, and accessed from the R.bool class.
 colors.xml for color values, and accessed from the R.color class.
 dimens.xml for dimension values, and accessed from the R.dimen class.
 strings.xml for string values, and accessed from the R.string class.
 styles.xml for styles, and accessed from the R.style class.
8 xml/
Arbitrary XML files that can be read at runtime by calling Resources.getXML(). You
can save various configuration files here which will be used at run time.

Alternative Resources
Your application should provide alternative resources to support specific device
configurations. For example, you should include alternative drawable resources ( i.e.images )
for different screen resolution and alternative string resources for different languages. At
runtime, Android detects the current device configuration and loads the appropriate
resources for your application.

To specify configuration-specific alternatives for a set of resources, follow the following steps

 Create a new directory in res/ named in the form <resources_name>-


<config_qualifier>. Here resources_name will be any of the resources mentioned in
the above table, like layout, drawable etc. The qualifier will specify an individual
configuration for which these resources are to be used. You can check official
documentation for a complete list of qualifiers for different type of resources.

 Save the respective alternative resources in this new directory. The resource files must
be named exactly the same as the default resource files as shown in the below
example, but these files will have content specific to the alternative. For example
though image file name will be same but for high resolution screen, its resolution will
be high.

Below is an example which specifies images for a default screen and alternative images for
high resolution screen.
Below is another example which specifies layout for a default language and alternative layout
for Arabic language.

Accessing Resources
During your application development you will need to access defined resources either in your
code, or in your layout XML files. Following section explains how to access your resources in
both the scenarios −

Accessing Resources in Code

When your Android application is compiled, a R class gets generated, which contains
resource IDs for all the resources available in your res/ directory. You can use R class to
access that resource using sub-directory and resource name or directly resource ID.

Example

To access res/drawable/myimage.png and set an ImageView you will use following code −

ImageView imageView = (ImageView) findViewById(R.id.myimageview);


imageView.setImageResource(R.drawable.myimage);

Here first line of the code make use of R.id.myimageview to get ImageView defined with
id myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to
get an image with name myimage available in drawable sub-directory under /res.

Example

Consider next example where res/values/strings.xml has following definition −

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

<resources>

<string name="hello">Hello, World!</string>

</resources>

Now you can set the text on a TextView object with ID msg using a resource ID as follows −

TextView msgTextView = (TextView) findViewById(R.id.msg);

msgTextView.setText(R.string.hello);

Example

Consider a layout res/layout/activity_main.xml with the following definition −

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

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

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

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, I am a TextView" />

<Button android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, I am a Button" />

</LinearLayout>

This application code will load this layout for an Activity, in the onCreate() method as follows

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Accessing Resources in XML


Consider the following resource XML res/values/strings.xml file that includes a color resource
and a string resource −

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

<resources>

<color name="opaque_red">#f00</color>

<string name="hello">Hello!</string>

</resources>

Now you can use these resources in the following layout file to set the text color and text
string as follows −

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

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

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:textColor="@color/opaque_red"

android:text="@string/hello" />

Discuss the framework of Android studio.


Covered above

Explain the activity life cycle.


Covered above

How does Mobile Computing work? Discuss Mobile Software


Engineering?
How Does Mobile Computing Work?
Mobile computing refers to the ability to use computing devices (smartphones, tablets,
laptops, etc.) while on the move, without being constrained to a fixed location. Mobile
computing is achieved through wireless technologies, allowing devices to communicate and
access data via networks such as cellular networks, Wi-Fi, and Bluetooth.

The primary components of mobile computing are:

1. Mobile Devices (Hardware):


o Mobile devices are the physical units used for mobile computing. These devices
have hardware components like processors, memory, storage, touchscreens,
cameras, sensors (GPS, accelerometer, gyroscope), and wireless communication
modules (Wi-Fi, Bluetooth, cellular).

o Examples: Smartphones, Tablets, Laptops, Wearables (e.g., smartwatches).

2. Mobile Networks:

o Mobile computing relies on wireless networks to transmit data. These include


cellular networks (3G, 4G, 5G), Wi-Fi, and Bluetooth. The networks allow mobile
devices to connect to the internet, other devices, and cloud services.

o Cellular networks are typically used for internet access and phone calls, while Wi-
Fi is used in local areas for high-speed internet.

3. Mobile Software:

o Mobile software includes the operating system and applications that run on
mobile devices. Popular mobile operating systems include Android and iOS.

o Applications in mobile computing use software APIs to access hardware features


(camera, GPS, sensors) and cloud-based services (e.g., storage, databases).

4. Cloud Computing:

o Cloud computing provides back-end services that mobile devices rely on for data
storage, processing, and other computational tasks. Mobile devices use cloud
computing to access data, applications, and services remotely, reducing the need
for local storage and processing power.

5. Mobile Data Management:

o Data is transferred wirelessly between mobile devices and servers. Mobile data
management tools allow synchronization and storage of data across devices and
cloud services, enabling access to the most up-to-date information on any device.

Basic Working of Mobile Computing:

1. Data Input:

o Data is input through the device’s interface (touchscreen, voice, sensors). For
example, users might input text or interact with a mobile app using gestures or
voice commands.

2. Data Transmission:

o The device communicates with the network using wireless technologies (Wi-Fi,
4G, 5G, Bluetooth). The data (e.g., requests, commands, or updates) is sent over
the internet or a local network to remote servers or devices.

3. Data Processing:

o The server or cloud platform processes the incoming data. For example, when a
user accesses a mobile app, the app may fetch data from a server, run
computations, or use cloud services to execute tasks.

4. Data Output:
o The output (e.g., responses, content) is sent back to the mobile device. The
mobile device displays the results or provides feedback to the user.

Mobile Software Engineering


Mobile software engineering is the field of software development that focuses on the creation
of software applications for mobile devices. Mobile software engineering involves
understanding the unique challenges and constraints of mobile environments (e.g., limited
resources, small screens, wireless connectivity) and applying engineering practices to build
high-quality mobile applications.

Key Aspects of Mobile Software Engineering:

1. Mobile App Development:

o Platform-specific Development:

 Android: Uses Java or Kotlin as the primary programming languages.


Android apps are built using the Android SDK, which provides a
comprehensive set of tools to interact with mobile device features (camera,
GPS, sensors, etc.).

 iOS: Uses Objective-C or Swift as programming languages. iOS apps are


developed using the iOS SDK and the Xcode development environment.

o Cross-platform Development:

 Cross-platform frameworks like Flutter, React Native, and Xamarin allow


developers to write code once and deploy on multiple platforms (Android,
iOS).

2. Mobile App Architecture:

o Mobile app architecture defines the structure of the app, and it focuses on the
organization of code, components, and data management. Common patterns
include:

 Model-View-Controller (MVC)

 Model-View-ViewModel (MVVM)

 Clean Architecture

 Reactive programming (e.g., using RxJava or RxSwift)

3. Mobile UI/UX Design:

o User Interface (UI) refers to the visual design of the app (layouts, colors,
typography), and User Experience (UX) refers to how users interact with the
app and how intuitive the app feels. Designing for mobile involves working within
the limitations of smaller screen sizes, varied device types, and different user
contexts (e.g., one-handed usage, touch gestures).

o Responsive Design: Ensures the app works well on different screen sizes and
orientations (portrait vs. landscape).

4. Performance Optimization:
o Mobile devices have limited resources (CPU, memory, battery). Therefore,
optimizing app performance is crucial for delivering a smooth experience.
Strategies for performance optimization include:

 Minimizing network usage

 Optimizing memory usage

 Reducing CPU-intensive tasks

 Efficient use of battery resources

5. Mobile Security:

o Mobile apps handle sensitive data, so ensuring security is critical. Mobile app
security involves protecting user data, securing network communications, and
ensuring the integrity of the app. Key practices include:

 Data Encryption: Ensuring that sensitive data is encrypted, both at rest


and in transit.

 Authentication & Authorization: Using authentication mechanisms (e.g.,


biometrics, OAuth, two-factor authentication) to verify user identity.

 App Sandboxing: Ensuring that the app operates in a restricted


environment, minimizing the risk of unauthorized access to system
resources.

6. Testing and Debugging:

o Testing mobile applications involves ensuring that the app works properly across
various devices, screen sizes, and operating system versions. Types of tests
include:

 Unit Testing: Testing individual functions or methods.

 UI Testing: Ensuring that the app’s user interface works as expected.

 Integration Testing: Ensuring that various components (e.g., UI, backend)


work together.

 Performance Testing: Testing the app's performance under different


conditions (e.g., high traffic, limited resources).

7. Deployment and Maintenance:

o App Deployment: Mobile apps are distributed via app stores (Google Play Store
for Android and Apple App Store for iOS). Each store has specific guidelines for
app submission, review, and release.

o App Updates and Maintenance: Mobile apps require regular updates to fix
bugs, improve performance, and introduce new features. Maintenance involves
monitoring app performance, user feedback, and staying up-to-date with OS
updates.

Challenges in Mobile Software Engineering:

1. Device Fragmentation:
o There is a wide variety of devices with different screen sizes, hardware
specifications, and OS versions. Mobile engineers must account for this
fragmentation to ensure the app works across all devices.

2. Battery Consumption:

o Mobile devices have limited battery life, and apps that consume too much power
will negatively affect the user experience.

3. Network Connectivity:

o Mobile apps often rely on network connectivity to access data or services.


Network issues like low bandwidth, latency, or intermittent connections must be
handled gracefully in the app.

4. Security Risks:

o Mobile apps are often targets for cyber-attacks. Protecting user data and ensuring
secure communications are constant concerns for developers.

5. User Experience (UX):

o Designing an intuitive and user-friendly experience for small screens and diverse
contexts is a challenge. Apps must be easy to navigate and accessible.

Discuss in detail different mobile computing techniques in


IOT.
Mobile Computing Techniques in IoT (Internet of Things)

Mobile computing is a critical enabler of the Internet of Things (IoT), as it provides the
infrastructure for mobile devices to interact with IoT devices and systems. IoT typically
involves a network of connected devices, sensors, actuators, and other embedded systems
that collect and exchange data. The use of mobile computing techniques ensures that users
can access, control, and interact with IoT devices from anywhere at any time. Here’s an in-
depth look at the mobile computing techniques applied to IoT:

1. Mobile Applications for IoT Control and Monitoring

 Overview: Mobile applications serve as the interface between users and IoT devices.
These applications allow users to remotely control and monitor IoT devices, such as
smart home appliances, wearables, industrial machines, and healthcare devices.

 Techniques:

o Cloud Integration: Many IoT devices store and process data in the cloud. Mobile
applications use cloud services to fetch, update, and synchronize data. For
example, a user can monitor the data from a smart thermostat or security
camera via a mobile app.

o Real-time Data Processing: Mobile apps use technologies like WebSockets,


MQTT (Message Queuing Telemetry Transport), and HTTP/2 to communicate
with IoT devices in real-time. For example, a smart home app can instantly
display the temperature reading from a smart thermometer or the status of a
smart light bulb.
 Example: A mobile app can control a smart thermostat by adjusting the temperature,
setting schedules, and receiving notifications about changes in the home environment.

2. Data Communication Protocols

 Overview: Mobile devices communicate with IoT devices through different wireless
communication protocols. These protocols ensure reliable and efficient data
transmission between mobile devices and IoT networks.

 Techniques:

o Bluetooth Low Energy (BLE): BLE is widely used for short-range


communication between mobile devices and IoT devices. BLE is energy-efficient
and ideal for battery-powered devices such as wearables, health monitors, and
IoT sensors.

o Wi-Fi: Mobile devices use Wi-Fi to communicate with IoT devices that are
connected to the same local network. Wi-Fi is more suitable for high-bandwidth
applications, such as streaming data from security cameras or controlling smart
appliances.

o Zigbee and Z-Wave: These protocols are used in home automation for device
communication. While Zigbee is designed for low power consumption and low
data rates, Z-Wave is commonly used in home security and energy monitoring.

o Cellular (LTE/5G): Mobile devices also use cellular networks for communication
with IoT devices, especially for IoT applications that require long-range
communication and constant connectivity, such as fleet management, remote
surveillance, and agriculture monitoring.

o LoRaWAN (Long Range Wide Area Network): LoRaWAN is ideal for low-
power, long-range communication for IoT applications, such as environmental
monitoring, smart agriculture, and asset tracking. Mobile applications can
connect to IoT devices via LoRaWAN gateways.

 Example: A smart home app uses BLE to connect to smart locks and Wi-Fi to control air
conditioning systems.

3. Edge and Fog Computing

 Overview: Edge and fog computing enable data processing closer to the source of
data generation (IoT devices), reducing latency and bandwidth usage. In IoT, mobile
devices can leverage edge and fog computing for faster responses and local decision-
making.

 Techniques:

o Edge Computing: IoT devices process data locally on the device or near the
device (in edge nodes) before sending it to the cloud. For example, smart
cameras can analyze video streams locally to detect motion or faces, reducing
the need to send raw video data to the cloud for analysis.

o Fog Computing: Fog computing extends cloud computing by processing data at


intermediate nodes between devices and the cloud (such as gateways). It
reduces the burden on the cloud and increases efficiency by processing time-
sensitive data locally.
o Mobile Edge Computing (MEC): In mobile computing, MEC involves using
mobile devices as edge nodes to process and store data locally. This technique
can reduce latency and allow for real-time data processing and decision-making.

 Example: In a smart agriculture system, a mobile app can interact with IoT devices in
the field, but data analysis happens at a local edge server or mobile device to control
irrigation based on local weather data.

4. Cloud Computing for IoT Integration

 Overview: Cloud computing provides scalable storage and processing power for IoT
devices. Mobile devices can access the cloud to retrieve data, manage devices, and
perform analytics in real-time.

 Techniques:

o Cloud-based APIs: Mobile devices use RESTful APIs or GraphQL APIs to


communicate with cloud services, which manage IoT device data. For example, a
cloud service may provide an API to control a smart appliance remotely.

o Serverless Computing: In IoT, serverless architecture helps in managing the


backend of mobile IoT applications. With serverless computing (e.g., AWS
Lambda), cloud services execute code without provisioning or managing servers,
reducing overhead for mobile IoT applications.

o IoT Cloud Platforms: Cloud platforms like AWS IoT, Google Cloud IoT, and
Microsoft Azure IoT offer IoT-specific services to manage devices, process data,
and integrate with mobile applications.

 Example: A mobile app that interacts with a smart thermostat can pull data from the
cloud to update settings and display the current temperature in real-time.

5. Location-Based Services (LBS)

 Overview: Location-based services enable mobile devices to interact with IoT systems
based on the user’s physical location. Using GPS, Wi-Fi, or Bluetooth, mobile apps can
retrieve location data to trigger actions in IoT devices.

 Techniques:

o Geofencing: Geofencing allows mobile devices to trigger events when they


enter or leave a predefined geographical area. IoT devices, such as smart
security systems or home appliances, can be automatically controlled when the
mobile device enters or leaves the home zone.

o Indoor Positioning Systems (IPS): IPS technologies like Bluetooth Low Energy
(BLE) beacons enable accurate indoor navigation. Mobile devices can interact
with IoT systems inside buildings for applications like asset tracking, smart retail,
or navigation within large facilities.

 Example: A smart door lock could automatically unlock when a user’s mobile device
enters the home geofence, or a mobile app could track a package’s location in a
warehouse using BLE.

6. Security and Privacy Techniques for Mobile IoT

 Overview: Security is critical in IoT systems as they are prone to hacking, data
breaches, and unauthorized access. Mobile devices often serve as gateways for
interacting with IoT devices, so ensuring secure communication between mobile apps
and IoT devices is essential.

 Techniques:

o Encryption: IoT communications between mobile devices and IoT systems can
be secured using encryption protocols such as SSL/TLS, ensuring the
confidentiality of sensitive data during transmission.

o Authentication and Authorization: Using mechanisms like OAuth2, biometric


authentication (fingerprint or facial recognition), and two-factor authentication
(2FA) helps protect mobile IoT applications and ensures that only authorized
users have access to IoT devices.

o Token-based Authentication: Token-based authentication (e.g., JWT) is


commonly used for securing mobile IoT applications by validating requests and
ensuring that only authorized devices can communicate with IoT systems.

 Example: A mobile app controlling a home security system might require user
authentication (password or fingerprint) before granting access to arm/disarm the
system.

7. Data Analytics and Machine Learning for IoT

 Overview: Data analytics and machine learning (ML) play a key role in extracting
insights from the massive amounts of data generated by IoT devices. Mobile computing
integrates these techniques to help users make data-driven decisions.

 Techniques:

o Real-time Analytics: IoT devices generate a stream of real-time data. Mobile


apps can use cloud-based analytics platforms or edge processing to analyze data
from sensors, making real-time decisions. For example, a mobile app might
provide users with live updates based on sensor data from wearable devices.

o Machine Learning: ML models can be used to predict future events or behaviors


based on historical data. For example, a mobile app could analyze sensor data
from an IoT health device to predict when a user might need medication based
on patterns.

 Example: In smart homes, mobile apps can learn user preferences over time and
optimize IoT device behavior based on the collected data (e.g., adjusting heating and
lighting based on usage patterns).

Unit 2

Define a) View b) View group c) Layout.


Android UI Layouts
Layouts in Android is used to define the user interface that holds the UI controls or widgets
that will appear on the screen of an android application or activity screen. Generally, every
application is a combination of View and ViewGroup. As we know, an android application
contains a large number of activities and we can say each activity is one page of the
application. So, each activity contains multiple user interface components and those
components are the instances of the View and ViewGroup. All the elements in a layout are
built using a hierarchy of View and ViewGroup objects.

View
A View is defined as the user interface which is used to create interactive UI components
such as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event
handling and drawing. They are Generally Called Widgets.

View

ViewGroup
A ViewGroup act as a base class for layouts and layouts parameters that hold other Views or
ViewGroups and to define the layout properties. They are Generally Called layouts.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

ViewGroup

The Android framework will allow us to use UI elements or widgets in two ways:

 Use UI elements in the XML file

 Create elements in the Kotlin file dynamically

Types of Android Layout


 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child
View elements one by one either in a particular direction either horizontally or vertically
based on the orientation property.

 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify


the position of child View elements relative to each other like (A to the right of B) or
relative to the parent (fix to the top of the parent).
 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to
specify the position of layout constraints for every child View relative to other views
present. A ConstraintLayout is similar to a RelativeLayout, but having more power.

 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the


position of View elements it contains on the top of each other to display only a single
View inside the FrameLayout.

 Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child
View elements in rows and columns.

 Android Web View: WebView is a browser that is used to display the web pages in our
activity layout.

 Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in


a single column.

 Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of
items in a grid view of rows and columns.

Explain the following layouts: Relative Layout, Linear Layout


LinearLayout
LinearLayout is a type of view group which is responsible for holding views in it either
Horizontally or vertically. It is a type of Layout where one can arrange groups either
Horizontally or Vertically.

Example Diagram:

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Syntax:
<LinearLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:orientation="either vertical or horizontal">

<!--ImageView, TextView, ButtonView etc.-->

</LinearLayout>

RelativeLayout
RelativeLayout is a layout in which we can arrange views/widgets according to the position of
other view/widgets. It is independent of horizontal and vertical view and we can arrange it
according to one’s satisfaction.

Example Diagram:

Syntax:

<RelativeLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content">

<!--ImageView, TextView, ButtonView

etc with specified position-->

</RelativeLayout>

Difference Between LinearLayout and RelativeLayout


LinearLayout RelativeLayout
We can adjust views and widgets We can adjust views and widgets according to
linearly i.e. Horizontally and vertically. one’s satisfaction.
layout_weight attribute in the linear Various attributes like: layout_toRightOf,
layout is used to specify the equal or layout_toLeftOf, layout_below,
specific size to the particular widget layout_alignParentTop, layout_top,
and view by using the following layout_alignParentLeft,
attribute. layout_alignParentRight are used to specify the
android:layout_weight = ‘0’ position of each view and widget.
Here Weight is specified as 0 in order
to give equal size or space to each
view or widget.
It is useful when we arrange views in a It is useful when we arrange views in a relative
linear fashion fashion.
Syntax: Syntax:
<LinearLayout> <RelativeLayout>
<!–Views, widgets–> <!–Views, Widgets–>
</LinearLayout> </RelativeLayout>
Example: In various Apps, Example: In Google Play Store, when we open the
LinearLayout is mainly applicable in app, the games, books, movies, and App’s
the SignUp screen where Name, Email, sections all are arranges in Relative Layout
Phone Number, Submit, etc. are Fashion.
arranged in a linear fashion.
LinearLayout is less used as compared RelativeLayout is used more in applications.
to RelativeLayout.
We can use LinearLayout inside We can also use RelativeLayout as a Child of
RelativeLayout. LinearLayout.

Explain Different Layouts available in Android. Explain with


Example.
In Android, Layouts are used to define the structure of user interfaces (UI). They control how
the elements (views) are arranged on the screen, such as buttons, text fields, images, and
other components. Android provides several built-in layout types, each suitable for specific
use cases.

Types of Layouts in Android

1. LinearLayout

2. RelativeLayout

3. FrameLayout

4. ConstraintLayout

5. GridLayout

6. TableLayout

7. CoordinatorLayout

8. ScrollView
9. DrawerLayout

1. LinearLayout

A LinearLayout arranges its child views in a single direction (either horizontally or


vertically). It’s one of the most commonly used layouts for simple UIs.

 Use case: If you want all the elements to appear in a single column or row.

Example (Vertical LinearLayout):

<LinearLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="First Item"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Second Item"/>

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter text here"/>

</LinearLayout>

 Orientation: You can set the orientation to vertical or horizontal to control the
direction of the layout.

2. RelativeLayout

In a RelativeLayout, child views are positioned relative to each other or the parent layout.
You can position views based on their relationship with other views (e.g., align one view to
the left of another or center a view in the parent).
 Use case: When you need precise control over the positioning of UI elements relative
to others.

Example:

<RelativeLayout

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World"

android:layout_centerHorizontal="true"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

android:layout_below="@id/textView"

android:layout_alignParentRight="true"/>

</RelativeLayout>

 Positioning: The android:layout_below and android:layout_alignParentRight attributes


are used to position the button relative to the TextView.

3. FrameLayout

A FrameLayout is designed to block out an area on the screen to display a single item. You
can stack views on top of each other, and only the topmost view will be visible unless you
manage the visibility of the others.

 Use case: When you need to display a single element or overlay multiple elements on
top of each other.

Example:

<FrameLayout

android:layout_width="match_parent"

android:layout_height="match_parent">
<ImageView

android:layout_width="match_parent"

android:layout_height="match_parent"

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

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Overlay Text"

android:layout_gravity="center"/>

</FrameLayout>

 Stacking Views: The ImageView is the background, and the TextView is centered over
it.

4. ConstraintLayout

ConstraintLayout is a flexible layout that allows you to define the position and size of child
views based on constraints (relationships to other views). It is the most powerful and
recommended layout for complex UIs.

 Use case: For complex UIs with complex interactions between views. It provides a flat
view hierarchy, making it ideal for performance.

Example:

<androidx.constraintlayout.widget.ConstraintLayout

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

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintStart_toStartOf="parent"/>

<Button
android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Click Me"

app:layout_constraintTop_toBottomOf="@id/textView"

app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 Constrainting: Views are constrained to other views or to the parent container,


creating a flexible and efficient layout.

5. GridLayout

A GridLayout allows you to arrange child views in a grid-like structure with rows and
columns. It is similar to a table.

 Use case: When you need to arrange elements in a table format (e.g., buttons in a
calculator or a grid of images).

Example:

<GridLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:columnCount="2">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="First Row, First Column"/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Second Row, Second Column"

android:layout_row="1"

android:layout_column="1"/>

</GridLayout>

 Row and Column: android:columnCount specifies the number of columns. Child views
can be assigned specific rows and columns.
6. TableLayout

A TableLayout is used to display UI elements in a grid of rows and columns. Each row can
have one or more columns, and the children are arranged accordingly.

 Use case: Best suited for forms or other tabular structures.

Example:

<TableLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="First Name"/>

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:hint="Enter your first name"/>

</TableRow>

<TableRow>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Last Name"/>

<EditText

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:hint="Enter your last name"/>

</TableRow>

</TableLayout>
 Table Rows: TableRow is used to define each row in the table. Views in a TableRow are
laid out horizontally.

7. CoordinatorLayout

CoordinatorLayout is a super-powered version of a FrameLayout and is often used as a root


layout to handle complex interaction between child views (such as floating action buttons,
snackbars, etc.).

 Use case: For complex user interactions, such as handling scroll events or creating
animations.

Example:

<androidx.coordinatorlayout.widget.CoordinatorLayout

android:layout_width="match_parent"

android:layout_height="match_parent">

<AppBarLayout

android:layout_width="match_parent"

android:layout_height="wrap_content">

<Toolbar

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:title="Coordinator Layout"/>

</AppBarLayout>

<RecyclerView

android:layout_width="match_parent"

android:layout_height="match_parent"

app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 AppBar and RecyclerView: The CoordinatorLayout allows interactions between the


AppBar and RecyclerView (scrolling behavior).

8. ScrollView

A ScrollView is used to enable scrolling of a single child view when the content exceeds the
screen size.
 Use case: When you have content that doesn’t fit on the screen and needs to be
scrollable.

Example:

<ScrollView

android:layout_width="match_parent"

android:layout_height="match_parent">

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="This is some content that might need scrolling."/>

</LinearLayout>

</ScrollView>

 ScrollView: Wraps a layout to make the content scrollable.

9. DrawerLayout

A DrawerLayout is used to create a sliding menu or navigation drawer.

 Use case: Commonly used for side navigation menus.

Example:

<androidx.drawerlayout.widget.DrawerLayout

android:layout_width="match_parent"

android:layout_height="match_parent">

<!-- Main content area -->

<RelativeLayout

android:layout_width="match_parent"

android:layout_height="match_parent">

<!-- Your main UI components -->

</RelativeLayout>
<!-- Drawer menu -->

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:orientation="vertical">

<!-- Drawer content goes here -->

</LinearLayout>

</androidx.drawerlayout.widget.DrawerLayout>

 DrawerLayout: Defines the sliding menu and the main content area.

Conclusion

Each layout in Android is designed for specific scenarios, and understanding them helps in
choosing the right one based on the requirements of your app's UI. Here's a quick recap of
the main layouts:

 LinearLayout: For vertical/horizontal lists.

 RelativeLayout: For relative positioning of elements.

 FrameLayout: For overlaying elements.

 ConstraintLayout: For flexible, complex UI designs.

 GridLayout/TableLayout: For grid-like or tabular structures.

 CoordinatorLayout: For handling complex interactions.

 ScrollView: For scrolling content.

 DrawerLayout: For side navigation.

Each layout offers unique features and can be combined to create rich, dynamic interfaces.

What is Fragment? Explain Fragment Lifecycle with Example.


Fragment
In Android, the fragment is the part of the Activity that represents a portion of the 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. that can exist only inside an activity as its lifecycle is
dependent on the lifecycle of the host activity. For example, if the host activity is paused,
then all the methods and operations of the fragment related to that activity will stop
functioning, the fragment is also termed a sub-activity. Fragments in Android can be added,
removed, or replaced dynamically i.e., while the 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:

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Understanding fragment lifecycles is crucial for building dynamic apps. For those looking to
master fragments using Kotlin, the Android Mastery with Kotlin: Beginner to
Advanced course covers everything from lifecycle management to advanced
implementations.

Types of Android Fragments


1. Single Fragment: Display only one single view on the device screen. This type of
fragment in android is mostly used for mobile phones.

2. List Fragment: This Fragment is used to display a list-view from which the user can
select the desired sub-activity. The menu drawer of apps like Gmail is the best example
of this kind of android fragment.

3. Fragment Transaction: This kind of fragments in android supports the transition from
one fragment in android to another at run time. Users can switch between multiple
fragments like switching tabs.
Android Fragment Lifecycle

Each fragment has it’s own lifecycle but due to the connection with the Activity it belongs to,
the android fragment lifecycle is influenced by the activity’s lifecycle.

Methods of the Android Fragment

Methods Description
onAttach() The very first method to be called when the fragment has been associated
with the activity. This method executes only 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.
onCreate() This method initializes the fragment by adding all the required attributes
and components.
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.
onViewCreate It indicates that the activity has been created in which the fragment exists.
d() View hierarchy of the fragment also instantiated before this function call.
onStart() The system invokes this method to make the fragment visible on the user’s
device.
onResume() This method is called to make the visible fragment interactive.
onPause() It indicates that the user is leaving the fragment. System call this method
to commit the changes made to the fragment.
onStop() Method to terminate the functioning and visibility of fragment from the
user’s screen.
onDestroyVie System calls this method to clean up all kinds of resources as well as view
w() hierarchy associated with the fragment. It will call when you can attach
new fragment and destroy existing fragment Resoruce
onDestroy() It is called to perform the final clean up of fragment’s state and its lifecycle.
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)
Android Fragment When to call Method

Consider Fragment-1 is A and Fragment-2 is B and A is attached to the Main Activity


1. If you can replace B with A.
A’s call back:
onDestroyView()
onDestroy()
onDetach()

B’s call back:


onAttach()
onCreate()
onCreateView()
onViewCreated()

2. If you can replace B with A without Losing resources.


A’s call back:
onDestroy()
onDetach()

B’s call back:


onAttach()
onCreate()
onCreateView()
onViewCreated()

Example of Android Fragment

Fragments in android are always embedded in Activities i.e., they are added to the layout of
activity in which they reside. Multiple fragments can be added to one activity. This task can
be carried out in 2 ways:

1. Statically: Explicitly mention the fragment in the XML file of the activity. This type of
fragment can not be replaced during the run time.

2. Dynamically: FragmentManager is used to embed fragments with activities that


enable the addition, deletion, or replacement of fragments at run time.

Almost all android app uses dynamic addition of fragments as it improves the user
experience. Below is the step-by-step implementation of adding 2 fragments in one activity. A
default fragment will be visible when the activity appears on the screen and the user can
switch between the 2 fragments at the run time.

Note: Following steps are performed on Android Studio version 4.0

Step 1: Create a new project

1. Click on File, then New => New Project.

2. Choose Empty activity

3. Select language as Java

4. Select the minimum SDK as per your need.


Step 2: Modify strings.xml file

All the strings which are used in the activity are listed in this file

<resources>

<string name="app_name">GfG | Fragment in Android</string>

<string name="heading">Two Fragments in One Activity</string>

<string name="fragment1_button">Display First Fragment</string>

<string name="fragment2_button">Display Second Fragment</string>

<string name="fragment1_text1">Displaying contents of the First Fragment</string>

<string name="fragment2_text1">Displaying contents of the Second Fragment</string>

</resources>

Step 3: Working with the activity_main.xml file

Open the activity_main.xml file and add 2 buttons to it which will be used to switch
between the 2 fragments. Further, add the fragment element in the activity layout. It is the
area in which the fragments in android will be displayed.

<?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:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#168BC34A"

android:orientation="vertical"

tools:context=".MainActivity">

<!-- Heading of the activity -->

<TextView

android:id="@+id/textView"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="20dp"

android:layout_marginBottom="20dp"

android:fontFamily="@font/roboto"

android:text="@string/heading"

android:textAlignment="center"
android:textColor="@android:color/holo_green_light"

android:textSize="24sp"

android:textStyle="bold" />

<!-- Button to display first fragment -->

<Button

android:id="@+id/button1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginStart="20dp"

android:layout_marginEnd="20dp"

android:background="#4CAF50"

android:fontFamily="@font/roboto"

android:onClick="selectFragment"

android:text="@string/fragment1_button"

android:textColor="@android:color/background_light"

android:textSize="18sp"

android:textStyle="bold" />

<!-- Button to display second fragment -->

<Button

android:id="@+id/button2"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_marginStart="20dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="20dp"

android:layout_marginBottom="20dp"

android:background="#4CAF50"

android:fontFamily="@font/roboto"

android:onClick="selectFragment"

android:text="@string/fragment2_button"

android:textColor="@android:color/background_light"

android:textSize="18sp"
android:textStyle="bold" />

<!-- Adding Fragment element in the activity -->

<fragment

android:id="@+id/fragment_section"

android:name="com.example.fragments_backup.FragmentOne"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginStart="10dp"

android:layout_marginEnd="10dp"

android:layout_marginBottom="10dp"

tools:layout="@layout/fragment_one" />

</LinearLayout>

The android:name tag under the <fragment> element is containing the file name of default
fragment which is to be displayed when activity opens.

Step 4: Creating the two fragment class

These files contain only the onCreateView() method to inflate the UI of the fragment and
returns the root of the fragment layout. If the fragment does not have any UI, it will return
null.

1. First Fragment class:

import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

public class FragmentOne extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle


savedInstanceState) {

// inflating the layout of the fragment

// and returning the view component

return inflater.inflate(R.layout.fragment_one, container, false);


}

2. Second Fragment Class:

import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

public class FragmentTwo extends Fragment{

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle


savedInstanceState) {

// inflating the layout of the fragment

// and returning the view component

return inflater.inflate(R.layout.fragment_two, container, false);

Step 5: Creating Layouts for both the fragments

Create two Layout Resource Files for both the fragments. Fragment displays a text on the
screen and have a background color to differentiate their area in the Activity layout. Below is
the code to implement this layout.

1. fragment_one.xml file:

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

<LinearLayout

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#5C52CC57"

android:orientation="vertical">

<!-- Text to be displayed inside the Fragment -->

<TextView

android:id="@+id/textView1"
android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_weight="1"

android:gravity="center"

android:text="@string/fragment1_text1"

android:textAlignment="center"

android:textColor="@android:color/background_light"

android:textSize="24sp"

android:textStyle="bold" />

</LinearLayout>

2. fragment_two.xml file:

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

<LinearLayout

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#5C3473A6"

android:orientation="vertical">

<!-- Text to be displayed inside the Fragment -->

<TextView

android:id="@+id/textView2"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:fontFamily="@font/roboto"

android:gravity="center"

android:text="@string/fragment2_text1"

android:textAlignment="center"

android:textColor="@android:color/background_light"

android:textSize="24sp"

android:textStyle="bold" />

</LinearLayout>
Step 6: Working with the MainActivity.java file

Now, the functionality of the button to perform operations on clicking will be defined in the
MainActivity class. Moreover, the code for the replacement of fragments during run time is
also mentioned in this file. Below is the code to implement this step.

import android.os.Bundle;

import android.view.View;

import android.app.Fragment;

import android.app.FragmentManager;

import android.app.FragmentTransaction;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// method for displaying the appropriate

// fragment according to the clicked button

public void selectFragment(View view) {

// creating object for Fragment

Fragment fr;

// displaying first fragment

// if button1 is clicked

if(view == findViewById(R.id.button1)) {

fr = new FragmentOne();

// displaying second fragment


// if button2 is clicked

else {

fr = new FragmentTwo();

FragmentManager fm = getFragmentManager();

// fragment transaction to add or replace

// fragments while activity is running

FragmentTransaction fragmentTransaction = fm.beginTransaction();

fragmentTransaction.replace(R.id.fragment_section, fr);

// making a commit after the transaction

// to assure that the change is effective

fragmentTransaction.commit();

Output:

Video

Explain how do you design the checkboxes? Along with


onSubmit() method implementation.
Designing Checkboxes in Android
In Android, Checkboxes are commonly used to let users select multiple options from a list of
choices. A CheckBox is a type of CompoundButton that can either be checked or
unchecked, allowing the user to make a selection.

Creating a Checkbox in Android

A checkbox is created using the <CheckBox> widget in XML layout files. Below is an example
of how to define and design checkboxes in an Android XML layout.

1. XML Layout for Checkboxes

xml

Copy code

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:orientation="vertical"

android:padding="16dp">

<!-- Label or Title -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Choose your favorite fruits"

android:textSize="18sp"

android:layout_marginBottom="16dp"/>

<!-- Checkbox for Apple -->

<CheckBox

android:id="@+id/appleCheckBox"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Apple"

android:layout_marginBottom="8dp"/>

<!-- Checkbox for Banana -->

<CheckBox

android:id="@+id/bananaCheckBox"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Banana"

android:layout_marginBottom="8dp"/>

<!-- Checkbox for Mango -->

<CheckBox

android:id="@+id/mangoCheckBox"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Mango"

android:layout_marginBottom="8dp"/>
<!-- Submit Button -->

<Button

android:id="@+id/submitButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:onClick="onSubmit"/>

</LinearLayout>

Explanation:

 TextView: Provides the label for the group of checkboxes (e.g., "Choose your favorite
fruits").

 CheckBoxes: The checkboxes are created for three options: Apple, Banana, and
Mango. You can change the text of each checkbox to match the options you want to
present to the user.

 Button: A submit button that triggers the onSubmit() method when clicked.

2. Handling Checkbox Selections in Java/Kotlin Code


After the checkboxes are defined in the layout, you need to handle the logic when the user
submits the form. You can capture the checked state of each checkbox and perform an action
when the submit button is clicked.

Java Implementation for onSubmit()

In the Activity or Fragment (depending on where you're working), you can define the
onSubmit() method, which will get triggered when the user clicks the submit button.

Here’s the Java code to handle the checkbox selections:

public class MainActivity extends AppCompatActivity {

// Declare checkboxes and button

private CheckBox appleCheckBox;

private CheckBox bananaCheckBox;

private CheckBox mangoCheckBox;

private Button submitButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Initialize the views

appleCheckBox = findViewById(R.id.appleCheckBox);

bananaCheckBox = findViewById(R.id.bananaCheckBox);

mangoCheckBox = findViewById(R.id.mangoCheckBox);

submitButton = findViewById(R.id.submitButton);

// onSubmit() method to handle button click

public void onSubmit(View view) {

// Check the state of each checkbox and create a list of selected options

StringBuilder selectedFruits = new StringBuilder("Selected Fruits: ");

if (appleCheckBox.isChecked()) {

selectedFruits.append("Apple ");

if (bananaCheckBox.isChecked()) {

selectedFruits.append("Banana ");

if (mangoCheckBox.isChecked()) {

selectedFruits.append("Mango ");

// If no fruits are selected

if (selectedFruits.toString().equals("Selected Fruits: ")) {

selectedFruits.append("None");

// Display the result using Toast or show in a TextView

Toast.makeText(this, selectedFruits.toString(), Toast.LENGTH_SHORT).show();

Explanation:
1. Initialization: The checkboxes (appleCheckBox, bananaCheckBox, and
mangoCheckBox) and the submitButton are initialized in the onCreate() method using
findViewById().

2. onSubmit() Method:

o Checking if a checkbox is checked: The isChecked() method is used to check


whether a particular checkbox is selected.

o Storing selected options: A StringBuilder is used to dynamically append the


selected items. This is helpful when there are multiple checkboxes, and you need
to list all selected ones.

o Toast Message: After collecting all the selected items, you can display the result
to the user using a Toast message or update a TextView.

How do you design toggle button and implement the response


to it?
Designing a Toggle Button in Android
A ToggleButton in Android is a type of CompoundButton that acts like a switch, allowing
users to toggle between two states: ON or OFF. It’s often used for settings or preferences,
like turning features on or off (e.g., enabling Wi-Fi or turning on/off dark mode).

Steps to Design and Implement a Toggle Button

1. XML Layout for a ToggleButton

To add a ToggleButton in your layout, you can define it in the XML layout file like this:

xml

Copy code

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:padding="16dp">

<!-- Label for ToggleButton -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Enable Feature"

android:textSize="18sp"

android:layout_marginBottom="16dp"/>
<!-- ToggleButton for enabling/disabling a feature -->

<ToggleButton

android:id="@+id/toggleButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textOff="OFF"

android:textOn="ON"

android:layout_marginBottom="16dp"/>

<!-- A Button to submit or confirm the action -->

<Button

android:id="@+id/submitButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:onClick="onSubmit"/>

</LinearLayout>

Explanation:

 LinearLayout: A vertical LinearLayout is used to arrange the elements.

 TextView: Displays a label for the ToggleButton (e.g., "Enable Feature").

 ToggleButton:

o android:id="@+id/toggleButton": Unique ID for accessing the ToggleButton in


Java or Kotlin.

o android:textOff="OFF": Text displayed when the button is off.

o android:textOn="ON": Text displayed when the button is on.

o You can customize the button's appearance, including the textOn and textOff
attributes.

2. Java Implementation for Handling ToggleButton State

To handle the state change of the ToggleButton, you can implement an


OnCheckedChangeListener to listen for the toggle state (ON or OFF).

Java Code for Response to ToggleButton

java

Copy code
public class MainActivity extends AppCompatActivity {

private ToggleButton toggleButton;

private Button submitButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize the views

toggleButton = findViewById(R.id.toggleButton);

submitButton = findViewById(R.id.submitButton);

// Set an OnCheckedChangeListener for the ToggleButton

toggleButton.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {

@Override

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

if (isChecked) {

// The toggle button is ON

Toast.makeText(MainActivity.this, "Feature Enabled",


Toast.LENGTH_SHORT).show();

} else {

// The toggle button is OFF

Toast.makeText(MainActivity.this, "Feature Disabled",


Toast.LENGTH_SHORT).show();

});

// onSubmit() method to handle the button click

public void onSubmit(View view) {

boolean isFeatureEnabled = toggleButton.isChecked();


String message = isFeatureEnabled ? "Feature is ON" : "Feature is OFF";

Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

Explanation of Java Code:

 Initialization:

o toggleButton = findViewById(R.id.toggleButton) initializes the ToggleButton.

o submitButton = findViewById(R.id.submitButton) initializes the Submit button.

 OnCheckedChangeListener:

o The setOnCheckedChangeListener() method listens for changes in the state of


the ToggleButton.

o The listener receives the state of the ToggleButton in the onCheckedChanged()


method, where the isChecked parameter tells whether the button is ON or OFF.

o Based on the state, you can perform actions like displaying a Toast message
(e.g., "Feature Enabled" or "Feature Disabled").

 onSubmit() Method:

o The onSubmit() method is triggered when the submit button is clicked. It checks
the state of the ToggleButton using toggleButton.isChecked(), which returns true
if the button is ON and false if it’s OFF.

o It then displays a Toast message indicating whether the feature is enabled or


disabled.

4. Using the ToggleButton in Practice

Use Case: You might use a ToggleButton to toggle features like:

 Enabling or disabling a Wi-Fi or Bluetooth connection.

 Switching between light and dark modes.

 Activating or deactivating certain app features like notifications or background services.

Conclusion

To design and handle a ToggleButton in Android:

 XML Layout: Use the <ToggleButton> element in the layout file and define textOn and
textOff attributes.

 State Handling: Use an OnCheckedChangeListener to respond to the toggle button's


state changes and perform actions accordingly (such as showing a message or
enabling/disabling features).

 Submit Action: Use the isChecked() method in the onSubmit() method to determine
the toggle state when a user submits the form.
Explain how to create Text Input? List out the Attributes for
customizing Textview. Write down the steps for getting the
user's input.
Creating Text Input in Android

In Android, text input is typically done using EditText views. EditText is a type of TextView
that allows users to enter and modify text. It is commonly used for forms, login screens, or
anywhere user input is required.

1. Creating a Text Input Field (EditText)


You can define an EditText in the XML layout file to create a text input field where users can
type their information.

Example of XML Layout for Text Input:

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:padding="16dp">

<!-- Label for EditText -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Enter your name"

android:textSize="18sp"

android:layout_marginBottom="8dp"/>

<!-- EditText for text input -->

<EditText

android:id="@+id/editTextName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Name"

android:inputType="text"

android:maxLength="50"
android:layout_marginBottom="16dp"/>

<!-- Submit Button -->

<Button

android:id="@+id/submitButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Submit"

android:onClick="onSubmit"/>

</LinearLayout>

Explanation:

 TextView: Displays a label above the EditText to prompt the user for input (e.g., "Enter
your name").

 EditText:

o android:id="@+id/editTextName": A unique ID for the EditText to access it


programmatically.

o android:hint="Name": Placeholder text that appears when the EditText is empty.

o android:inputType="text": Specifies that the input type is plain text. You can
customize it to accept different input types like textPassword, number, etc.

o android:maxLength="50": Restricts the input length to a maximum of 50


characters.

 Button: A button labeled "Submit" that triggers an action (e.g., collecting user input)
when clicked.

2. Attributes for Customizing TextView and EditText


Here’s a list of common attributes you can use to customize TextView and EditText in XML:

Common Attributes for TextView:

 android:text: Specifies the text to display in the TextView.

 android:textSize: Specifies the size of the text (e.g., 16sp).

 android:textColor: Specifies the color of the text (e.g., @android:color/black).

 android:textStyle: Controls the text style (e.g., bold, italic).

 android:gravity: Defines the alignment of the text (e.g., center, left, right).

 android:maxLines: Limits the number of lines the text can occupy.

 android:ellipsize: Specifies how the text should be truncated when it overflows (e.g.,
end, middle, marquee).

 android:padding: Defines padding around the text.


Common Attributes for EditText:

 android:hint: Placeholder text when the EditText is empty.

 android:inputType: Specifies the type of data expected (e.g., text, textPassword,


number, datetime).

 android:maxLength: Limits the number of characters the user can input.

 android:textColor: Defines the color of the text entered by the user.

 android:background: Specifies the background color or drawable for the EditText.

 android:importantForAccessibility: Affects accessibility features (e.g., yes, no).

 android:selectAllOnFocus: Automatically selects the text when the EditText is focused.

 android:lineSpacingExtra: Adds extra space between lines in multi-line EditText.

 android:lines: Defines the number of visible lines in the EditText.

Example of Customized EditText in XML:

<EditText

android:id="@+id/editTextName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:inputType="text"

android:textColor="#000000"

android:textSize="18sp"

android:maxLength="50"

android:padding="12dp"

android:background="@drawable/edit_text_background"

android:importantForAccessibility="yes" />

3. Steps for Getting User Input from EditText in Java/Kotlin


To get the input from an EditText field and process it (e.g., when the user submits the form),
follow these steps:

Step 1: Get the Reference to the EditText Field

You first need to get a reference to the EditText in your Java/Kotlin code using the ID you
assigned in the XML layout file.

Java Code:

public class MainActivity extends AppCompatActivity {

private EditText editTextName;


private Button submitButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize the EditText and Button

editTextName = findViewById(R.id.editTextName);

submitButton = findViewById(R.id.submitButton);

// Set the onClick listener for the submit button

submitButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get the user's input from the EditText

String userInput = editTextName.getText().toString();

// Perform action with the input (e.g., show it in a Toast)

Toast.makeText(MainActivity.this, "User Input: " + userInput,


Toast.LENGTH_SHORT).show();

});

Explanation:

 findViewById(): You use this method to get references to the EditText (editTextName)
and Button (submitButton) defined in your layout XML file.

 getText().toString(): The getText() method returns an editable text (Editable), so you


need to convert it to a regular string using toString().

 Toast: A Toast message is used to display the input for the user. In a real app, you
would probably use the input to perform some action, like saving it to a database,
sending it to a server, etc.
4. Handling Validation and Input Check
Before proceeding with any action (such as submitting the input), it's a good practice to
validate the user's input (e.g., ensuring the field isn't empty).

if (userInput.isEmpty()) {

Toast.makeText(MainActivity.this, "Please enter your name", Toast.LENGTH_SHORT).show();

} else {

// Proceed with the user's input

What is a Menu? List out the types of Menus. Explain


implementation of app bar & options menu.
What is a Menu in Android?
In Android, a Menu refers to a set of options or commands that can be displayed to the user.
Menus provide a way to interact with the app, offering various actions or functionalities (such
as settings, preferences, or app features). Android supports different types of menus for
different use cases, such as app bars (action bars), context menus, and options menus.

Menus in Android can be categorized into the following types:

Types of Menus in Android


1. Options Menu

o The Options Menu is the primary menu used in Android apps. It is typically
displayed when the user presses the Menu button or in the app bar (toolbar).

o It can include options like Settings, Search, or app-specific actions.

o It’s a global menu, available from anywhere in the app.

2. Context Menu

o A Context Menu is shown when a user performs a long-press (or right-click on


some devices) on an element in the app, such as a list item or an image.

o This menu provides context-specific options based on the item the user interacts
with.

o It can be used for actions like Delete, Share, or Edit for specific items in a list.

3. Popup Menu

o A Popup Menu is similar to the context menu but is displayed as a floating menu
that can appear anywhere on the screen. It is often triggered by a button or a
view.

o It’s typically used for a list of actions related to a specific item but not tied to
long-clicking on the item (unlike a Context Menu).
o Commonly used in overflow menus or buttons like three dots (⋮) or more
options.

4. Submenu

o A Submenu is a menu within a menu. It allows you to organize complex menus


in a hierarchical structure.

o For example, you could have a "Settings" option in the main menu, and inside it,
a "Display" submenu with various display-related settings.

Implementation of App Bar & Options Menu


1. App Bar (Toolbar) in Android

The App Bar (or Toolbar) is a common UI component in Android that allows the user to
perform actions such as navigation, or other app-specific actions (like saving data or
refreshing). It also often includes the Options Menu (or Overflow Menu) as part of the app’s
action items.

Steps to Implement an App Bar (Toolbar)

1. Add Toolbar to Layout (XML):

First, you need to add a Toolbar widget to the app’s XML layout. The Toolbar can act as the
app’s app bar.

<androidx.appcompat.widget.Toolbar

android:id="@+id/toolbar"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="?attr/colorPrimary"

android:title="My App"

android:elevation="4dp"/>

2. Set Toolbar as Action Bar in Java or Kotlin:

In your Activity, you need to set the Toolbar as the Action Bar to enable it to display menus
and actions.

Java:

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize the toolbar

Toolbar toolbar = findViewById(R.id.toolbar);

setSupportActionBar(toolbar); // Set the toolbar as the ActionBar


}

2. Options Menu in Android

The Options Menu is an Android menu that provides a list of options/actions available in the
current screen. This is usually displayed when the user taps the overflow icon (three dots)
on the toolbar, or when the user presses the menu button on the device (if available).

Steps to Implement the Options Menu

1. Override onCreateOptionsMenu():

o You must override onCreateOptionsMenu() to define the menu items that should
appear in the options menu.

Java:

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu items from a menu resource file

getMenuInflater().inflate(R.menu.menu_main, menu); // Assuming


menu_main.xml exists

return true;

2. Handle Menu Item Clicks:

o Once the menu is inflated, you need to handle item clicks by overriding the
onOptionsItemSelected() method.

Java:

@Override

public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {

case R.id.action_settings:

// Handle settings option

Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();

return true;

case R.id.action_search:

// Handle search option

Toast.makeText(this, "Search clicked", Toast.LENGTH_SHORT).show();

return true;

default:

return super.onOptionsItemSelected(item);

}
}

3. Create the Menu Resource (menu_main.xml):

o Create a menu resource file (e.g., menu_main.xml) in the res/menu/ directory.


This file defines the items to be displayed in the menu.

Example of menu_main.xml:

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

<item

android:id="@+id/action_settings"

android:title="Settings"

android:icon="@drawable/ic_settings"

android:showAsAction="ifRoom"/>

<item

android:id="@+id/action_search"

android:title="Search"

android:icon="@drawable/ic_search"

android:showAsAction="ifRoom"/>

</menu>

o android:id: Unique identifier for each menu item.

o android:title: The label text for the menu item.

o android:icon: The icon for the menu item.

o android:showAsAction: Defines whether the item should appear in


the action bar or overflow menu. Options include always, ifRoom, or
never.

Example of Full Code for App Bar & Options Menu

XML Layout (activity_main.xml)

<androidx.appcompat.widget.Toolbar

android:id="@+id/toolbar"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="?attr/colorPrimary"

android:title="My App"

android:elevation="4dp"/>
<!-- Other UI elements go here -->

Menu Resource (menu_main.xml)

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

<item

android:id="@+id/action_settings"

android:title="Settings"

android:icon="@drawable/ic_settings"

android:showAsAction="ifRoom"/>

<item

android:id="@+id/action_search"

android:title="Search"

android:icon="@drawable/ic_search"

android:showAsAction="ifRoom"/>

</menu>

Activity Code (MainActivity.java)

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Toolbar toolbar = findViewById(R.id.toolbar);

setSupportActionBar(toolbar); // Set Toolbar as Action Bar

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

@Override

public boolean onOptionsItemSelected(MenuItem item) {


switch (item.getItemId()) {

case R.id.action_settings:

Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();

return true;

case R.id.action_search:

Toast.makeText(this, "Search clicked", Toast.LENGTH_SHORT).show();

return true;

default:

return super.onOptionsItemSelected(item);

What is screen orientation? Explain its implementation.


Screen Orientations in Android with Examples
Screen Orientation, also known as screen rotation, is the attribute of activity element in
android. When screen orientation change from one state to other, it is also known
as configuration change.

States of Screen orientation


There are various possible screen orientation states for any android application, such as:

 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED

 ActivityInfo.SCREEN_ORIENTATION_USER

 ActivityInfo.SCREEN_ORIENTATION_SENSOR

 ActivityInfo.SCREEN_ORIENTATION_BEHIND

 ActivityInfo.SCREEN_ORIENTATION_NOSENSOR

 ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE

 ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT

 ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT

The initial orientation of the Screen has to be defined in the AndroidManifest.xml file.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.
Syntax:

 AndroidManifest.xml

<activity android:name="package_name.Your_ActivityName"

android:screenOrientation="orientation_type">

</activity>

Example:

android:screenOrientation="orientation_type">

How to change Screen orientation?


Here is an example of an Android application that changes screen orientation for Landscape
and Portrait mode.

We will create two activities of different screen orientation.

 The first activity will be as “portrait” orientation and

 Second activity as “landscape” orientation state.

Step-by-Step demonstration:

 Creating the activities: There will be two activities and hence two XML files, one for
each activity.

1. activity_main.xml: XML file for first activity consist of constraint layout with
Button and Text View in it. This activity is in Landscape state.

2. activity_next.xml: XML file for second activity consist of constraint layout with
Text View in it. This activity is in Landscape state.

Below is the code for both activities:

o activity_main.xml

o activity_next.xml

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

<!--Constraint Layout-->

<android.support.constraint.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="com.geeksforgeeks.screenorientation.MainActivity">

<!--Button to launch next activity with onClick-->


<Button

android:id="@+id/b1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Next Activity"

android:layout_marginTop="100dp"

android:onClick="onClick"

android:layout_marginBottom="10dp"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintVertical_bias="0.613"

app:layout_constraintHorizontal_bias="0.612"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/tv1"

/>

<!--TextView -->

<TextView

android:text="Potrait orientation"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_marginTop="124dp"

android:textSize="25dp"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintHorizontal_bias="0.502"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

 Creating the Java file: There will be two activities and hence two Java files, one for
each activity.

1. MainActivity.java: Java file for Main Activity, in which setOnClick() listener is


attached to the button to launch next activity with different orientation.

2. NextActivity.java: Java file for Next Activity which is in Landscape mode.


o MainActivity.java

o NextActivity.java

package com.geeksforgeeks.screenorientation;

import android.support.v7.app.AppCompatActivity;

import android.content.Intent;

import android.view.View;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

// declare button variable

Button button;

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// initialise button with id

button = findViewById(R.id.b1);

// onClickListener attached to button

// to send intent to next activity

public void onClick(View v)

// Create instance of intent and

// startActivity with intent object

Intent intent

= new Intent(
MainActivity.this,

NextActivity.class);

startActivity(intent);

 Updating the AndroidManifest file: In AndroidManifest.xml file, add


the screenOrientation state in activity along with its orientation. Here, we provide
“portrait” orientation for MainActivity and “landscape” for NextActivity.

Below is the code for AndroidManifest file:

o AndroidManifest.xml

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

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

package="com.geeksforgeeks.screenorientation">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<!-Define potrait orientation for Main activity-->

<activity

android:name="com.geeksforgeeks.screenorientation.MainActivity"

android:screenOrientation="portrait">

<intent-filter>

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

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

</intent-filter>

</activity>

<!--Define landscape orientation for NextActivity-->

<activity android:name=".NextActivity"
android:screenOrientation="landscape">

</activity>

</application>

</manifest>

 Output:

1. Activity 1:

2. Activity 2:

Explain Event handing. Write a program to display the


Messages through Toast.
Android - Event Handling
Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android
framework maintains an event queue as first-in, first-out (FIFO) basis. You can capture these
events in your program and take appropriate action as per requirements.

There are following three concepts related to Android Event Management −


 Event Listeners − An event listener is an interface in the View class that contains a
single callback method. These methods will be called by the Android framework when
the View to which the listener has been registered is triggered by user interaction with
the item in the UI.

 Event Listeners Registration − Event Registration is the process by which an Event


Handler gets registered with an Event Listener so that the handler is called when the
Event Listener fires the event.

 Event Handlers − When an event happens and we have registered an event listener
for the event, the event listener calls the Event Handlers, which is the method that
actually handles the event.

What is Toast in Android?


A Toast is a feedback message. It takes a very little space for displaying while the overall
activity is interactive and visible to the user. It disappears after a few seconds. It disappears
automatically. If the user wants a permanently visible message, a Notification can be used.
Another type of Toast is custom Toast, in which images can be used instead of a simple
message.

Example: Toast class provides a simple popup message that is displayed on the current
activity UI screen (e.g. Main Activity).

Complete the Code to display a simple Toast Message:

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

// Defining the object for button

Button btn;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Bind the components to their respective objects by assigning

// their IDs with the help of findViewById() method

Button btn = (Button)findViewById(R.id.Button01);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Displaying simple Toast message

Toast.makeText(getApplicationContext(), "This a toast message",


Toast.LENGTH_LONG).show();

});

Output:

Write about Mobile App UI? How do we use text to speech on


Android?
What is Mobile User Interface(UI)?
The mobile user interface or mobile UI refers to the visual and interactive elements that users
interact with on their mobile devices, such as smartphones and tablets. It includes the layout,
navigation, buttons, icons, typography, and overall aesthetic design of the mobile application
or website. The mobile UI is the primary touchpoint between the user and the digital product,
shaping their perception and experience.

A well-designed mobile UI should be intuitive, visually appealing, and optimized for the
unique characteristics of mobile devices, including smaller screen sizes, touch-based
interactions, and varying device capabilities. It should prioritize simplicity, clarity, and ease of
use, ensuring that users can effortlessly navigate and accomplish their desired tasks.

Types of Mobile User Interfaces(UI)


Onboarding Screen:

This screen helps the new users to understand the app better.

Home Screen:

Home Screen is the main screen of any app. It is the screen that is opened when an
application is launched.

Login Screen:

Login screens are the pages that helps the users to create their account on the application.

Splash Screen:

Splash Screens are the screens that are displayed when any application is launched.

App Screen:

App Screens are all the screens of an application. They include showing information and
interacts with user.

Explain Text-to-Speech Techniques with examples.


Text-to-Speech Techniques in Android
In Android, Text-to-Speech (TTS) technology is widely used to convert written text into spoken
words, making apps more interactive, accessible, and user-friendly. Android provides an in-
built TextToSpeech class to enable TTS functionality. The implementation of TTS can vary
depending on different techniques that allow for control over speech quality, pitch, speed,
and naturalness.

Here, we’ll explore Text-to-Speech techniques in Android, focusing on how to implement


and customize them using Android’s TextToSpeech API, including practical examples.

1. Basic Text-to-Speech Implementation

The basic approach to TTS in Android is simple and involves initializing the TextToSpeech
engine and speaking text. The default settings provide a simple way to convert text into
speech.

Steps:

1. Initialize TextToSpeech.

2. Set the language and initialize speech parameters.


3. Use the speak() method to read out the text.

Example Code:

import android.speech.tts.TextToSpeech;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.speech.tts.TextToSpeech.OnInitListener;

import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements OnInitListener {

private TextToSpeech textToSpeech;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textToSpeech = new TextToSpeech(this, this); // Initialize TextToSpeech

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

int langResult = textToSpeech.setLanguage(Locale.US); // Set language to US English

// Check if the language is supported

if (langResult == TextToSpeech.LANG_MISSING_DATA || langResult ==


TextToSpeech.LANG_NOT_SUPPORTED) {

Toast.makeText(MainActivity.this, "Language not supported",


Toast.LENGTH_SHORT).show();

} else {

// If successful, speak text

textToSpeech.speak("Hello, welcome to the Android TTS tutorial.",


TextToSpeech.QUEUE_FLUSH, null, null);
}

} else {

Toast.makeText(MainActivity.this, "TTS Initialization failed",


Toast.LENGTH_SHORT).show();

@Override

protected void onDestroy() {

if (textToSpeech != null) {

textToSpeech.stop();

textToSpeech.shutdown();

super.onDestroy();

Key Points:

 Initialization: The TextToSpeech object is initialized in the onCreate() method.

 Language: Set the language to U.S. English (Locale.US).

 Speaking: The speak() method converts text into speech.

 Clean-up: It's important to call stop() and shutdown() to release resources in the
onDestroy() method.

2. Adjusting Speech Rate and Pitch

Android allows developers to control the speech rate (how fast the speech is) and pitch
(how high or low the voice sounds) using the setSpeechRate() and setPitch() methods. These
settings help in making the speech sound more natural.

Steps:

1. Set the speech rate (speed) and pitch (tone).

2. Use the speak() method with the adjusted parameters.

Example Code:

textToSpeech.setSpeechRate(1.5f); // Speed up the speech (1.0f is normal, 2.0f is faster)

textToSpeech.setPitch(0.8f); // Lower the pitch of the voice (1.0f is normal)

textToSpeech.speak("Hello, this is an example of speech rate and pitch adjustment.",


TextToSpeech.QUEUE_FLUSH, null, null);
Explanation:

 setSpeechRate(): A value of 1.0f represents normal speed. Values lower than 1.0f
slow down the speech, while values greater than 1.0f make the speech faster.

 setPitch(): A value of 1.0f represents the normal pitch. Values below 1.0f lower the
pitch, while values above 1.0f raise the pitch.

3. Using SSML (Speech Synthesis Markup Language)

SSML is an XML-based language used to provide additional control over speech synthesis.
Android TTS engine supports SSML tags to adjust aspects like pauses, emphasis, and
pronunciation.

Common SSML Tags:

 <prosody>: Controls the pitch, rate, and volume.

 <break>: Adds pauses between words or sentences.

 <emphasis>: Adds emphasis to a word.

 <voice>: Specifies the voice to be used.

Example Code:

String ssmlText = "<speak>" +

"<prosody rate='slow' pitch='high'>" +

"Hello, welcome to the SSML example." +

"</prosody>" +

"</speak>";

textToSpeech.speak(ssmlText, TextToSpeech.QUEUE_FLUSH, null, null);

Explanation:

 <prosody rate='slow' pitch='high'>: Slows down the speech and increases the
pitch.

 <speak>: Wraps the SSML content.

 SSML provides finer control over speech attributes, including pauses, speech rate,
pitch, emphasis, and more.

4. Speech with Multiple Languages

Android TTS supports multiple languages, and you can change the language dynamically. If
the device supports multiple languages, you can switch to the desired language (e.g., French,
Spanish) at runtime.

Steps:

1. Set the language to another locale using setLanguage().


2. Use the speak() method to read text in that language.

Example Code:

textToSpeech.setLanguage(Locale.FRENCH); // Set language to French

textToSpeech.speak("Bonjour, comment ça va?", TextToSpeech.QUEUE_FLUSH, null, null);

Explanation:

 Locale.FRENCH: This changes the speech to French.

 If the language is not supported on the device, Android will return a language not
supported error.

5. Handling Text-to-Speech Initialization Failure

In some cases, TTS may fail to initialize properly, particularly when the required language
data is missing or the device does not support TTS. It's essential to handle these failures
gracefully by checking for TextToSpeech.LANG_NOT_SUPPORTED or
TextToSpeech.LANG_MISSING_DATA.

Example Code:

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

int langResult = textToSpeech.setLanguage(Locale.US);

if (langResult == TextToSpeech.LANG_MISSING_DATA || langResult ==


TextToSpeech.LANG_NOT_SUPPORTED) {

Toast.makeText(this, "Language not supported or missing data",


Toast.LENGTH_SHORT).show();

} else {

textToSpeech.speak("TTS Initialized successfully.", TextToSpeech.QUEUE_FLUSH, null,


null);

} else {

Toast.makeText(this, "TTS Initialization failed", Toast.LENGTH_SHORT).show();

Explanation:

 LANG_MISSING_DATA: Indicates that necessary speech data is missing.

 LANG_NOT_SUPPORTED: The language selected is not supported by the device.


6. Speech with Pauses and Emphasis (Using SSML)

Sometimes you may need to introduce pauses or emphasize certain words for a more
natural-sounding speech. This can be done using SSML tags like <break> for pauses and
<emphasis> for emphasizing specific words.

Example Code:

String ssmlText = "<speak>" +

"This is a <break time='500ms'/> sample text with a pause. " +

"<emphasis level='strong'>Hello!</emphasis> How are you?" +

"</speak>";

textToSpeech.speak(ssmlText, TextToSpeech.QUEUE_FLUSH, null, null);

Explanation:

 <break time='500ms'/>: Adds a half-second pause.

 <emphasis level='strong'>Hello!</emphasis>: Emphasizes the word "Hello!".

7. Clean Up and Resource Management

After using the TextToSpeech object, always clean up resources to prevent memory leaks.
This is done using stop() and shutdown() methods.

Example Code:

@Override

protected void onDestroy() {

if (textToSpeech != null) {

textToSpeech.stop(); // Stop any ongoing speech

textToSpeech.shutdown(); // Release resources

super.onDestroy();

How text-to-speech technology is implemented in mobile app?


Implementing Text-to-Speech Technology in a Mobile App (Android)
Text-to-Speech (TTS) technology converts written text into spoken words. In Android, this
feature can be implemented using the built-in TextToSpeech class, which allows the app to
read aloud text for a better user experience, especially for accessibility purposes (e.g.,
reading content aloud for visually impaired users).

Below are the steps to implement Text-to-Speech (TTS) functionality in an Android mobile
app.
1. Add TTS Permission (if required)

In Android, Text-to-Speech does not require any specific permissions in the


AndroidManifest.xml file. However, you might need to check if the TTS engine is available
on the device and handle situations where it is not supported.

2. Initialize TextToSpeech

Android provides a built-in TextToSpeech class that is responsible for converting text into
speech. You must initialize the TextToSpeech object before using it.

Steps for Initializing TTS:

1. Declare TextToSpeech Object:

private TextToSpeech textToSpeech;

2. Initialize TextToSpeech Object:

In the onCreate() method, initialize the TextToSpeech instance and set the listener to monitor
its initialization status.

Java:

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize TextToSpeech object

textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

// Language set for the TTS

int langResult = textToSpeech.setLanguage(Locale.US); // Set to US English

// Check if language is supported

if (langResult == TextToSpeech.LANG_MISSING_DATA

|| langResult == TextToSpeech.LANG_NOT_SUPPORTED) {

// Handle language data issues

Toast.makeText(MainActivity.this, "Language not supported or missing",


Toast.LENGTH_SHORT).show();
} else {

// Language is successfully set

Toast.makeText(MainActivity.this, "TTS Initialized", Toast.LENGTH_SHORT).show();

} else {

// Initialization failed

Toast.makeText(MainActivity.this, "Initialization failed",


Toast.LENGTH_SHORT).show();

});

3. Use TTS to Speak Text

Once the TextToSpeech object is initialized, you can use the speak() method to convert text
into speech.

textToSpeech.speak("Hello, welcome to the app!", TextToSpeech.QUEUE_FLUSH, null, null);

 TextToSpeech.QUEUE_FLUSH: This ensures that any previous speech in the queue is


cleared before starting the new speech.

 null: These are for parameters like speech rate, pitch, and any additional settings you
might want to apply.

You can also modify the speech rate and pitch of the voice.

4. Set Speech Rate and Pitch

To adjust the speed (rate) and the tone (pitch) of the speech, use the following methods:

// Set speech rate (speed of speech)

textToSpeech.setSpeechRate(1.0f); // Normal speed

// Set pitch (tone of speech)

textToSpeech.setPitch(1.0f); // Normal pitch

 Speech Rate: The speed at which the text is spoken. A value of 1.0f is normal speed.
You can adjust it between 0.1f (slow) and 2.0f (fast).

 Pitch: The pitch of the voice. A value of 1.0f is normal pitch. You can adjust it to make
the voice higher or lower.

5. Handle TTS Shutdown

After using the TextToSpeech service, you need to properly shut it down to release resources.

@Override

protected void onDestroy() {


if (textToSpeech != null) {

textToSpeech.stop();

textToSpeech.shutdown();

super.onDestroy();

This ensures that the TTS engine is properly shut down when the activity or app is destroyed.

6. Example of Complete Code

XML Layout (activity_main.xml):

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp"

android:gravity="center">

<!-- Button to trigger Text-to-Speech -->

<Button

android:id="@+id/btnSpeak"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Speak Text"/>

</LinearLayout>

Activity Code (MainActivity.java):

public class MainActivity extends AppCompatActivity {

private TextToSpeech textToSpeech;

private Button btnSpeak;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Initialize TextToSpeech object

textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

int langResult = textToSpeech.setLanguage(Locale.US);

if (langResult == TextToSpeech.LANG_MISSING_DATA || langResult ==


TextToSpeech.LANG_NOT_SUPPORTED) {

Toast.makeText(MainActivity.this, "Language not supported or missing",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(MainActivity.this, "TTS Initialized",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(MainActivity.this, "Initialization failed",


Toast.LENGTH_SHORT).show();

});

// Button click listener to speak the text

btnSpeak = findViewById(R.id.btnSpeak);

btnSpeak.setOnClickListener(v -> {

String text = "Hello, welcome to the Android Text to Speech tutorial!";

textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);

});

@Override

protected void onDestroy() {

if (textToSpeech != null) {

textToSpeech.stop();
textToSpeech.shutdown();

super.onDestroy();

How synchronization and Replication of Mobile data is


performed?
Synchronization and Replication of Mobile Data

In the context of mobile applications, synchronization and replication are two critical
techniques for ensuring data consistency and availability across different devices and
servers. These methods help apps maintain up-to-date data and ensure that the data
remains available even when users are offline or using multiple devices.

Here’s a detailed explanation of how synchronization and replication work in mobile apps,
along with the differences and the process of implementation:

1. Synchronization of Mobile Data


Synchronization refers to the process of ensuring that the data stored on the mobile device
is consistent with the data on remote servers or other devices. This allows users to access
the latest information and ensures consistency across multiple platforms (e.g., mobile app
and server).

Types of Synchronization:
 One-way synchronization: Data flows in only one direction, from the device to the
server or vice versa. For example, syncing local changes to the server.

 Two-way synchronization: Data is synchronized in both directions (from device to


server and server to device). This ensures that any changes on the device or the server
are reflected in both places.

Synchronization Process:
1. Initial Data Fetch: When the app first starts, it may fetch data from the server to
populate the local database on the device. This process is known as initial
synchronization.

2. Data Change Detection: The app continuously tracks data changes. These could be
changes to local data (such as adding, updating, or deleting items) or changes that
occur remotely on the server.

3. Conflict Resolution: If there are conflicting changes (e.g., changes made both locally
and on the server), the system must resolve the conflict. This can be done using
several strategies:

o Timestamp-based: The most recent update is chosen.


o Versioning: Each data entity has a version number that is incremented when
changes occur.

o User input: The app asks the user to resolve the conflict.

4. Sync Process: After detecting changes, the mobile app sends or fetches data from the
server. The data can be transferred over the internet using APIs or web services (such
as RESTful APIs).

5. Network Management: Mobile apps must handle network changes (e.g., switching
between Wi-Fi and mobile data) and offline scenarios:

o Offline Mode: Data changes are stored locally and synchronized when the
network is available.

o Background Sync: Sync operations can be performed periodically or in the


background to keep the app data up-to-date.

Example Code (Android):

Using Android’s SyncAdapter class to manage synchronization.

public class MySyncAdapter extends AbstractThreadedSyncAdapter {

public MySyncAdapter(Context context, boolean autoInitialize) {

super(context, autoInitialize);

@Override

public void onPerformSync(Account account, Bundle extras, String authority,


ContentProviderClient provider, SyncResult syncResult) {

// Perform the data synchronization process here, e.g., pull data from the server

fetchDataFromServer();

private void fetchDataFromServer() {

// Example of using an API to fetch data

String url = "https://example.com/api/data";

// Fetch the data and update the local content provider

In this example, the SyncAdapter is used to manage data synchronization in the background.

2. Replication of Mobile Data


Replication refers to copying and maintaining data across multiple devices or servers. The
goal of replication is to ensure data redundancy and improve data availability. In mobile
applications, replication is used to maintain the same data on multiple devices or to back up
data to cloud servers.

Types of Replication:
 Master-Slave Replication: In this model, one server acts as the master, and other
servers (or devices) act as slaves. The master server holds the primary copy of the
data, and the slaves hold replicas. Data is replicated from the master to the slaves.

 Peer-to-Peer Replication: Here, all devices or servers are treated as equals. Each
device can both send and receive data, allowing for decentralized replication.

 Multi-Master Replication: In this model, multiple servers (or devices) can act as
masters and have the ability to read and write data. Changes made on one master
node are replicated to all others.

Replication Process:
1. Data Snapshot: A snapshot of the data is taken at a particular point in time. This
snapshot is replicated to other devices or servers.

2. Replication Mechanism: When data is updated on one device (or server), the change
is replicated to all other copies of the data. This could be done in real-time or
periodically, depending on the application requirements.

3. Conflict Management: Just like with synchronization, replication systems must handle
conflicts. This is typically done by using timestamps, version control, or user
intervention.

4. Data Consistency: Replication must ensure that all copies of the data are eventually
consistent. This means that, over time, all copies of the data should converge to the
same state, even if some copies were temporarily out-of-sync.

Example of Replication:

Consider a mobile application that replicates data between a local SQLite database and a
cloud server. Whenever a change occurs locally (such as adding a new contact), that change
is sent to the cloud, and the cloud server replicates the change to all other devices connected
to the same account.

For instance, if a user adds a new contact to their app while offline, the app will store the
data locally. Once the app goes online, it will send the change to the server, which will
replicate the new contact to other devices.

3. Challenges in Synchronization and Replication


 Network Issues: Mobile apps need to handle scenarios where the device has
intermittent or no network connectivity. Both synchronization and replication must
support offline functionality to allow changes to be made locally and synced when the
network is available.

 Data Conflicts: Handling conflicts when two devices or systems make different
changes to the same data at the same time. Proper conflict resolution strategies must
be implemented to ensure data consistency.

 Scalability: Replication across multiple devices or servers can become complex as the
number of devices grows. Efficient algorithms are needed to handle large-scale data
replication.
 Data Security: When replicating data across devices or servers, ensuring that data is
securely transferred and stored is critical, especially for sensitive data.

 Latency: Replicating data in real-time across devices or servers can introduce latency.
Developers must balance consistency with performance, especially for mobile
applications where performance is crucial.

4. Techniques and Tools for Synchronization and Replication


 Firebase Realtime Database: Firebase offers an easy-to-use solution for data
synchronization and replication. It automatically syncs data across all connected clients
in real time.

 CloudKit (Apple): Apple’s CloudKit service offers data synchronization and replication
features for iOS devices, allowing seamless syncing between local storage and the
cloud.

 CouchDB: CouchDB is a NoSQL database that supports multi-master replication and


offline capabilities, allowing for easy synchronization and replication of data across
devices.

 PouchDB: PouchDB is an open-source JavaScript database that works offline and


synchronizes with CouchDB or compatible servers.

 SQLite Sync Adapter: In Android, using the SyncAdapter with an SQLite database
allows mobile apps to sync data with a remote server.

Unit 3

What is Intent, intent objects and fields? List and explain


types of Intents
Intent in Android

An Intent in Android is a messaging object used to request an action from another


component (such as an activity, service, or broadcast receiver). Intents allow you to
communicate between different components of an app or even across apps. They can carry
data (such as user input or results of operations) and specify the action to be performed.

An Intent can be used for several purposes, such as:

 Starting an activity (e.g., navigating from one screen to another).

 Starting a service (e.g., performing background tasks).

 Broadcasting a message (e.g., sending a message to other components of the


system or apps).

Intent Objects

An Intent object is created using the Intent class in Android. It specifies the action to be
performed, the data to operate on, and other optional parameters like categories, flags, and
extras (extra data). You can create an Intent in several ways, such as starting a new activity,
invoking services, or broadcasting information.
The basic syntax to create an Intent is:

Intent intent = new Intent(Context context, TargetActivity.class);

Alternatively, for implicit intents, you can specify actions or data:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));

Intent Fields

An Intent object typically has several fields, which define what actions or components the
intent will interact with. Here are the important fields associated with intents:

1. Action: Describes the action to be performed, such as viewing a URL, picking a


contact, etc. Common actions include:

o Intent.ACTION_VIEW

o Intent.ACTION_SEND

o Intent.ACTION_MAIN

o Intent.ACTION_PICK

2. Data (URI): A URI (Uniform Resource Identifier) that provides the location of the data
to be used or operated on. For example, an intent to view a specific URL might use
http://www.example.com.

3. Category: Specifies the type of component that should handle the intent. Common
categories include:

o Intent.CATEGORY_DEFAULT

o Intent.CATEGORY_LAUNCHER

o Intent.CATEGORY_ALTERNATIVE

4. Extras: Additional data that is passed along with the intent. Extras are usually key-
value pairs (bundles) containing data like strings, numbers, and objects. The data is
stored in a Bundle.

intent.putExtra("key", value);

5. Flags: Flags provide additional instructions to the Android system about how to treat
the intent. Examples include:

o Intent.FLAG_ACTIVITY_NEW_TASK — Starts a new activity.

o Intent.FLAG_ACTIVITY_CLEAR_TOP — Clears the current activity stack.

6. Component: Specifies which component (activity, service, or broadcast receiver)


should handle the intent. If not specified, Android will find the most suitable component
based on the action.

7. Type: The MIME type of the data being passed with the intent, used mainly with implicit
intents to specify the data format (e.g., text/plain, image/jpeg).

Types of Intents

There are two main types of Intents in Android:


1. Explicit Intent

An explicit intent is used when you know the exact component (such as a specific activity
or service) that should handle the intent. You explicitly specify the target class of the
component.

 Usage: Primarily used within an app to navigate between activities or start specific
services.

 Example: Starting a new Activity or Service within the same app.

Example (explicit intent):

java

Copy code

Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);

startActivity(intent);

In this example, the intent is explicitly created for TargetActivity.

2. Implicit Intent

An implicit intent does not specify the exact component to handle the request. Instead, it
relies on the Android system to find a suitable component based on the action and data
specified. The system will search for all registered components that can handle the given
action.

 Usage: Used when you want to perform a task but don’t know which specific
component should handle it (for example, opening a web page, sending an email, etc.).

 Example: Sharing a photo via email, viewing a website, or opening a map.

Example (implicit intent):

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));

startActivity(intent);

In this case, Android will find an appropriate app that can handle the ACTION_VIEW action
with the URL data.

Common Actions in Intents

Some common actions that an intent can perform:

 Intent.ACTION_VIEW: Used to display data (like opening a URL in a browser or viewing a


photo).

 Intent.ACTION_SEND: Used to send data (like sending an email or sharing content).

 Intent.ACTION_EDIT: Used to allow the user to edit data (like editing a contact).

 Intent.ACTION_PICK: Used to select data from a collection (like picking a contact or


photo).

 Intent.ACTION_MAIN: The main entry point for an activity, often used to launch the app.

 Intent.ACTION_CALL: Initiates a phone call (requires CALL_PHONE permission).


 Intent.ACTION_DIAL: Opens the dialer with a phone number (does not require
permission).

Example of Explicit and Implicit Intents

Explicit Intent Example (Navigating Between Activities)

// Creating an explicit intent to start another activity

Intent intent = new Intent(MainActivity.this, SecondActivity.class);

startActivity(intent);

Implicit Intent Example (Opening a Web Page)

// Creating an implicit intent to open a web page

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));

startActivity(intent);

Setting Intent Data and Extras

You can pass additional data with an intent using putExtra() to send key-value pairs.

Example: Passing a string extra:

Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);

intent.putExtra("message", "Hello, World!");

startActivity(intent);

In the receiving activity, you can retrieve this extra data using getIntent().getStringExtra():

Intent intent = getIntent();

String message = intent.getStringExtra("message");

Flags in Intents

Flags control how activities are launched and how the back stack is handled.

 Intent.FLAG_ACTIVITY_NEW_TASK: Starts a new task and a new activity.

 Intent.FLAG_ACTIVITY_CLEAR_TOP: If the activity being launched is already in the stack,


all activities on top of it are popped off.

 Intent.FLAG_ACTIVITY_SINGLE_TOP: If the activity is already at the top of the stack, it


will reuse the existing instance instead of creating a new one.

Example of setting a flag:

Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);
Conclusion

 Intent: A messaging object used to request actions from other components (e.g.,
activities, services, and broadcast receivers).

 Explicit Intent: Specifies the exact component to handle the request.

 Implicit Intent: Relies on the Android system to find a suitable component to handle
the request.

 Intent Fields: Includes action, data, category, flags, and extras.

Understanding explicit and implicit intents, along with how to use actions, categories, and
data, is crucial for navigating and managing components within Android applications.

Explain the steps for sending and receiving the implicit


intents.
Steps for Sending and Receiving Implicit Intents in Android
In Android, implicit intents are used to request an action, but they don't specify a specific
component (e.g., an activity or service) to handle the request. Instead, Android's system will
find an appropriate component (such as an app that can handle the action) based on the
action and data specified in the intent.

Steps for Sending Implicit Intents

When sending an implicit intent, the action is specified, but no specific component is defined.
Android uses the action and data to find the most appropriate app that can perform the
requested task.

1. Create an Intent with Action and Data

You need to create an Intent with an action (what you want to do, such as view or send) and,
optionally, data (what the intent is acting on, such as a URL or file).

 Action: An action string (e.g., Intent.ACTION_VIEW to view data).

 Data: A URI representing the data (e.g., a URL, file path, or contact).

Example: Opening a website with ACTION_VIEW

java

Copy code

// Create an implicit intent to open a webpage

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));

startActivity(intent);

 The action ACTION_VIEW tells Android to open the data (http://www.example.com) in a


suitable browser or app.

 The Uri.parse() function is used to specify the data that is being acted upon (a URL in
this case).

2. Optionally Add Extra Data


You can add additional data (like user input, settings, or configurations) to the intent using
extras.

java

Copy code

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.example.com"));

intent.putExtra("extra_key", "extra_value");

startActivity(intent);

 Here, "extra_key" and "extra_value" represent additional data passed with the intent.

3. Start the Activity

Once the intent is configured, you send it using the startActivity() method, which lets Android
decide which app or activity should handle the intent based on the action and data provided.

Steps for Receiving Implicit Intents

The receiving app (activity, service, or broadcast receiver) must be prepared to handle
implicit intents, which means the component must declare the necessary intent filters in the
AndroidManifest.xml file.

1. Declare Intent Filters in the Manifest

To receive implicit intents, an activity must declare an intent filter in the


AndroidManifest.xml. This filter specifies which actions and data types the component (e.g.,
an activity) can handle.

 Action: The type of action (e.g., ACTION_VIEW).

 Category: Optional, used to refine what kind of component can handle the intent.

 Data: Specifies the data (e.g., URI schemes, file types) that can be handled.

Example (Manifest Declaration for Receiving Implicit Intents):

xml

Copy code

<activity android:name=".WebViewActivity">

<intent-filter>

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

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

<data android:scheme="http" android:host="www.example.com"/>

</intent-filter>

</activity>

 This filter tells Android that WebViewActivity can handle VIEW actions with http URIs
that point to www.example.com.

2. Handle the Intent in the Activity


In the activity that handles the implicit intent, you can retrieve the data from the Intent
object in onCreate() or onResume(). Specifically, you access the data (such as the URL) and
perform the intended action (e.g., display the webpage).

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class WebViewActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_webview);

// Get the intent and extract the data

Intent intent = getIntent();

Uri data = intent.getData(); // Retrieve the data (URL)

// Perform action with the data (e.g., display in WebView or open browser)

if (data != null) {

// For simplicity, show a toast

Toast.makeText(this, "Received URL: " + data.toString(), Toast.LENGTH_LONG).show();

 The getIntent().getData() method retrieves the data passed with the intent, and you
can then act on it.

3. Handle Multiple Intent Filters

If there are multiple activities or apps that can handle the same implicit intent, Android will
display a chooser (e.g., a dialog asking the user which app they want to use). If your app is
one of the possibilities, the user can select it.

Implicit Intent Example: Sending and Receiving a Photo

Let’s break it down into a practical example of sending and receiving a photo using an
implicit intent.
1. Sending an Implicit Intent to Pick a Photo (ACTION_PICK)

Intent intent = new Intent(Intent.ACTION_PICK,


MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(intent, PICK_IMAGE_REQUEST);

 This implicit intent lets the user pick a photo from their gallery (handled by any app
that can access the gallery).

 MediaStore.Images.Media.EXTERNAL_CONTENT_URI is a URI to the image media on the


device.

2. Receiving the Selected Image in onActivityResult()

To handle the result of the image selection, override onActivityResult() to retrieve the
selected image URI.

java

Copy code

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null)


{

Uri selectedImageUri = data.getData();

// Do something with the selected image URI

Toast.makeText(this, "Image selected: " + selectedImageUri,


Toast.LENGTH_SHORT).show();

Key Points About Implicit Intents

1. Action: Defines the task to be performed (e.g., ACTION_VIEW, ACTION_SEND,


ACTION_DIAL).

2. Data: Specifies the data for the action (e.g., a URI for a web page, a file path for an
image).

3. Intent Filter: Required in the receiving component's AndroidManifest.xml to declare


which intents the component can handle.

4. Chooser Dialog: If multiple apps can handle the same intent, Android shows a chooser
dialog to let the user select which app to use.

Summary
 Sending Implicit Intents: Create an Intent with an action and data, then call
startActivity(). Android will search for a matching component.

 Receiving Implicit Intents: Declare intent filters in the AndroidManifest.xml file to


specify what actions and data types your activity can handle. Handle the intent in the
onCreate() method (or another lifecycle method) of the receiving component.

 Extras: You can also add extra data to the intent using putExtra() to pass additional
information along with the request.

This approach allows you to build flexible apps that can interact with other apps in a
seamless way, without knowing in advance which app will handle the action.

What is Broadcast Receiver? How do you create Broadcast


Receiver?
Broadcast Receiver in Android
A Broadcast Receiver in Android is a component that listens for and responds to system-
wide or app-specific events (broadcasts). These events are sent as broadcasts by various
applications or system services to notify other apps or components about specific actions,
such as a change in network connectivity, battery status, or receiving a new SMS.

Broadcast Receivers allow apps to react to these broadcasts and perform corresponding
actions, such as showing notifications, updating UI elements, or even launching background
services.

Types of Broadcasts

There are two main types of broadcasts in Android:

1. Normal Broadcasts:

o Sent to all interested receivers simultaneously.

o No priority or ordered behavior; receivers do not interfere with each other.

2. Ordered Broadcasts:

o Sent to receivers one at a time in a specific order.

o Each receiver can either abort the broadcast or modify the broadcast’s data
before passing it to the next receiver.

o Allows higher-priority receivers to act before others.

How to Create a Broadcast Receiver

There are two ways to create a Broadcast Receiver in Android:

1. Using a Java class: You can create a class that extends BroadcastReceiver and
override the onReceive() method to handle the broadcast.

2. Using an anonymous inner class: You can also define a broadcast receiver without
creating a separate class by using an anonymous inner class.

Let’s break these down:


1. Creating a Broadcast Receiver Using a Java Class

To create a BroadcastReceiver in Android, follow these steps:

1. Create a new class that extends BroadcastReceiver: Override the onReceive()


method, which is called when the broadcast is received. The onReceive() method
accepts two parameters:

o Context context: Provides access to app-specific resources.

o Intent intent: The broadcast intent that contains information about the broadcast
event.

Example:

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

// Handle the broadcast

Toast.makeText(context, "Broadcast Received!", Toast.LENGTH_SHORT).show();

2. Register the Broadcast Receiver: There are two ways to register a


BroadcastReceiver:

o Static Registration in the AndroidManifest file (used for system-wide


broadcasts).

o Dynamic Registration in code (used for app-specific or local broadcasts).

Static Registration (Manifest Declaration)

In static registration, you define the BroadcastReceiver in the AndroidManifest.xml file. This
way, the receiver listens for specific system broadcasts even when the app is not running. It
is used for global events such as system shutdown, screen state changes, etc.

Steps:

1. Add the receiver declaration to your AndroidManifest.xml file.

2. Specify the action you want to listen for in the <intent-filter> tag.

Example (AndroidManifest.xml):
<receiver android:name=".MyBroadcastReceiver">

<intent-filter>

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

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

</intent-filter>

</receiver>

In this example, the receiver listens for two actions: when the device boots up
(BOOT_COMPLETED) and when the power is connected (ACTION_POWER_CONNECTED).

Dynamic Registration (Code Registration)

In dynamic registration, you register the BroadcastReceiver at runtime using the


registerReceiver() method. This is useful for app-specific broadcasts and when you want to
unregister the receiver after a certain point (e.g., in onPause() or onDestroy()).

Steps:

1. Register the receiver in your activity or service using registerReceiver().

2. Unregister the receiver when no longer needed using unregisterReceiver().

Example (Activity Code):

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Bundle;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private BroadcastReceiver myReceiver;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
// Create and register the receiver

myReceiver = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

// Handle the broadcast

Toast.makeText(context, "Broadcast Received!", Toast.LENGTH_SHORT).show();

};

// Register the receiver to listen for a specific action

IntentFilter filter = new IntentFilter();

filter.addAction("com.example.myapp.MY_CUSTOM_BROADCAST");

registerReceiver(myReceiver, filter);

@Override

protected void onDestroy() {

super.onDestroy();

// Unregister the receiver to prevent memory leaks

unregisterReceiver(myReceiver);

In this example, the app registers a receiver for a custom broadcast action
(com.example.myapp.MY_CUSTOM_BROADCAST). The receiver listens for this action while the
activity is active.

2. Sending a Broadcast

Once you have a broadcast receiver set up, you may want to send a broadcast that the
receiver can handle. You can send both normal broadcasts and ordered broadcasts.

Normal Broadcast

Example (Sending a Broadcast):

Intent intent = new Intent();

intent.setAction("com.example.myapp.MY_CUSTOM_BROADCAST");

sendBroadcast(intent);

Ordered Broadcast
You can send ordered broadcasts where receivers have the opportunity to modify the data or
abort the broadcast.

Example (Sending an Ordered Broadcast):

Intent intent = new Intent();

intent.setAction("com.example.myapp.ORDERED_BROADCAST");

sendOrderedBroadcast(intent, null);

3. Permissions in Broadcast Receivers

Certain broadcasts require special permissions to listen for or send them. For instance, to
listen for the system broadcast BOOT_COMPLETED, your app must declare the
RECEIVE_BOOT_COMPLETED permission in the manifest:

Example (Manifest):

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

Broadcast Receiver Lifecycle

The lifecycle of a broadcast receiver is quite simple:

 onReceive(): This method is called when the broadcast is received. It is a short-lived


method and should complete quickly. It is called on the main UI thread.

 Once the onReceive() method finishes, the broadcast receiver is destroyed. Unlike
activities, broadcast receivers do not have a persistent lifecycle.

Conclusion

 Broadcast Receiver: A component used to listen for and respond to system-wide or


app-specific broadcasts. It allows your app to react to events like power changes,
network status, or custom application-specific actions.

 You can create a BroadcastReceiver by either:

o Defining a separate Java class that extends BroadcastReceiver.

o Using an anonymous class in the Activity or Service.

 Static Registration: Used in the AndroidManifest.xml for global system events.

 Dynamic Registration: Used in the app code for app-specific broadcasts or when you
want to register/unregister receivers at runtime.

By using Broadcast Receivers, Android apps can efficiently listen to and react to important
system or user-generated events.
How do you make an HTTP connection to connect to internet?
To make an HTTP connection to the internet in Android, you can use several different
methods. The most common approach is to use HttpURLConnection or higher-level libraries
like OkHttp or Retrofit. Here’s a detailed explanation of each method, starting with
HttpURLConnection.

1. Using HttpURLConnection to Connect to the Internet

HttpURLConnection is part of Android’s standard library, and it allows you to make HTTP
requests to the internet. Below are the steps to create an HTTP connection in Android:

Step 1: Add Permissions in AndroidManifest.xml

Before making any HTTP connection, you must ensure that the app has the necessary
permissions to access the internet.

xml

Copy code

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

If you need to check for network connectivity (whether the device is connected to the
internet), you can also add:

xml

Copy code

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

Step 2: Making an HTTP Request with HttpURLConnection

Here’s a basic example of how to send an HTTP GET request using HttpURLConnection:

Example: HTTP GET Request with HttpURLConnection

java

Copy code

import java.io.InputStreamReader;

import java.io.BufferedReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.io.IOException;

public class HttpClient {

public String makeHttpGetRequest(String urlString) throws IOException {

// Create URL object

URL url = new URL(urlString);


// Open an HTTP connection

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set the HTTP request method

connection.setRequestMethod("GET");

// Set the connection timeout and read timeout (optional but recommended)

connection.setConnectTimeout(15000); // 15 seconds to establish a connection

connection.setReadTimeout(15000); // 15 seconds to read data

// Get the response code to check if the connection was successful

int responseCode = connection.getResponseCode();

// Read the response if the request was successful

StringBuilder response = new StringBuilder();

if (responseCode == HttpURLConnection.HTTP_OK) {

// Create a BufferedReader to read the response

BufferedReader in = new BufferedReader(new


InputStreamReader(connection.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

in.close();

} else {

// Handle the error (e.g., display an error message or log it)

response.append("Error: " + responseCode);

// Return the response data

return response.toString();

}
 In the above code, we create a URL object from a string URL and establish an
HttpURLConnection to it.

 We then set the request method to "GET" (you can change it to "POST" for sending
data).

 We check if the response code is HTTP_OK (200), meaning the request was successful,
and then read the response data.

 We return the response data as a string.

Step 3: Handling Network Operations in a Separate Thread

Important: Network operations cannot be performed on the main UI thread in


Android because it may lead to Application Not Responding (ANR) errors. Hence, network
operations should be done on a background thread or use asynchronous tasks.

You can use AsyncTask or Thread to handle the HTTP request in the background.

Example with AsyncTask:

java

Copy code

import android.os.AsyncTask;

import android.widget.Toast;

import android.content.Context;

public class FetchDataTask extends AsyncTask<String, Void, String> {

private Context context;

public FetchDataTask(Context context) {

this.context = context;

@Override

protected String doInBackground(String... params) {

try {

// Use the method from HttpClient to fetch data

HttpClient client = new HttpClient();

return client.makeHttpGetRequest(params[0]);

} catch (IOException e) {

e.printStackTrace();
return "Error: " + e.getMessage();

@Override

protected void onPostExecute(String result) {

// Display the result in a Toast or update UI here

Toast.makeText(context, "Response: " + result, Toast.LENGTH_LONG).show();

Now, you can call this AsyncTask in your activity or fragment:

java

Copy code

// Call AsyncTask to perform the HTTP GET request

new FetchDataTask(this).execute("https://api.example.com/data");

This way, the HTTP request is handled in the background thread, and the result is passed to
the main UI thread via onPostExecute().

2. Using OkHttp for HTTP Requests

OkHttp is a more modern, flexible, and efficient HTTP client that makes it easier to send HTTP
requests and handle responses. It is commonly used in Android apps for network operations.

To use OkHttp, you first need to add the library dependency in the build.gradle file:

gradle

Copy code

dependencies {

implementation("com.squareup.okhttp3:okhttp:4.9.0")

Example: HTTP GET Request with OkHttp

java

Copy code

import okhttp3.OkHttpClient;

import okhttp3.Request;

import okhttp3.Response;

import java.io.IOException;
public class OkHttpClientExample {

public String makeHttpGetRequest(String urlString) throws IOException {

// Create OkHttpClient instance

OkHttpClient client = new OkHttpClient();

// Build the request

Request request = new Request.Builder()

.url(urlString)

.build();

// Execute the request

try (Response response = client.newCall(request).execute()) {

if (response.isSuccessful()) {

// Return the response body as string

return response.body().string();

} else {

return "Error: " + response.code();

In this code, we use OkHttpClient to send a GET request to the specified URL. The Response
object contains the server's response, which you can handle (e.g., extract the body and
return it).

3. Using Retrofit for Network Requests

Retrofit is a powerful library for making HTTP requests in a more structured and object-
oriented way. It abstracts away much of the boilerplate code involved with making HTTP calls.

To use Retrofit, you need to add the dependencies in the build.gradle file:

gradle

Copy code

dependencies {

implementation("com.squareup.retrofit2:retrofit:2.9.0")

implementation("com.squareup.retrofit2:converter-gson:2.9.0") // for JSON conversion


}

Example: HTTP GET Request with Retrofit

java

Copy code

import retrofit2.Call;

import retrofit2.Callback;

import retrofit2.Response;

import retrofit2.Retrofit;

import retrofit2.http.GET;

public class RetrofitClient {

interface ApiService {

@GET("data")

Call<String> getData();

public void fetchData() {

Retrofit retrofit = new Retrofit.Builder()

.baseUrl("https://api.example.com/")

.addConverterFactory(GsonConverterFactory.create())

.build();

ApiService apiService = retrofit.create(ApiService.class);

// Make the HTTP GET request asynchronously

Call<String> call = apiService.getData();

call.enqueue(new Callback<String>() {

@Override

public void onResponse(Call<String> call, Response<String> response) {

if (response.isSuccessful()) {

// Handle the response

String responseData = response.body();

System.out.println(responseData);
} else {

// Handle error response

System.out.println("Error: " + response.code());

@Override

public void onFailure(Call<String> call, Throwable t) {

// Handle failure

t.printStackTrace();

});

 Retrofit takes care of the network connection and response parsing, making it much
simpler to use than HttpURLConnection or OkHttp in many cases.

Conclusion

To make an HTTP connection in Android, you can:

1. HttpURLConnection: A standard API for HTTP requests but requires more manual
handling of HTTP connections and responses.

2. OkHttp: A more modern and efficient HTTP client with built-in support for common
features like caching and retries.

3. Retrofit: A high-level library that simplifies working with HTTP APIs by abstracting the
process and automatically converting responses into Java objects.

Each method has its advantages, but OkHttp and Retrofit are highly recommended for their
ease of use and powerful features.

What is a Service? How do you implement Started Service and


Bound Service? Explain.
Service
Services in Android are a special component that facilitates an application to run in the
background in order to perform long-running operation tasks. The prime aim of a service is to
ensure that the application remains active in the background so that the user can operate
multiple applications at the same time. A user-interface is not desirable for android services
as it is designed to operate long-running processes without any user intervention. A service
can run continuously in the background even if the application is closed or the user switches
to another application. Further, application components can bind itself to service to carry
out inter-process communication(IPC) . There is a major difference between android
services and threads, one must not be confused between the two. Thread is a feature
provided by the Operating system to allow the user to perform operations in the background.
While service is an android component that performs a long-running operation about which
the user might not be aware of as it does not have UI.

Types of Android Services

1. Foreground Services:

Services that notify the user about its ongoing operations are termed as Foreground Services.
Users can interact with the service by the notifications provided about the ongoing task. Such
as in downloading a file, the user can keep track of the progress in downloading and can also
pause and resume the process.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

2. Background Services:

Background services do not require any user intervention. These services do not notify the
user about ongoing background tasks and users also cannot access them. The process like
schedule syncing of data or storing of data fall under this service.

3. Bound Services:

This type of android service allows the components of the application like activity to bound
themselves with it. Bound services perform their task as long as any application component
is bound to it. More than one component is allowed to bind themselves with a service at a
time. In order to bind an application component with a service bindService() method is
used.

The Life Cycle of Android Services

In android, services have 2 possible paths to complete its life cycle namely Started and
Bounded .

1. Started Service (Unbounded Service):

By following this path, a service will initiate when an application component calls
the startService() method. Once initiated, the service can run continuously in the
background even if the component is destroyed which was responsible for the start of the
service. Two option are available to stop the execution of service:

 By calling stopService() method,


 The service can stop itself by using stopSelf() method.

2. Bounded Service:

It can be treated as a server in a client-server interface. By following this path, android


application components can send requests to the service and can fetch results. A service is
termed as bounded when an application component binds itself with a service by
calling bindService() method. To stop the execution of this service, all the components must
unbind themselves from the service by using unbindService() method.

In Android, services are used to perform background tasks. There are two types of services:
Started Services and Bound Services. Both types have different use cases and ways of
interaction with the application components. Below is a detailed explanation of how to
implement each type of service:

1. Started Service

A Started Service is a service that is initiated by an application component (such as an


activity or broadcast receiver) to perform a task in the background. It runs until the task is
completed, or it is explicitly stopped by the application using stopSelf() or stopService().

Key Characteristics of Started Service

 It is started by calling startService() method.

 It runs in the background indefinitely or until explicitly stopped.

 It doesn't interact directly with the components that start it.

Steps to Implement a Started Service

1. Create the Service class


A Started Service typically extends the Service class. Override the onStartCommand()
method, where you define the task to run in the background.

Example of a Started Service (MyService.java):

import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;

public class MyService extends Service {

@Override

public void onCreate() {

super.onCreate();

// Initialize resources

Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// Perform background task

new Thread(new Runnable() {

@Override

public void run() {

// Simulate a task (e.g., downloading data, processing, etc.)

try {

Thread.sleep(5000); // Simulating a long-running task

} catch (InterruptedException e) {

e.printStackTrace();

// Task completed

stopSelf(); // Stop the service once the task is done

}).start();
return START_STICKY; // Indicates that the service should be restarted if killed

@Override

public void onDestroy() {

super.onDestroy();

// Clean up resources

Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();

@Override

public IBinder onBind(Intent intent) {

return null; // No binding in a started service

2. Register the Service in the Manifest

You need to declare the service in the AndroidManifest.xml file:

<service android:name=".MyService" />

3. Start the Service from an Activity

To start the service from an activity or any other component, you call startService() and
provide an Intent to the service:

Intent serviceIntent = new Intent(this, MyService.class);

startService(serviceIntent);

Stopping the Service:

To stop the service manually, you can call stopService() or stopSelf() within the service itself
after the task is complete:

stopService(serviceIntent); // Stops the service from an activity

Or, inside the service class:

java

Copy code

stopSelf(); // Stops the service after completing the task

Example Usage:

 Use Case: A background task that plays music, downloads files, or processes data.
2. Bound Service

A Bound Service is a service that allows components (such as activities or other services) to
interact with it. It provides an interface for communication between the service and the
components that bind to it. A bound service only runs as long as at least one component is
bound to it.

Key Characteristics of Bound Service

 It is started by calling bindService().

 It provides an interface to other components via Binder or Messenger.

 It allows for two-way communication between the service and the component that
binds to it.

 It stops when all clients have unbound from it.

Steps to Implement a Bound Service

1. Create the Service class

In a bound service, you need to override the onBind() method to return an IBinder object,
which will be used for communication between the service and the binding component.

Example of a Bound Service (MyBoundService.java):

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.widget.Toast;

public class MyBoundService extends Service {

// Define a Binder for communication

private final IBinder binder = new LocalBinder();

@Override

public void onCreate() {

super.onCreate();

Toast.makeText(this, "Bound Service Created", Toast.LENGTH_SHORT).show();

@Override

public IBinder onBind(Intent intent) {


return binder; // Return the Binder object to allow communication

@Override

public void onUnbind(Intent intent) {

super.onUnbind(intent);

Toast.makeText(this, "Service Unbound", Toast.LENGTH_SHORT).show();

public class LocalBinder extends Binder {

// This method is used by clients to access the service

public MyBoundService getService() {

return MyBoundService.this;

@Override

public void onDestroy() {

super.onDestroy();

Toast.makeText(this, "Bound Service Destroyed", Toast.LENGTH_SHORT).show();

2. Register the Service in the Manifest

As with a started service, you need to declare the service in the AndroidManifest.xml:

<service android:name=".MyBoundService" />

3. Bind the Service from an Activity

In the activity, use the bindService() method to bind to the service and access its methods
via the Binder object.

Activity Code for Binding the Service:

import android.content.ComponentName;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.IBinder;

import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

MyBoundService myBoundService;

boolean isBound = false;

private ServiceConnection serviceConnection = new ServiceConnection() {

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

MyBoundService.LocalBinder binder = (MyBoundService.LocalBinder) service;

myBoundService = binder.getService();

isBound = true;

Toast.makeText(MainActivity.this, "Service Bound", Toast.LENGTH_SHORT).show();

@Override

public void onServiceDisconnected(ComponentName name) {

isBound = false;

};

@Override

protected void onStart() {

super.onStart();

// Bind the service when the activity starts

Intent intent = new Intent(this, MyBoundService.class);

bindService(intent, serviceConnection, BIND_AUTO_CREATE);

@Override

protected void onStop() {

super.onStop();

// Unbind the service when the activity stops


if (isBound) {

unbindService(serviceConnection);

isBound = false;

Toast.makeText(this, "Service Unbound", Toast.LENGTH_SHORT).show();

o bindService() is used to bind to the service. The ServiceConnection interface


provides methods to handle when the service is connected or disconnected.

o unbindService() is called when the component is no longer using the service.

4. Interacting with the Bound Service

Once bound, the client (activity) can call the public methods of the service directly,
which is enabled by the Binder object. In this case, we access the getService() method
from the LocalBinder.

Key Differences Between Started and Bound Services

Aspect Started Service Bound Service


Lifecycle Runs until explicitly stopped Runs only as long as at least one
(stopSelf()) client is bound
Client No direct interaction, runs in the Provides an interface for client
Interaction background communication
Use Case Background tasks like downloading Provides real-time communication
files, playing music (e.g., data updates)

Use Cases

 Started Service: Use when you want to run a background task that doesn’t require
interaction with the activity (e.g., long-running operations like downloading a file or
processing data).

 Bound Service: Use when you need to communicate between the service and the
activity or other components. For example, when the service provides real-time
updates, such as when retrieving data from a network or performing calculations.

What is a Notification? Explain the implementation steps for


creating Notifications.
Notifications in Android with Example
Notification is a kind of message, alert, or status of an application (probably running in the
background) that is visible or available in the Android’s UI elements. This application could be
running in the background but not in use by the user. The purpose of a notification is to notify
the user about a process that was initiated in the application either by the user or the
system. This article could help someone who’s trying hard to create a notification for
developmental purposes.

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, and 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)

In this article, we will be discussing how to produce notifications in Kotlin.

Step by Step Implementation


Step 1: Create a New Project

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

Step 2: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. In this step, we are going to
design our layout page. Here, we will use the RelativeLayout to get the Scroll View from the
Kotlin file. Below is the code for 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>

Step 3: Create a new empty activity

Reference article: How to Create Constructor, Getter/Setter Methods and New Activity in
Android Studio using Shortcuts?

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"

android:layout_centerInParent="true"

android:text="Welcome To GeeksforGeeks"

android:textSize="15sp"

android:textStyle="bold" />

</RelativeLayout>

Note 1: Without configuring Notification Channels, you cannot build notification for
applications with Android API >=26. For them generating a notification channel is mandatory.
Apps with API<26 don’t need notification channels they just need notification builder. Each
channel is supposed to have a particular behavior that will be applicable to all the
notifications which are a part of it. Every channel will, therefore, have a Channel ID which
basically will act as a unique identifier for this Channel which will be useful if the user wants
to differentiate a particular notification channel. In contrast, the Notification builder provides
a convenient way to set the various fields of a Notification and generate content views using
the platform’s notification layout template but is not able to target a particular notification
channel.

Note 2: If you have referred any other documentation or any other blog before this one, you
might have noticed them appealing to implement the following
dependency“com.android.support:support-compat:28.0.0”. What I’ve personally
experienced is that there’s no need to implement it, things go far and good without this also.

Step 4: Working with the MainActivity.kt file

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

import android.app.Notification

import android.app.NotificationChannel

import android.app.NotificationManager

import android.app.PendingIntent

import android.content.Context

import android.content.Intent

import android.graphics.BitmapFactory

import android.graphics.Color

import android.os.Build

import android.os.Bundle

import android.widget.Button

import android.widget.RemoteViews

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

// declaring variables

lateinit var notificationManager: NotificationManager

lateinit var notificationChannel: NotificationChannel

lateinit var builder: Notification.Builder

private val channelId = "i.apps.notifications"

private val description = "Test notification"

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

// accessing button

val btn = findViewById<Button>(R.id.btn)

// it is a class to notify the user of events that happen.

// This is how you tell the user that something has happened in the

// background.

notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager

// onClick listener for the button

btn.setOnClickListener {

// pendingIntent is an intent for future use i.e after

// the notification is clicked, this intent will come into action

val intent = Intent(this, afterNotification::class)

// FLAG_UPDATE_CURRENT specifies that if a previous

// PendingIntent already exists, then the current one

// will update it with the latest intent

// 0 is the request code, using it later with the

// same method again will get back the same pending

// intent for future reference

// intent passed here is to our afterNotification class

val pendingIntent = PendingIntent.getActivity(this, 0, intent,


PendingIntent.FLAG_UPDATE_CURRENT)

// RemoteViews are used to use the content of

// some different layout apart from the current activity layout

val contentView = RemoteViews(packageName, R.layout.activity_after_notification)

// checking if android version is greater than oreo(API 26) or not

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


notificationChannel = NotificationChannel(channelId, description,
NotificationManager.IMPORTANCE_HIGH)

notificationChannel.enableLights(true)

notificationChannel.lightColor = Color.GREEN

notificationChannel.enableVibration(false)

notificationManager.createNotificationChannel(notificationChannel)

builder = Notification.Builder(this, channelId)

.setContent(contentView)

.setSmallIcon(R.drawable.ic_launcher_background)

.setLargeIcon(BitmapFactory.decodeResource(this.resources,
R.drawable.ic_launcher_background))

.setContentIntent(pendingIntent)

} else {

builder = Notification.Builder(this)

.setContent(contentView)

.setSmallIcon(R.drawable.ic_launcher_background)

.setLargeIcon(BitmapFactory.decodeResource(this.resources,
R.drawable.ic_launcher_background))

.setContentIntent(pendingIntent)

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

With this, we have now successfully created a “Notification” for our application. Note that the
parameters listed in the above code are required and the absence of any single parameter
could result in crashing or not starting the application. The content title, content text, small
icon are customizable parameters but are mandatory also. One can change their values
according to the requirement.
Explain the Notification design guidelines.
Notification Design Guidelines in Android
Notifications are an essential part of the user experience in Android apps, allowing apps to
alert users about important events or updates. Android provides a flexible system for creating
and managing notifications. However, there are best practices and design guidelines to
ensure notifications are effective, non-intrusive, and align with Android's UX standards.

Here’s a detailed overview of Notification Design Guidelines in Android:

1. Notification Types

There are different types of notifications you can create in Android, each suited to different
purposes. Understanding these types helps you decide the most appropriate format for your
app’s notification.

Types of Notifications:

 Standard Notifications: These are simple notifications with a title, text, and icon.
They can include additional elements like images or action buttons.

 Heads-Up Notifications: These notifications pop up at the top of the screen to grab
attention, typically used for high-priority notifications.

 Big Notifications: Larger notifications with additional content such as an expandable


text or a larger image.

 Ongoing Notifications: These notifications indicate an ongoing process, such as


music playback or a file download, and cannot be dismissed until the process
completes.

 Custom Notifications: These allow for the design of notifications that break the
standard format and include custom layouts or media (e.g., large images, rich text).

2. Notification Channels (Android 8.0 and above)

Introduced in Android 8.0 (API level 26), Notification Channels allow users to control the
types of notifications they want to receive, giving them more granular control over their
notifications.

 Importance: Each channel has an importance level that determines how the
notification is displayed (e.g., sound, vibration, or silent).

 Categories: Channels can be categorized by their purpose (e.g., messaging, social


updates, reminders).

Example of creating a Notification Channel:

java

Copy code

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

CharSequence name = "MyChannel";

String description = "Description of my notifications";


int importance = NotificationManager.IMPORTANCE_DEFAULT;

NotificationChannel channel = new NotificationChannel("channel_id", name, importance);

channel.setDescription(description);

// Register the channel with the system

NotificationManager notificationManager = getSystemService(NotificationManager.class);

notificationManager.createNotificationChannel(channel);

 Best Practice: Always create a notification channel for apps targeting Android 8.0 and
above, as notifications will not be displayed without one.

3. Notification Layouts and Components

Android provides flexibility in how notifications are structured. The layout of a notification
should be simple, intuitive, and consistent with your app's theme and design language.

Basic Components of a Notification:

 Title and Text: Clear, concise titles and descriptive text to inform users.

 Icon: A small icon representing your app or the event. It should be recognizable and
simple.

 Priority/Importance: The priority level helps determine how prominently the


notification appears. Android supports several importance levels such as High,
Medium, Low, and Min.

o High Priority: Displays as a Heads-Up Notification on the screen.

o Low Priority: Appears in the notification tray and may be silently delivered.

 Actions: Include buttons for performing actions directly from the notification (e.g.,
Reply, Like, Delete). Keep the number of actions minimal to avoid clutter.

Example of adding actions:

java

Copy code

NotificationCompat.Action action = new NotificationCompat.Action.Builder(

R.drawable.ic_reply, "Reply", replyPendingIntent)

.build();

 Media Style: For media-related notifications (e.g., music playback), use the
MediaStyle to display playback controls (play, pause, skip).

java

Copy code

NotificationCompat.MediaStyle mediaStyle = new NotificationCompat.MediaStyle()

.setShowActionsInCompactView(0, 1, 2);
 Custom Layouts: Use RemoteViews for custom layouts when you want to display
complex or rich content. Custom layouts can contain images, additional text, or buttons
beyond the default styles.

4. Use Rich Content for Interactive Notifications

 Images: Use BigPictureStyle to display images in notifications. This is particularly


useful for promotions, social media posts, or event updates.

Example of BigPictureStyle:

java

Copy code

NotificationCompat.BigPictureStyle bigPictureStyle = new


NotificationCompat.BigPictureStyle()

.bigPicture(bitmap) // Bitmap for image

.setBigContentTitle("Title")

.setSummaryText("Summary");

 Expandable Content: Notifications can be expanded to show more content using


BigTextStyle, especially useful for showing longer text.

Example of BigTextStyle:

java

Copy code

NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()

.bigText("Here is some extended text for the notification...");

5. Manage Notification Behavior and Visibility

Timing and Frequency:

 Rate Limit Notifications: Avoid bombarding users with too many notifications at
once. Grouping notifications and limiting their frequency will improve user experience.

 Grouping Notifications: For similar notifications, such as ongoing updates or


messages, use Notification Grouping. This will combine multiple notifications into a
single expandable one.

Example of Grouping:

java

Copy code

Notification summaryNotification = new NotificationCompat.Builder(this, CHANNEL_ID)

.setContentTitle("New Messages")

.setContentText("You have 5 new messages.")


.setSmallIcon(R.drawable.ic_message)

.setGroup("message_group")

.setGroupSummary(true)

.build();

Visibility and Importance:

 Ensure notifications are visible when necessary but not overly intrusive. For example,
use low priority for less important notifications (e.g., updates from an app that is not
critical).

 Avoid Overuse of Sound and Vibration: Use sounds and vibrations sparingly.
Consider silent notifications or use custom sound profiles for different notification
types.

6. Notification Actions and Interaction

Provide useful actions that allow users to interact with notifications directly. This eliminates
the need to open the app and improves efficiency.

Examples of Action Buttons:

 Reply: For messaging apps, include a "Reply" button, allowing the user to respond
directly from the notification.

 Like or Thumbs Up: For social apps, enable quick actions such as "Like" or "Share"
buttons.

Example of Adding Action Button:

java

Copy code

NotificationCompat.Action action = new NotificationCompat.Action.Builder(

R.drawable.ic_reply, "Reply", replyPendingIntent)

.build();

Pending Intent:

Action buttons trigger PendingIntent, which allows your app to execute code (such as
opening an activity, starting a service, or sending data) when the user interacts with the
notification.

7. Do Not Overwhelm the User

Notifications should provide clear, relevant, and timely information. Overuse of notifications
can result in user fatigue and uninstallation of the app. Follow these practices:

 Use Quiet Time: If the user hasn’t interacted with the app in a while, avoid
overwhelming them with constant notifications.

 Opt-in for Notifications: Allow users to opt in or opt out of notifications in the app
settings (via notification channels or in-app settings).
8. User-Centric Design

Design notifications keeping the user experience in mind:

 Clear and Relevant Messaging: Notifications should convey essential information


succinctly.

 Contextual Design: Notifications should fit the context and purpose of the app. For
example, music apps should prioritize media controls, while productivity apps can focus
on reminders.

 Rich Media Support: If your app uses multimedia, leverage rich media content like
images, audio, or video for a more engaging experience.

 Consistency: Follow material design principles for consistency in design (e.g., spacing,
font sizes, button placements).

Conclusion

Designing effective notifications in Android requires understanding user needs, providing


useful interactions, and following Android’s best practices. By paying attention to notification
types, content, and user preferences, you can enhance the user experience while ensuring
that notifications are non-intrusive and effective.

Key Takeaways:

 Use Notification Channels for Android 8.0 and above.

 Create simple, interactive notifications with relevant actions.

 Use media styles, expandable content, and custom layouts for rich notifications.

 Prioritize user control over notification behavior (e.g., opt-in/opt-out options).

 Don't overwhelm users with excessive notifications; be mindful of timing and frequency.

By following these guidelines, you can create notifications that are functional, informative,
and user-friendly.

List and Explain the Notification Priorities.


Notification Priorities in Android
In Android, notification priorities determine how notifications are presented to users. They
help to manage the visibility and behavior of notifications based on their importance,
ensuring that important notifications get the user's attention while less critical ones remain
unobtrusive.

With the introduction of Notification Channels in Android 8.0 (API level 26), Android allows
developers to assign a priority level to notifications. These priorities control the urgency of a
notification and how it behaves in the system.
Notification Priority Levels
Here are the different priority levels in Android, including how they affect the notification
behavior:

1. HIGH (Importance Level: IMPORTANCE_HIGH)

 Purpose: High-priority notifications are meant to get the user's immediate attention.

 Behavior:

o Display as Heads-Up Notifications (notifications that briefly appear on top of


the screen, even if the app is not in the foreground).

o These notifications can make sound, vibrate, and visually interrupt the user.

o Typically used for urgent or important events (e.g., messages, alerts, incoming
calls, etc.).

Example Use Cases:

o Instant messaging apps (e.g., new message from a contact).

o Reminders for important tasks.

o Alerting the user of critical events, such as system errors or app crashes.

Implementation:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,


CHANNEL_ID)

.setContentTitle("Important Alert")

.setContentText("You have a new message.")

.setPriority(NotificationCompat.PRIORITY_HIGH)

.setDefaults(Notification.DEFAULT_ALL); // Sound, vibration, etc.

2. MEDIUM (Importance Level: IMPORTANCE_DEFAULT)

 Purpose: Medium-priority notifications are less urgent but still important for the user
to see. They do not demand immediate attention but should be visible.

 Behavior:

o These notifications appear in the notification shade but will not interrupt the user
with a Heads-Up Notification.

o Can use sound and vibration, but may be muted by Do Not Disturb mode.

o Suitable for non-urgent notifications that provide value to the user but are not
time-critical.

Example Use Cases:

o Notifications for new content (e.g., a social media post, a new email).

o System updates or maintenance notifications.


o Alerts that are not time-sensitive (e.g., a news app update).

Implementation:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,


CHANNEL_ID)

.setContentTitle("Update Available")

.setContentText("A new version of the app is available.")

.setPriority(NotificationCompat.PRIORITY_DEFAULT)

.setDefaults(Notification.DEFAULT_LIGHTS); // Light-only notification

3. LOW (Importance Level: IMPORTANCE_LOW)

 Purpose: Low-priority notifications are typically used for information that is not
immediately necessary or crucial.

 Behavior:

o These notifications appear in the notification shade, but they are silent, and they
do not make any sound or vibration.

o They are less intrusive and allow users to review them when they choose to.

o Suitable for background tasks or information that doesn’t need immediate


attention.

Example Use Cases:

o Informational updates (e.g., successful download notification).

o Non-urgent reminders (e.g., periodic news updates or event reminders).

o Quiet updates from services, such as battery optimization tips.

Implementation:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,


CHANNEL_ID)

.setContentTitle("Sync Complete")

.setContentText("Your data has been successfully synced.")

.setPriority(NotificationCompat.PRIORITY_LOW)

.setDefaults(Notification.DEFAULT_LIGHTS); // No sound or vibration

4. MIN (Importance Level: IMPORTANCE_MIN)

 Purpose: Min-priority notifications are used for notifications that are not critical and do
not need to be immediately visible to the user. These are generally background
notifications.

 Behavior:
o These notifications are typically only shown in the notification drawer and do not
appear as a heads-up or visually interrupt the user.

o They will be silent and will not use sound or vibration by default.

o They can be useful for background tasks like synchronizations or long-running


processes.

Example Use Cases:

o Background tasks or data syncs.

o Low-priority system status updates that don’t require immediate attention.

o Background services like GPS tracking or background music playback.

Implementation:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,


CHANNEL_ID)

.setContentTitle("Background Process")

.setContentText("Your task is running in the background.")

.setPriority(NotificationCompat.PRIORITY_MIN)

.setOngoing(true); // Prevents dismissal

Notification Priority Summary Table

Priority Behavior Use Cases Default Behavior


Level
High (Priority Heads-up notifications, Critical alerts Appears on top of
High) sound, vibration, urgent (messages, calls, screen, interrupts the
errors) user
Medium Appears in the New updates, general Light sound or visual,
(Priority notification shade, no notifications less intrusive
Default) interruption
Low (Priority Silent notifications, Background updates, Silent, no sound or
Low) appears in the shade non-urgent vibration
notifications
Min (Priority Silent, only in the Background tasks, Silent and unobtrusive,
Min) notification drawer system updates often non-dismissible

5. Choosing the Right Priority Level

When designing notifications, it’s important to choose the right priority based on the context
and urgency of the message:

 High Priority: Use when the notification requires immediate user action or attention,
such as messages, reminders, or alerts related to the user’s well-being.

 Medium Priority: Use for notifications that are important but do not need immediate
attention. These might be related to updates, new content, or reminders.
 Low Priority: Use for notifications that don’t require immediate attention, like
background tasks or routine updates that the user can check later.

 Min Priority: Use for background tasks or non-intrusive notifications that the user does
not need to see immediately.

Choosing the right priority helps ensure the notifications fit into the overall user experience
without being too disruptive or missing out on important alerts.

6. Considerations for User Experience

 Do Not Disturb (DND) Mode: Users can enable Do Not Disturb mode, which silences
notifications based on their priority level. High-priority notifications can override DND
settings, while low-priority notifications will be silenced.

 Frequency of Notifications: Even with high-priority notifications, excessive


notifications can annoy users. Use notification channels to allow users to fine-tune their
preferences and avoid overwhelming them.

 Consistency: Keep your notification behavior consistent across your app. For example,
use high-priority notifications only for critical events like messages or alarms, while
using lower priority for periodic updates.

Define Loader? Explain, how do you start and restart a loader?


What is a Loader?
Loader is a set of APIs, known as Loader APIs given by Android, to load data asynchronously
in activity/fragment.

What is the Use of Loader?

It can fetch data asynchronously without blocking the main thread and it manages it's own
lifecycle during onDestroy() and configuration changes.

How Do I Use it?

Loaders in Android is an abstract class implementation of Loader and two default classes,
which are provided by Android, I.E. AsyncTaskLoader, and cursor loaders.

There is only one Loader instance per activity/fragment and is created by Loader
managers. LoaderManager can manage multiple instances of Loaders.

There are three main parts to implement loader with Android:

1. LoaderManager: LoaderManager is used to initialize loaders in activity/fragment. Loaders


can be initialized mainly in onCreate () / onStart () , functions by using LoaderManager.
init(LOADER_ID,OPTION_ARGUMENT,CALLBACK_CLASS_REFERNCE) and
`LoaderManagereRestartLoader(LOADER_ID,OPTION_ARGUMENT,CLASSBACK_CLASS_REFERE
NCE)

The three arguments that will into init() and restartLoader() function are as follows:
 LOADER_ID: Uniq ID given to Loader, if we are initializing Loader, will check if the
Loader ID is present or not. It will call on the callbacks method accordingly, which I wil
explain later.

 OPTION_ARGUMENT: It is the argument given to Loader at the time of initialization.

 CALLBACK_CLASS_REFERENCE: Class that implements all it's callback function, which


Loader will return data.

2. LoaderManager.LoaderCallBacks:

It provide a set of three methods which Loader with call sequentially:

 OnCreateLoader(int,bundle): We will call on this method when we initialize Loader. In


can only be called when no Loader with LOADER_ID is already
present. onCreateLoader() will return the Loader object,
either CursorLoader, AyncTaskLoader or CustomImplementedLoader.

 OnLoadFinished(): Called after our data loading is finished. Basically we'll do all the user
interface binding and other things here.

 OnLoaderReset(): Every time our Loader gets reset (either activity/ Fragment get
destroyed), we have to clear all the refereces from current Loader in this callback.

3. Loader:

Loader is the abstract class, which serves as a base class for all the Loaders. There are two
implementation given by Android:

 AsyncTaskLoader: A Loader that provides AsyncTask to perform background operations.

 CusorLoader: A Loader implementation used to get data from content providers through
content resolvers.

How to Start and Restart a Loader in Android


In Android, Loaders are used to manage background operations and provide data to the UI,
especially when working with content providers or large datasets. They are part of the
Loader Framework, which allows asynchronous loading of data without blocking the UI
thread, helping keep the app responsive.

Loaders are primarily used for tasks such as loading data from a database, a network, or a
content provider. They handle lifecycle management automatically, which means they
survive configuration changes (like device rotation) and can handle data loading efficiently.

Below is a guide on how to start and restart a loader in Android.

1. Starting a Loader

To start a loader, you need to call the getLoaderManager().initLoader() method. This method
initializes a loader and starts loading data asynchronously.

The general steps to start a loader are:

1. Define a Loader: Create a subclass of AsyncTaskLoader or use existing loaders (like


CursorLoader for querying a content provider).
2. Call initLoader(): In the Activity or Fragment, call the initLoader() method, which will
either start a new loader or use an existing one if the loader with the given ID already
exists.

Example: Starting a Loader

Here’s an example of how to start a loader in an Activity or Fragment:

java

Copy code

public class MainActivity extends AppCompatActivity implements


LoaderManager.LoaderCallbacks<Cursor> {

private static final int LOADER_ID = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Start the loader

getLoaderManager().initLoader(LOADER_ID, null, this);

// Implementing the LoaderCallbacks interface methods

@Override

public Loader<Cursor> onCreateLoader(int id, Bundle args) {

if (id == LOADER_ID) {

// Returning a CursorLoader that queries a content provider or a database

return new CursorLoader(this,

YourContentProvider.CONTENT_URI,

null,

null,

null,

null);

return null;

}
@Override

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

// Handle the loaded data

@Override

public void onLoaderReset(Loader<Cursor> loader) {

// Reset any data related to the loader

In this example:

 The loader is started when initLoader() is called.

 The loader is associated with a LoaderCallbacks interface that provides methods for
creating and receiving data from the loader.

Key Methods for Loader Starting:

 initLoader(int id, Bundle args, LoaderCallbacks<D> callback): This method initializes a


new loader or reuses an existing one. It takes the loader ID, any additional arguments,
and the loader callback.

2. Restarting a Loader

You might want to restart a loader in cases where the data needs to be reloaded. For
example, if the data source changes or the user requests to reload the data, you can restart
the loader.

To restart a loader, you can either:

 Restart a Loader: This is achieved by calling getLoaderManager().restartLoader()


method. This stops and restarts the loader, allowing it to reload data.

Steps to Restart a Loader:

1. Call restartLoader(): This is similar to calling initLoader(), but it forces the loader to
be reset and reloaded from scratch.

Example: Restarting a Loader

Here’s an example of how to restart a loader in an Activity or Fragment:

public class MainActivity extends AppCompatActivity implements


LoaderManager.LoaderCallbacks<Cursor> {

private static final int LOADER_ID = 1;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Start the loader initially

getLoaderManager().initLoader(LOADER_ID, null, this);

// Method to restart the loader based on certain conditions

public void restartDataLoader() {

getLoaderManager().restartLoader(LOADER_ID, null, this);

@Override

public Loader<Cursor> onCreateLoader(int id, Bundle args) {

if (id == LOADER_ID) {

// Returning a CursorLoader to fetch data

return new CursorLoader(this,

YourContentProvider.CONTENT_URI,

null,

null,

null,

null);

return null;

@Override

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

// Handle the loaded data

}
@Override

public void onLoaderReset(Loader<Cursor> loader) {

// Reset any data related to the loader

In this example:

 The restartDataLoader() method is called to restart the loader. It calls


getLoaderManager().restartLoader() and reinitializes the loader.

 The loader ID remains the same, but the loader will be reset, causing it to re-query the
data source.

Key Methods for Restarting a Loader:

 restartLoader(int id, Bundle args, LoaderCallbacks<D> callback): This method restarts


an existing loader with the given ID, resetting its state and triggering a reload of data.

Important Considerations When Restarting a Loader

 Loader Lifecycle: When restarting a loader, it will go through the entire lifecycle of a
loader, including re-creating the loader and invoking the onLoadFinished() callback with
new data.

 Data Reset: When restarting the loader, any previous data held by the loader (e.g., a
cursor or dataset) is reset, and fresh data will be loaded.

 Efficiency: While restarting the loader can be useful in certain scenarios (e.g., user-
requested refresh or dynamic data changes), it should be done judiciously to avoid
unnecessary data loading and performance overhead.

3. Stopping a Loader

Although not directly related to starting or restarting a loader, it’s good to note that loaders
should also be stopped when they are no longer needed. This is done by calling:

java

Copy code

getLoaderManager().destroyLoader(LOADER_ID);

This ensures that any resources held by the loader (such as memory) are released when the
loader is no longer required.

Summary

 Starting a Loader: Use initLoader() to start a loader for the first time or when it's not
previously initialized.
 Restarting a Loader: Use restartLoader() to reset and reload the data from scratch.
This can be used when you need to refresh the data (e.g., after a data change or user
request).

 Stopping a Loader: Use destroyLoader() to clean up resources when the loader is no


longer needed.

These methods help manage background tasks efficiently, improve UI responsiveness, and
handle data loading in a manner that is consistent with the Android lifecycle.

Explain Image Views to display pictures in Android Mobile.


ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application
either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is
a general abstraction for anything that can be drawn in Android). ImageView class
or android.widget.ImageView inherits the android.view.View class which is the subclass
of Kotlin. AnyClass.Application of ImageView is also in applying tints to an image in order
to reuse a drawable resource and create overlays on background images. Moreover,
ImageView is also used to control the size and movement of an image.

Adding an ImageView to an Activity

Whenever ImageView is added to an activity, it means there is a requirement for an image


resource. Thus it is oblivious to provide an Image file to that ImageView class. It can be done
by adding an image file that is present in the Android Studio itself or we can add our own
image file. Android Studio owns a wide range of drawable resources which are very common
in the android application layout. The following are the steps to add a drawable resource to
the ImageView class. To enhance your image-handling skills and implement efficient image
loading techniques in Kotlin-based apps, the Android Mastery with Kotlin: Beginner to
Advanced course offers practical lessons on using ImageView effectively

Note: The steps are performed on Android Studio version 4.0

Open the activity_main.xml File in which the Image is to be Added

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Switch from the Code View to the Design View of the activity_main.xml File
For adding an image from Android Studio, Drag the ImageView widget to the
activity area of the application, a pop-up dialogue box will open choose from the
wide range of drawable resources and click “OK“.

For Adding an Image File other than Android Studio Drawable Resources:

Click on the “Resource Manager” tab on the leftmost panel and select the “Import
Drawables” option.
Select the path of the image file on your computer and click “OK“. After that set, the
“Qualifier type” and “value” of the image file according to your need and click “Next” then
“Import“.

Drag the ImageView class in the activity area, a pop-up dialogue box will appear which
contains your imported image file. Choose your image file and click “OK“, your image will be
added to the activity.
Note: After adding an image set its constraints layout both vertically and horizontally
otherwise it will show an error.

XML Attributes of ImageView

XML Attribute Description


android:id To uniquely identify an image view
android:src/ To add the file path of the inserted image
app:srcCompat
android:background To provide a background color to the inserted image
android:layout_width To set the width of the image
android:layout_height To set the height of the image
android:padding To add padding to the image from the left, right, top, or
bottom of the view
android:scaleType To re-size the image or to move it in order to fix its size
Step by Step Implementation
Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in
Android Studio. The code has been given in both Java and Kotlin Programming Language
for Android.

Step 2: Working with the activity_main.xml FileWorking with the activity_main.xml


File

Go to the activity_main.xml File and refer to the following code. Below is the code for
the activity_main.xml File.

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

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

<ImageView

android:id="@+id/GfG_full_logo"

android:layout_width="0dp"

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"

app:layout_constraintVertical_bias="0.078"

app:srcCompat="@drawable/full_logo" />

<ImageView

android:id="@+id/GfG_logo"

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/GfG_full_logo"

app:srcCompat="@drawable/logo" />

</androidx.constraintlayout.widget.ConstraintLayout>

Note: All the attributes of the ImageView which are starting with app:layout_constraint are
the vertical and horizontal constraints to fix the image position in the activity. This is very
necessary to add the constraint to the ImageView otherwise, all the images will take the
position (0, 0) of the activity layout.

Step 4: Working with the MainActivity File

Go to the MainActivity file and refer to the following code. Below is the code for
the MainActivity file. Since in the activity, only 2 images have been added and nothing else
is being done like touching a button, etc. So, the MainActivity file will simply look like the
below code i.e. no change.

JavaKotlin

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}
Output:

Explain Activity Launch modes using attributes and intent


flags.
Launch mode is an instruction for Android OS which specifies how the activity should be
launched. It instructs how any new activity should be associated with the current task. Before
moving further you first need to understand about very important topics-

1. Tasks

2. Back Stack

Tasks

A task is a collection of activities that users interact with when performing a certain job. In
general an application contains number of activities. Normally when user launch an
application a new task will be created and the first activity instance is called root of the task.

When user launches an app from home icon, it navigates through different screens so
different activities placed on the top of one another. This collection of activities is known as
tasks.

Back Stack

Activities are arranged with the order in which each activity is opened. This maintained stack
called Back Stack. When you start a new activity using startActivity(), it “pushes” a new
activity onto your task, and put the previous Activity in the back stack.

Once you press back button then “pops” the top most activity and remove it from the back
stack and taking you back to the previous activity.

Figure- Back Stack


Above figure explains representation of how each new activity in a task adds an item to the
back stack. When the user presses the Back button, the current activity is destroyed and the
previous activity resumes. For more details you can also refer .

There are four launch modes for activity. They are:

1. standard

2. singleTop

3. singleTask

4. singleInstance

In the AndroidManifest you can use “launchMode” attribute inside the <activity> element to
declare the activity’s launch mode like-

<activity android:launchMode = [“standard” | “singleTop” | “singleTask” |


“singleInstance”] ../>

Now let’s look at the differences between launch modes.

1. standard

This is the default launch mode of an activity (If not specified). It creates a new instance of an
activity in the task from which it was started. Multiple instances of the activity can be created
and multiple instances can be added to the same or different tasks. In other words you can
create the same activity multiple times in the same task as well as in different tasks.

<activity android:launchMode=”standard” />

Example:

Suppose you have A, B, C and D activities and your activity B has “launch mode = standard”.
Now you again launching activity B –

State of Activity Stack before launch B

A -> B -> C -> D

State of Activity Stack after launch B

A -> B -> C -> D -> B

2. singleTop

In this launch mode if an instance of activity already exists at the top of the current task, a
new instance will not be created and Android system will route the intent information through
onNewIntent(). If an instance is not present on top of task then new instance will be created.

Using this launch mode you can create multiple instance of the same activity in the same
task or in different tasks only if the same instance does not already exist at the top of stack.

<activity android:launchMode=”singleTop” />

Example:

Case 1:

Suppose you have A, B and C activities and your activity D has “launch mode = singleTop”.
Now you launching activity D -

State of Activity Stack before launch D


A -> B -> C

State of Activity Stack after launch D activity

A -> B -> C -> D (Here D launch as usual)

Case 2:

Suppose you have A, B, C and D activities and your activity D has “launch mode = singleTop”.
Now you again launching activity D -

State of Activity Stack before launch D

A -> B -> C -> D

State of Activity Stack after launch D activity

A -> B -> C -> D (Here old instance gets called and intent data route through onNewIntent()
callback)

3. singleTask

In this launch mode a new task will always be created and a new instance will be pushed to
the task as the root one. If an instance of activity exists on the separate task, a new instance
will not be created and Android system routes the intent information through onNewIntent()
method. At a time only one instance of activity will exist.

<activity android:launchMode=”singleTask” />

Example:

Case 1:

Suppose you have A, B and C activities and your activity D has “launch mode = singleTask”.
Now you launching activity D -

State of Activity Stack before launch D

A -> B -> C

State of Activity Stack after launch D activity

A -> B -> C -> D (Here D launch as usual)

Case 2:

Suppose you have A, B, C and D activities and your activity B has “launch mode =
singleTask”. Now you again launching activity B-

State of Activity Stack before launch D

A -> B -> C -> D

State of Activity Stack after launch B activity

A -> B (Here old instance gets called and intent data route through onNewIntent() callback)

Also notice that C and D activities get destroyed here.

4. singleInstance

This is very special launch mode and only used in the applications that has only one activity.
It is similar to singleTask except that no other activities will be created in the same task. Any
other activity started from here will create in a new task.
<activity android:launchMode=”singleInstance” />

Example:

Case 1:

Suppose you have A, B and C activities and your activity D has “launch mode =
singleInstance”. Now you launching activity D -

State of Activity Stack before launch D

A -> B -> C

State of Activity Stack after launch D activity

Task1 — A -> B -> C

Task2 — D (here D will be in different task)

Now if you continue this and start E and D then Stack will look like-

Task1 — A -> B -> C -> E

Task2 — D

Case 2:

Suppose you have A, B, C activities in one task and activity D is in another task with “launch
mode = singleInstance”. Now you again launching activity D-

State of Activity Stack before launch D

Task1 — A -> B -> C

Task2 — D

State of Activity Stack after launch B activity

Task1 — A -> B -> C

Task2 — D (Here old instance gets called and intent data route through onNewIntent()
callback)

Intent Flags

Android also provides Activity flags by which you can change the default behavior of Activity
association with Tasks while starting it via startActivity() method. These flags values can be
pass through Intent extra data.

FLAG_ACTIVITY_NEW_TASK

This flag works similar to “launchMode = singleTask”.

FLAG_ACTIVITY_CLEAR_TASK

This flag will cause any existing task that would be associated with the activity to be cleared
before the activity is started. The activity becomes the new root of an otherwise empty task,
and any old activities are finished.

FLAG_ACTIVITY_SINGLE_TOP

This flag works similar to “launchMode = singleTop”.

FLAG_ACTIVITY_CLEAR_TOP
If set, and the activity being launched is already running in the current task, then instead of
launching a new instance of that activity, all of the other activities on top of it will be closed
and this Intent will be delivered to the (now on top) old activity as a new Intent.

Describe these App components, Intent filters, Content


Sharing and Threads.
Components of an Android Application
There are some necessary building blocks that an Android application consists of. These
loosely coupled components are bound by the application manifest file which contains the
description of each component and how they interact. The manifest file also contains the
app’s metadata, its hardware configuration, and platform requirements, external libraries,
and required permissions. There are the following main components of an android app:

1. Activities

Activities are said to be the presentation layer of our applications. The UI of our application is
built around one or more extensions of the Activity class. By using Fragments and Views,
activities set the layout and display the output and also respond to the user’s actions. An
activity is implemented as a subclass of class Activity.

JavaKotlin

public class MainActivity extends Activity {

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

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

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

2. Services

Services are like invisible workers of our app. These components run at the backend,
updating your data sources and Activities, triggering Notification, and also broadcast Intents.
They also perform some tasks when applications are not active. A service can be used as a
subclass of class Service:

JavaKotlin

public class ServiceName extends Service {

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

3. Content Providers
It is used to manage and persist the application data also typically interacts with the SQL
database. They are also responsible for sharing the data beyond the application boundaries.
The Content Providers of a particular application can be configured to allow access from other
applications, and the Content Providers exposed by other applications can also be
configured.
A content provider should be a sub-class of the class ContentProvider.

JavaKotlin

public class contentProviderName extends ContentProvider {

public void onCreate(){}

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

4. Broadcast Receivers

They are known to be intent listeners as they enable your application to listen to the Intents
that satisfy the matching criteria specified by us. Broadcast Receivers make our application
react to any received Intent thereby making them perfect for creating event-driven
applications.

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

5. Intents

It is a powerful inter-application message-passing framework. They are extensively used


throughout Android. Intents can be used to start and stop Activities and Services, to
broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or
to request action be performed on a particular piece of data.

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

6. Widgets

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

7. Notifications

Notifications are the application alerts that are used to draw the user’s attention to some
particular app event without stealing focus or interrupting the current activity of the user.
They are generally used to grab user’s attention when the application is not visible or active,
particularly from within a Service or Broadcast Receiver. Examples: E-mail popups, Messenger
popups, etc.

Intent Filter
 Implicit intent uses the intent filter to serve the user request.

 The intent filter specifies the types of intents that an activity, service, or broadcast
receiver can respond.

 Intent filters are declared in the Android manifest file.

 Intent filter must contain <action>


Example:

 XML

<intent-filter

android:icon="drawable resource"

android:label="string resource"

android:priority="integer" >

...

</intent-filter>

Most of the intent filter are describe by its

1. <action>,

2. <category> and

3. <data>.

1. <action>

Syntax:

<action android:name="string" />

Adds an action to an intent filter. An <intent-filter> element must contain one or


more <action> elements. If there are no <action> elements in an intent filter, the filter
doesn’t accept any Intent objects.

Examples of common action:

 ACTION_VIEW: Use this action in intent with startActivity() when you have some
information that activity can show to the user like showing an image in a gallery app or
an address to view in a map app

 ACTION_SEND: You should use this in intent with startActivity() when you have some
data that the user can share through another app, such as an email app or social
sharing app.

2. <category>

Syntax:

<category android:name="string" />

Adds a category name to an intent filter. A string containing additional information about the
kind of component that should handle the intent.

Example of common categories:

 CATEGORY_BROWSABLE: The target activity allows itself to be started by a web


browser to display data referenced by a link.

3. <data>
Syntax:

<data android:scheme="string"

android:host="string"

android:port="string"

android:path="string"

android:pathPattern="string"

android:pathPrefix="string"

android:mimeType="string" />

Adds a data specification to an intent filter. The specification can be just a data type, just a
URI, or both a data type and a URI.

Content Sharing in Android


Content sharing in Android refers to the ability of an app to share data with other apps or to
allow other apps to share data with the app. This is a common requirement in mobile
applications, where users may need to share information such as images, text, links, or files
across different apps, without exposing their data directly to other apps.

Android provides several mechanisms for content sharing, including Intents and Content
Providers. These allow apps to securely exchange data between themselves or with the
user.

Key Concepts for Content Sharing

1. Intents:

o Intents are Android’s primary mechanism for communication between


components, such as activities, services, and broadcast receivers.

o They can be used to share data between apps, such as sending a message,
sharing an image, or opening a website.

o Implicit Intents are commonly used for content sharing, where the system
chooses the appropriate app based on the content type and the available
applications installed on the device.

2. Content Providers:

o A Content Provider is a structured interface through which an app can share


data with other apps.

o Content providers allow apps to share data (e.g., contacts, images, or files) by
exposing it through a standardized API.

o Content providers can be used for both reading and writing data to an app's
private database or for sharing data with other apps securely.

Types of Content Sharing Mechanisms


1. Sharing Data with Intents

o Intents can be used for sharing different types of content between apps. For
example, you can send text, images, or files using implicit intents to target
specific apps like messaging, email, or social media apps.

Examples of Content Sharing via Intent:

o Sharing text: You can share a simple text message with other apps like
WhatsApp, SMS, or email.

o Sharing images: You can share an image by using the Intent.ACTION_SEND


action and specifying the image URI.

o Sharing URLs: You can send a URL to a browser or a social media app.

Example of Sharing Text via Intent:

Intent shareIntent = new Intent();

shareIntent.setAction(Intent.ACTION_SEND);

shareIntent.putExtra(Intent.EXTRA_TEXT, "Check out this cool app!");

shareIntent.setType("text/plain");

startActivity(Intent.createChooser(shareIntent, "Share via"));

This creates an implicit intent that will allow the user to choose an app (e.g., WhatsApp,
Email, etc.) to send the text to.

2. Sharing Files

o You can share files using intents. Files can be shared via Content URIs to avoid
sharing raw file paths, which may not be accessible by all apps. Android provides
the ContentProvider interface for this purpose.

Example of Sharing an Image File:

Uri imageUri = Uri.parse("content://path_to_image");

Intent shareIntent = new Intent(Intent.ACTION_SEND);

shareIntent.setType("image/*");

shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);

startActivity(Intent.createChooser(shareIntent, "Share Image"));

3. Using Content Providers for Data Sharing

o A Content Provider is an abstraction layer for data storage. It allows an app to


expose its data to other apps in a secure manner. Content providers can be used
to share data such as contacts, media files, and app-specific databases.

o Examples: Android provides default content providers for handling common data
types like contacts (ContactsProvider), media (e.g., MediaStore for images and
audio), or calendar events.

Example of Sharing Contacts Using Content Provider:

Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;


Cursor cursor = getContentResolver().query(contactsUri, null, null, null, null);

if (cursor != null) {

while (cursor.moveToNext()) {

String contactName =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

// Process each contact name

cursor.close();

The ContentResolver allows apps to interact with other apps' content providers securely. For
example, you can query another app's data (like contacts or calendar events) or insert data
into a shared content provider.

4. Sharing Data with ShareActionProvider

o Android provides a ShareActionProvider widget for creating share menus in your


app, making it easier for users to share content from within your app.

o It integrates with the ActionBar or Toolbar to present a sharing option for users
to send data via intents.

Example Using ShareActionProvider:

ShareActionProvider mShareActionProvider;

Intent shareIntent = new Intent(Intent.ACTION_SEND);

shareIntent.setType("text/plain");

shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello, World!");

mShareActionProvider.setShareIntent(shareIntent);

The ShareActionProvider provides an easy way to implement sharing functionality without


needing to manually create and configure an intent each time.

What are Threads in Android with Example?


In Android, a thread is a unit of execution that can run independently of the main UI thread.
Threads can be used to perform long-running tasks without blocking the UI, but they are still
part of the same process, not separate background processes.

Threads in Android are typically used to offload tasks from the main thread to avoid freezing
the UI. However, they are part of the same application process and share the same memory
space. In Java and Kotlin, the Thread class and coroutines can be used to create and manage
threads.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

JavaKotlin

Thread thread = new Thread(new Runnable() {

@Override public void run() {

// code to run in background thread

});

thread.start();

Note: It’s recommended to use coroutines in Kotlin instead of Thread, as they are more
lightweight and easier to manage.

Code Snippet of a function that uses coroutines to perform a network request in the
background, and updates the UI with the result:

fun doNetworkRequest() = GlobalScope.launch(Dispatchers.Main) {


val result = withContext(Dispatchers.IO) {
// perform network request
}
// update UI with the result
}

There are different types of threads in Android, each with its own use cases:

 The main thread, also known as the UI thread, is responsible for handling all UI updates
and user interactions. Any code that updates the UI or interacts with the user should be
run on the main thread.

 Worker threads are used for background tasks that should not block the main thread,
such as network requests, database operations, and image processing.

 AsyncTask is a helper class that allows you to perform background tasks and update
the UI from the same thread. However, it has some limitations and it’s recommended to
use coroutines or other libraries for more complex tasks.

 Services are used for tasks that should continue running even when the app is not
visible, such as playing music or downloading files.

 In addition to the above, there are other types of threading mechanisms available in
android such as IntentService, JobIntentService, Service, JobScheduler, and
AlarmManager.

It’s important to choose the right threading mechanism for your task to ensure optimal
performance and avoid threading issues. It’s also important to test your app thoroughly on
different devices and configurations to ensure that it behaves correctly and does not crash
due to threading issues.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio


To create a new project in Android Studio please refer to How to Create/Start a New
Project in Android Studio.

The code for that has been given in both Java and Kotlin Programming Language for
Android.

Step 2: 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.

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

<LinearLayout

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:orientation="vertical">

<!-- Display the result text -->

<TextView

android:id="@+id/result_text_view"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Result will appear here"

android:textSize="25sp" />

<!-- Start button -->

<Button

android:id="@+id/start_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Start" />

</LinearLayout>

Step 3: Working with the MainActivity & ExampleIntentService File


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

import android.os.AsyncTask;

import android.os.Bundle;

import android.widget.Button;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView resultTextView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Get reference to start button and result text view

Button startButton = findViewById(R.id.start_button);

resultTextView = findViewById(R.id.result_text_view);

// Set an OnClickListener for the start button

startButton.setOnClickListener(view -> new BackgroundTask().execute());

// BackgroundTask inner class to perform the background task

private class BackgroundTask extends AsyncTask<Void, Void, String> {

@Override

protected String doInBackground(Void... voids) {

// Perform background task

try {

Thread.sleep(5000);

} catch (InterruptedException e) {
e.printStackTrace();

return "Task Completed";

@Override

protected void onPostExecute(String result) {

// Update UI with the results

resultTextView.setText(result);

Output:

Describe these App components - Intent, Activity and


Threads.
Covered above

What is meant by UI architecture explain?

What is intent? How many different intent types are there?


Covered above
How data is accessing and building a content provider? What
would be the result if not have network connectivity?
Accessing Data with Content Providers in Android
A Content Provider in Android is a key component for accessing and sharing data between
applications. It acts as an intermediary between an app’s data and other apps or the system.
It provides a standardized interface for querying, inserting, updating, and deleting data. A
content provider ensures that apps can share data securely, without exposing direct access
to their data sources, such as databases or file systems.

How Data is Accessed Using Content Providers

1. Content URI:

o Each Content Provider has a Content URI that specifies the location of the
data. The URI usually follows the format content://<authority>/<path>, where
<authority> is a unique identifier of the provider and <path> specifies the
specific dataset.

Example:

o content://contacts/phones might represent the list of phone contacts on the


device.

2. Content Resolver:

o The ContentResolver class is used to interact with Content Providers. It


serves as an API to perform CRUD (Create, Read, Update, Delete) operations on
the data exposed by a Content Provider.

3. Accessing Data (CRUD operations):

o Query: Retrieves data from the Content Provider.

o Insert: Adds data to the Content Provider.

o Update: Modifies existing data in the Content Provider.

o Delete: Removes data from the Content Provider.

Below are examples for accessing data using a Content Provider.

Example: Accessing Data (Querying Contacts)

To access contacts from the system's Contacts Provider, you can use the ContentResolver
to query the ContactsContract content provider.

java

Copy code

// Define the URI for the Contacts content provider

Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

// Use ContentResolver to query data

Cursor cursor = getContentResolver().query(

contactsUri, // URI
null, // Projection (null means all columns)

null, // Selection

null, // Selection arguments

null); // Sort order

// Iterate through the cursor and access the contacts

if (cursor != null) {

while (cursor.moveToNext()) {

String contactName =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

System.out.println("Contact Name: " + contactName);

cursor.close();

 The getContentResolver() method provides access to the ContentResolver.

 The query() method is used to perform a query on the content provider. It returns a
Cursor object which contains the result set.

 You can iterate through the Cursor and extract data using column indexes (e.g.,
ContactsContract.Contacts.DISPLAY_NAME).

Example: Inserting Data (Adding a Contact)

You can use the ContentResolver to insert new data into a content provider.

java

Copy code

ContentValues values = new ContentValues();

values.put(ContactsContract.Contacts.DISPLAY_NAME, "John Doe");

// Insert the new contact into the contacts content provider

Uri uri = getContentResolver().insert(ContactsContract.Contacts.CONTENT_URI, values);

 ContentValues is used to store key-value pairs that represent the data to be inserted.

 The insert() method returns the URI of the newly inserted data.

Building a Content Provider

Building a Content Provider involves creating a class that extends ContentProvider and
implementing its methods to handle data operations. Below are the steps involved in building
a Content Provider:
1. Create a Content Provider Class: The class must extend ContentProvider and
override essential methods such as onCreate(), query(), insert(), update(), and delete().

2. Define a URI: A URI is used to uniquely identify the content provider. It is used by
clients (other apps) to access the data.

3. Declare the Content Provider in the Manifest: The ContentProvider must be


declared in the app’s AndroidManifest.xml file.

4. Handle CRUD Operations: Implement logic to query, insert, update, and delete data.
This typically involves interacting with a database or some other data storage
mechanism.

Example: Basic Content Provider

public class MyContentProvider extends ContentProvider {

private static final String AUTHORITY = "com.example.myapp.provider";

private static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/items");

@Override

public boolean onCreate() {

// Initialize the data source (e.g., a SQLite database)

return true;

@Override

public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {

// Handle querying the database

SQLiteDatabase db = dbHelper.getReadableDatabase();

return db.query("items", projection, selection, selectionArgs, null, null, sortOrder);

@Override

public Uri insert(Uri uri, ContentValues values) {

// Handle inserting data into the database

SQLiteDatabase db = dbHelper.getWritableDatabase();

long id = db.insert("items", null, values);

return ContentUris.withAppendedId(CONTENT_URI, id);

}
@Override

public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

// Handle updating data in the database

SQLiteDatabase db = dbHelper.getWritableDatabase();

return db.update("items", values, selection, selectionArgs);

@Override

public int delete(Uri uri, String selection, String[] selectionArgs) {

// Handle deleting data from the database

SQLiteDatabase db = dbHelper.getWritableDatabase();

return db.delete("items", selection, selectionArgs);

@Override

public String getType(Uri uri) {

// Return MIME type based on URI (for example,


vnd.android.cursor.dir/vnd.com.example.myapp.items)

return "vnd.android.cursor.dir/vnd.com.example.myapp.items";

 onCreate(): Initializes resources such as databases or files.

 query(): Executes a query to retrieve data.

 insert(): Inserts data into the content provider.

 update(): Updates existing data.

 delete(): Deletes data.

 getType(): Returns the MIME type of the data.

What Happens if There is No Network Connectivity?


When dealing with content providers that rely on network connectivity (e.g., fetching data
from a remote server), it is important to handle the case where there is no network
connectivity.

Possible Results if No Network Connectivity:

1. Data Fetch Failure:


o If the content provider is designed to fetch data over the network (e.g., using a
ContentProvider that interacts with an API), and there is no network connection,
the operation will fail. This could result in an exception, like a
NetworkOnMainThreadException, or a failure to return data.

2. Empty Results:

o In cases where data cannot be fetched due to lack of connectivity, the content
provider might return empty data, or a null or empty Cursor for a query
operation, indicating that no data was available from the network.

3. Error Handling:

o Graceful Degradation: A good practice is to handle errors and show a


meaningful message to the user, such as "No internet connection" or "Unable to
fetch data."

o Fallback: If the content provider has a local cache (e.g., a database), it can fall
back to returning the cached data if the network is unavailable.

Handling Network Connectivity in Content Providers:

You can check for network availability before making a network request inside the
ContentProvider.

public boolean isNetworkAvailable() {

ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = cm.getActiveNetworkInfo();

return networkInfo != null && networkInfo.isConnected();

You could use this method to ensure that network requests are only made when the network
is available, or you could implement an offline caching mechanism that allows the app to
continue functioning when the network is not available.

Develop an App having some animations and graphics.


Animation in Android with Example
Animation is the process of adding a motion effect to any view, image, or text. With the help
of an animation, you can add motion or can change the shape of a specific view. Animation in
Android is generally used to give your UI a rich look and feel. The animations are basically of
three types as follows:

1. Property Animation

2. View Animation

3. Drawable Animation

Animations add a dynamic touch to Android apps, improving user experience. If you’re
looking to master animations and bring your Kotlin-based apps to life with advanced
techniques, the Android Mastery with Kotlin: Beginner to Advanced course offers in-depth
tutorials on creating engaging animations in Android

1. Property Animation

Property Animation is one of the robust frameworks which allows animation almost
everything. This is one of the powerful and flexible animations which was introduced in
Android 3.0. Property animation can be used to add any animation in
the CheckBox, RadioButtons, and widgets other than any view.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

2. View Animation

View Animation can be used to add animation to a specific view to perform tweened
animation on views. Tweened animation calculates animation information such as size,
rotation, start point, and endpoint. These animations are slower and less flexible. An example
of View animation can be used if we want to expand a specific layout in that place we can use
View Animation. The example of View Animation can be seen in Expandable RecyclerView.
3. Drawable Animation

Drawable Animation is used if you want to animate one image over another. The simple way
to understand is to animate drawable is to load the series of drawable one after another to
create an animation. A simple example of drawable animation can be seen in many apps
Splash screen on apps logo animation.

Important Methods of Animation

Methods Description
startAnimation() This method will start the animation.
clearAnimation() This method will clear the animation running on a
specific view.
Example of Implementation Android Animation

Now we will see the Simple Example to add animations to ImageView. Note that we are going
to implement this project using the Java language.

Step 1: Create a New Project

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

Step 2: Working with the strings.xml file

Strings.xml can be found from the app > res > values > strings.xml.
Below is the snippet for the strings.xml file.

<resources>

<string name="app_name">GFG App</string>

<string name="blink">BLINK</string>

<string name="clockwise">ROTATE</string>

<string name="fade">FADE</string>

<string name="move">MOVE</string>

<string name="slide">SLIDE</string>

<string name="zoom">ZOOM</string>

<string name="stop_animation">STOP ANIMATION</string>

<string name="course_rating">Course Rating</string>

<string name="course_name">Course Name</string>

</resources>

Step 3: Working with the activity_main.xml file

Create ImageView in the activity_main.xml along with buttons that will add animation to
the view. Navigate to the app > res > layout > activity_main.xml.

Below is the code for the activity_main.xml file.

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

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<ImageView

android:id="@+id/imageview"

android:layout_width="200dp"

android:layout_height="200dp"

android:layout_centerHorizontal="true"

android:layout_marginTop="40dp"

android:contentDescription="@string/app_name"

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

<LinearLayout

android:id="@+id/linear1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/imageview"

android:layout_marginTop="30dp"

android:orientation="horizontal"

android:weightSum="3">

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

<Button

android:id="@+id/BTNblink"

style="@style/TextAppearance.AppCompat.Widget.Button"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_weight="1"

android:padding="3dp"

android:text="@string/blink"
android:textColor="@color/white" />

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

<Button

android:id="@+id/BTNrotate"

style="@style/TextAppearance.AppCompat.Widget.Button"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_weight="1"

android:padding="3dp"

android:text="@string/clockwise"

android:textColor="@color/white" />

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

<Button

android:id="@+id/BTNfade"

style="@style/TextAppearance.AppCompat.Widget.Button"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_weight="1"

android:padding="3dp"

android:text="@string/fade"

android:textColor="@color/white" />

</LinearLayout>

<LinearLayout

android:id="@+id/linear2"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/linear1"

android:layout_marginTop="30dp"

android:orientation="horizontal"
android:weightSum="3">

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

<Button

android:id="@+id/BTNmove"

style="@style/TextAppearance.AppCompat.Widget.Button"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_weight="1"

android:padding="3dp"

android:text="@string/move"

android:textColor="@color/white" />

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

<Button

android:id="@+id/BTNslide"

style="@style/TextAppearance.AppCompat.Widget.Button"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_weight="1"

android:padding="3dp"

android:text="@string/slide"

android:textColor="@color/white" />

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

<Button

android:id="@+id/BTNzoom"

style="@style/TextAppearance.AppCompat.Widget.Button"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:layout_weight="1"
android:padding="3dp"

android:text="@string/zoom"

android:textColor="@color/white" />

</LinearLayout>

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

<Button

android:id="@+id/BTNstop"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/linear2"

android:layout_marginLeft="30dp"

android:layout_marginTop="30dp"

android:layout_marginRight="30dp"

android:text="@string/stop_animation" />

</RelativeLayout>

Step 4: Create 6 different types of animation for ImageView

To create new animations we have to create a new directory for storing all our animations.
Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your
directory as “anim”. Inside this directory, we will create our animations. For creating a new
anim right click on the anim directory >> Animation Resource file and give the name to your
file. Below is the code snippet for 6 different animations.

1. Blink Animation

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

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

<alpha android:fromAlpha="0.0"

android:toAlpha="1.0"

android:interpolator="@android:anim/accelerate_interpolator"

android:duration="500"

android:repeatMode="reverse"

android:repeatCount="infinite"/>

</set>
2. Fade Animation

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

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

android:interpolator="@android:anim/accelerate_interpolator">

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

<alpha

android:duration="1000"

android:fromAlpha="0"

android:toAlpha="1" />

<alpha

android:duration="1000"

android:fromAlpha="1"

android:startOffset="2000"

android:toAlpha="0" />

</set>

3. Move Animation

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

<set

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

android:interpolator="@android:anim/linear_interpolator"

android:fillAfter="true">

<translate

android:fromXDelta="0%p"

android:toXDelta="75%p"

android:duration="700" />

</set>

4. Rotate Animation
<?xml version="1.0" encoding="utf-8"?>

<set

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

<rotate

android:duration="6000"

android:fromDegrees="0"

android:pivotX="50%"

android:pivotY="50%"

android:toDegrees="360" />

<rotate

android:duration="6000"

android:fromDegrees="360"

android:pivotX="50%"

android:pivotY="50%"

android:startOffset="5000"

android:toDegrees="0" />

</set>

5. Slide Animation

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

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

android:fillAfter="true" >

<scale

android:duration="500"

android:fromXScale="1.0"

android:fromYScale="1.0"

android:interpolator="@android:anim/linear_interpolator"

android:toXScale="1.0"

android:toYScale="0.0" />

</set>

6. Zoom Animation
<?xml version="1.0" encoding="utf-8"?>

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

android:fillAfter="true" >

<scale

android:interpolator="@android:anim/linear_interpolator"

android:duration = "1000"

android:fromXScal = "1"

android:fromYScale = "1"

android:pivotX = "50%"

android:pivotY = "50%"

android:toXScale = "2"

android:toYScale = "2"/>

</set>

Step 5: Working with the MainActivity.java file

Add animation to the ImageView by clicking a specific Button. Navigate to the app > java >
your apps package name >> MainActivity.java.

Below is the implementation of MainActivity file:

MainActivity.javaMainActivity.kt

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.view.animation.Animation;

import android.view.animation.AnimationUtils;

import android.widget.Button;

import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {

// Declare ImageView and Buttons

ImageView imageView;

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

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize ImageView and Buttons using their IDs

imageView = findViewById(R.id.imageview);

blinkBTN = findViewById(R.id.BTNblink);

rotateBTN = findViewById(R.id.BTNrotate);

fadeBTN = findViewById(R.id.BTNfade);

moveBTN = findViewById(R.id.BTNmove);

slideBTN = findViewById(R.id.BTNslide);

zoomBTN = findViewById(R.id.BTNzoom);

stopBTN = findViewById(R.id.BTNstop);

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

blinkBTN.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Load blink animation and start it on the ImageView

Animation animation = AnimationUtils.loadAnimation(getApplicationContext()

, R.anim.blink_animation);

imageView.startAnimation(animation);

});

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


rotateBTN.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Load rotate animation and start it on the ImageView

Animation animation = AnimationUtils.loadAnimation(getApplicationContext()

, R.anim.rotate_animation);

imageView.startAnimation(animation);

});

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

fadeBTN.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Load fade animation and start it on the ImageView

Animation animation = AnimationUtils.loadAnimation(getApplicationContext()

, R.anim.fade_animation);

imageView.startAnimation(animation);

});

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

moveBTN.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Load move animation and start it on the ImageView

Animation animation = AnimationUtils.loadAnimation(getApplicationContext()

, R.anim.move_animation);

imageView.startAnimation(animation);

});

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

slideBTN.setOnClickListener(new View.OnClickListener() {
@Override

public void onClick(View v) {

// Load slide animation and start it on the ImageView

Animation animation = AnimationUtils.loadAnimation(getApplicationContext()

, R.anim.slide_animation);

imageView.startAnimation(animation);

});

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

zoomBTN.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Load zoom animation and start it on the ImageView

Animation animation = AnimationUtils.loadAnimation(getApplicationContext()

, R.anim.zoom_animation);

imageView.startAnimation(animation);

});

// Set up click listener for stop button to clear any ongoing animation

stopBTN.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Clear the animation on the ImageView

imageView.clearAnimation();

});

Note: Drawables and strings can be found in the drawable folder and strings.xml file.
Drawables can be found from the app > res > drawable.

Output:
Discuss Wireless Communications in Modern Mobile
Technologies?
Wireless Communications in Modern Mobile Technologies
Wireless communication is a cornerstone of modern mobile technologies, enabling the
exchange of data between devices without the need for physical connections. Over the past
few decades, mobile wireless communication has evolved significantly, supporting higher
data speeds, lower latency, and greater connectivity. Today, wireless communications are
central to everyday activities, from mobile phone usage and internet access to IoT devices
and connected services. Below is a discussion on the various wireless communication
technologies in modern mobile systems.

1. Generations of Wireless Communication (Mobile Networks)


Mobile communication systems have evolved through several generations, each improving
upon the previous one to offer faster speeds, enhanced capacity, and better efficiency.

1.1. 2G (Second Generation)

 Technology: Primarily based on GSM (Global System for Mobile


Communications).

 Key Features:

o Digital transmission of voice data.

o SMS (Short Message Service) and basic mobile data.

o The introduction of the concept of mobile broadband.

 Speed: Up to 64 kbps.

1.2. 3G (Third Generation)

 Technology: Primarily based on UMTS (Universal Mobile Telecommunications


System) and CDMA (Code Division Multiple Access).

 Key Features:

o Introduction of mobile internet and video calls.

o More efficient use of bandwidth for better data transmission.

o Enhanced voice quality and better network capacity.

 Speed: Up to 2 Mbps (higher for HSPA+).

1.3. 4G (Fourth Generation)

 Technology: LTE (Long-Term Evolution) and WiMAX (Worldwide Interoperability


for Microwave Access).

 Key Features:

o High-speed internet with support for HD video streaming and mobile gaming.

o Improved data rates, reduced latency, and better efficiency compared to previous
generations.
o Wide adoption of smartphones and mobile applications.

 Speed: Up to 1 Gbps (in ideal conditions).

 Latency: Around 30-50 ms.

1.4. 5G (Fifth Generation)

 Technology: NR (New Radio) and 5G NR (5G New Radio), utilizing millimeter-wave


bands, sub-6 GHz, and other spectrum bands.

 Key Features:

o Ultra-high-speed data transmission, with low latency and massive


connectivity.

o Improved coverage and capacity.

o Network slicing, allowing the creation of virtual networks optimized for specific
uses (e.g., smart cities, IoT, autonomous vehicles).

o Massive IoT connectivity: Supports a wide array of IoT devices with ultra-low
power consumption.

 Speed: Up to 10 Gbps or more.

 Latency: As low as 1 ms (critical for applications like autonomous driving).

 Use Cases: AR/VR, smart cities, autonomous vehicles, real-time remote healthcare.

1.5. Future - 6G and Beyond

 Technology: Expected to leverage terahertz (THz) frequencies for ultra-fast


communication.

 Key Features:

o More immersive, holographic communications.

o AI-driven networks for self-optimization and management.

o Seamless integration of quantum computing and edge computing to enhance


network capabilities.

2. Key Wireless Communication Technologies in Modern Mobile Networks


Wireless communication encompasses various technologies that are used to connect mobile
devices to networks, facilitating data transmission. Below are the most critical technologies
that play a role in modern mobile communications:

2.1. Wi-Fi (Wireless Fidelity)

 Technology: Wi-Fi uses IEEE 802.11 standards to enable short-range wireless


communication between devices and networks.

 Key Features:

o Commonly used in local area networks (LANs) to provide internet access.

o Can connect mobile devices to the internet without using cellular data.
o Multiple versions of Wi-Fi, including Wi-Fi 5 (802.11ac) and Wi-Fi 6
(802.11ax), offering higher data rates and reduced latency.

 Speed: Up to 9.6 Gbps (Wi-Fi 6).

 Use Cases: Home internet, public hotspots, enterprise networks.

2.2. Bluetooth

 Technology: Bluetooth operates on IEEE 802.15.1 and is used for short-range


communication between devices, usually in personal area networks (PANs).

 Key Features:

o Low energy consumption with the Bluetooth Low Energy (BLE) standard.

o Primarily used for device pairing and data transfer, such as for headphones,
wearables, and IoT devices.

o Newer versions like Bluetooth 5.0 provide enhanced range and data speed.

 Speed: Up to 3 Mbps (Bluetooth 5.0).

 Use Cases: Wearables, wireless peripherals, IoT devices, and car connectivity.

2.3. NFC (Near Field Communication)

 Technology: NFC is a short-range wireless communication technology based on


ISO/IEC 18092.

 Key Features:

o Used for secure, close-proximity communication between devices.

o Enables quick and secure data transfer (e.g., contactless payments, file sharing,
and authentication).

o Has a very short communication range (a few centimeters).

 Speed: Up to 424 kbps.

 Use Cases: Mobile payments (e.g., Google Pay, Apple Pay), ticketing, access control.

2.4. Zigbee

 Technology: Zigbee is based on the IEEE 802.15.4 standard and is designed for low-
power, low-data-rate wireless communication.

 Key Features:

o Primarily used in smart home and industrial applications.

o Enables communication between smart devices like lights, thermostats, and


sensors.

 Speed: Up to 250 kbps.

 Use Cases: Home automation, industrial IoT.


Write in detail about recent trends in communication
protocols for IOT nodes?
Recent Trends in Communication Protocols for IoT Nodes

The Internet of Things (IoT) revolution has ushered in a wave of innovation across industries,
from smart homes to industrial automation and healthcare. One of the key components
driving this revolution is the communication protocols that allow IoT devices (or nodes) to
share data and interact with each other or centralized systems (cloud, edge, or local
networks). As IoT applications evolve, so too do the communication protocols used, in terms
of both technology and standardization. Below are the most recent trends in communication
protocols for IoT nodes.

1. Low-Power Wide-Area Networks (LPWAN)

LPWAN protocols are gaining traction for IoT applications due to their ability to provide long-
range communication with minimal power consumption. These networks are particularly
useful for battery-powered IoT devices deployed in remote or rural areas.

Recent LPWAN Protocols:

 LoRaWAN (Long Range Wide Area Network):

o Trend: LoRaWAN has become a dominant protocol in IoT for long-range, low-
power communication, especially in smart agriculture, environmental monitoring,
and logistics.

o Key Features:

 Low power consumption.

 Long range (up to 15 km in rural areas).

 Supports bi-directional communication.

 Operates in unlicensed ISM bands.

o Use Cases: Smart meters, environmental sensors, smart agriculture, asset


tracking.

 NB-IoT (Narrowband IoT):

o Trend: Developed by 3GPP (Third Generation Partnership Project), NB-IoT


operates in licensed spectrum, ensuring better network security and reliability.

o Key Features:

 High capacity (supports massive IoT deployments).

 Ultra-low power consumption.

 Supports deep indoor coverage (excellent penetration in buildings).

o Use Cases: Smart cities, industrial IoT, smart grids, health monitoring.

 Sigfox:

o Trend: Sigfox is another LPWAN technology that is seeing widespread adoption,


particularly in industries requiring low data throughput over long distances.
o Key Features:

 Very low energy usage.

 Simple protocol with low-cost devices.

 Wide-area coverage via a global network of base stations.

o Use Cases: Remote asset tracking, agriculture, and logistics.

2. Bluetooth Low Energy (BLE)

Bluetooth Low Energy (BLE) is one of the most widely used communication protocols for
short-range IoT applications due to its ultra-low power consumption. BLE is being enhanced
to meet the increasing demands of modern IoT use cases.

Recent BLE Trends:

 Bluetooth 5.0 and Beyond:

o Trend: Bluetooth 5.0, and its subsequent versions, offer enhanced speed, range,
and broadcast capacity.

o Key Features:

 Increased Range: BLE 5.0 supports up to 240 meters of range,


significantly improving coverage compared to previous versions.

 Higher Data Transfer: BLE 5.0 supports data transfer rates of up to 2


Mbps, making it more viable for larger data payloads.

 Mesh Networking: BLE 5.0 also introduces mesh networking, enabling


low-power devices to communicate with each other over larger areas.

o Use Cases: Smart homes, wearables, healthcare devices, location-based


services (e.g., asset tracking).

3. Zigbee and Thread

Zigbee and Thread are communication protocols based on the IEEE 802.15.4 standard,
offering low-power, reliable, and secure wireless communication.

Recent Trends with Zigbee and Thread:

 Zigbee:

o Trend: Zigbee remains popular for home automation and industrial applications
because of its low power, mesh networking capabilities, and strong industry
support.

o Key Features:

 Low power, short-range communication (typically up to 100 meters).

 Mesh networking for scalability and reliability.

 Supports secure communication with AES encryption.


o Use Cases: Smart home devices, energy management systems, and industrial
sensors.

 Thread:

o Trend: Thread is an emerging protocol developed by the Thread Group


(supported by companies like Google, Apple, and others). It is designed for low-
power, secure, and scalable IoT networks.

o Key Features:

 IP-based (uses IPv6), which simplifies integration with existing internet


systems.

 Self-healing mesh network, which makes it robust and resilient.

 Strong security with AES encryption.

o Use Cases: Home automation, smart lighting, smart appliances, and healthcare.

4. 5G and IoT Communication

With the introduction of 5G, the evolution of communication protocols for IoT is taking a
massive leap forward. 5G promises ultra-fast data speeds, low latency, and the ability to
connect a massive number of devices simultaneously, making it ideal for demanding IoT
applications.

Recent 5G Trends:

 Ultra-low Latency: 5G is expected to provide latency as low as 1 millisecond, which


is essential for time-sensitive IoT applications, such as autonomous vehicles, smart
healthcare, and industrial automation.

 Massive Device Connectivity: 5G networks are optimized for supporting massive


IoT deployments, offering the ability to connect millions of devices in a single area
without network congestion.

 Network Slicing: 5G allows for the creation of network slices—virtual, isolated


networks that can be customized to meet specific requirements of different IoT use
cases (e.g., smart factories, healthcare, or urban infrastructure).

 Use Cases: Autonomous vehicles, smart cities, industrial IoT, real-time remote
monitoring.

5. MQTT and CoAP for IoT Messaging

IoT communication often involves the exchange of small amounts of data between devices.
To facilitate this, lightweight messaging protocols such as MQTT and CoAP have gained
popularity.

Recent MQTT and CoAP Trends:

 MQTT (Message Queuing Telemetry Transport):

o Trend: MQTT is a lightweight, publish-subscribe messaging protocol designed for


low-bandwidth, high-latency networks, making it ideal for IoT devices.
o Key Features:

 Quality of Service (QoS): Ensures reliable message delivery with various


levels of guarantees.

 Low Overhead: Minimal bandwidth usage and lightweight, making it


suitable for resource-constrained devices.

 Persistent Sessions: Devices can maintain connections and continue


message exchange even if temporarily disconnected.

o Use Cases: Smart home, industrial IoT, agriculture, and remote monitoring
systems.

 CoAP (Constrained Application Protocol):

o Trend: CoAP is designed for simple, low-power devices that often operate in
constrained environments.

o Key Features:

 Lightweight and optimized for low-power devices.

 Based on the RESTful architecture (similar to HTTP but more efficient).

 UDP-based, which offers low overhead compared to TCP.

o Use Cases: Smart grids, smart meters, environmental monitoring, and sensors in
resource-constrained environments.

6. Wi-Fi 6 and Wi-Fi HaLow

Wi-Fi 6 and Wi-Fi HaLow are emerging trends in Wi-Fi communication that are optimized for
IoT devices.

Wi-Fi 6:

 Trend: Wi-Fi 6 (802.11ax) is being adopted to support high-density IoT environments.

 Key Features:

o Improved capacity: Supports more devices simultaneously (ideal for


environments like smart cities or factories).

o Higher Speeds: Provides data rates of up to 9.6 Gbps.

o Reduced Latency: Supports applications requiring real-time communication.

o Use Cases: High-density IoT deployments, smart homes, connected cities.

Wi-Fi HaLow:

 Trend: Wi-Fi HaLow (802.11ah) is designed for low-power, long-range IoT devices.

 Key Features:

o Optimized for low-power, long-range IoT devices, ideal for smart homes and
industrial IoT.

o Operates on sub-1 GHz frequencies, providing better penetration and range.

o Lower power consumption than traditional Wi-Fi.


o Use Cases: Smart cities, industrial IoT, agriculture.

Conclusion

The communication protocols for IoT nodes continue to evolve to meet the increasing
demand for faster, more reliable, and more energy-efficient connectivity. Recent trends
indicate a shift towards:

 Low-power, long-range protocols like LPWAN (LoRaWAN, Sigfox, NB-IoT) for


applications that require minimal power consumption and long-range connectivity.

 Bluetooth 5.0 and Wi-Fi 6 offering faster, more efficient connections for personal and
home automation devices.

 The rise of 5G to enable real-time, high-speed communication for massive IoT


networks, with applications in autonomous vehicles, industrial automation, and smart
cities.

 Lightweight messaging protocols like MQTT and CoAP, designed to handle small
amounts of data with low overhead in constrained environments.

These trends reflect the growing complexity of IoT systems, their need for diverse and
adaptive communication protocols, and the shift toward more scalable and energy-efficient
IoT networks. As IoT applications continue to expand, these protocols will play a critical role in
enabling a fully connected and intelligent world.

Using the Intent Service to Simplify the Earthquake Update


Service. Explain?
Using Intent Service to Simplify the Earthquake Update Service
In Android, the IntentService class is a special type of service that simplifies performing
background tasks asynchronously. It is well-suited for operations that are off the main UI
thread, such as network calls, database operations, or performing time-consuming tasks. The
IntentService handles the threading and task queue automatically, which makes it
especially useful for scenarios like updating data from an API in the background.

For an Earthquake Update Service that needs to fetch the latest earthquake data from a
remote server and update the UI, using an IntentService can significantly simplify the
implementation, as it automatically manages the worker thread and executes tasks
sequentially in the background.

Overview: IntentService for Earthquake Updates

The goal of the Earthquake Update Service is to periodically fetch earthquake data (e.g.,
from a REST API), process the information, and update the UI or notify the user of new
earthquake events. The IntentService can manage this background operation in a simplified
manner by handling all the tasks in the background without the need for complex threading.

Why Use IntentService?

1. Automatic Threading: IntentService automatically spawns a worker thread to handle


the task without blocking the main UI thread.
2. Queueing Tasks: IntentService processes incoming tasks (Intents) sequentially,
meaning each task is handled one at a time, which simplifies managing concurrency.

3. Lifecycle Management: IntentService takes care of managing its own lifecycle


(starting and stopping) once the work is complete. This eliminates the need to
manually manage worker threads.

Steps to Implement Earthquake Update Service Using IntentService

Step 1: Define the EarthquakeUpdateIntentService Class

This service will handle the task of fetching earthquake data from an API and processing it.

public class EarthquakeUpdateIntentService extends IntentService {

// Constructor - must call the super constructor with a name for the worker thread

public EarthquakeUpdateIntentService() {

super("EarthquakeUpdateIntentService");

@Override

protected void onHandleIntent(Intent intent) {

// Step 2: Fetch earthquake data from a remote server

String earthquakeData = fetchEarthquakeData();

// Step 3: Process the data (e.g., parse the JSON)

List<Earthquake> earthquakes = parseEarthquakeData(earthquakeData);

// Step 4: Update the UI or notify the user about new earthquakes

updateUI(earthquakes);

private String fetchEarthquakeData() {

// Simulate fetching data from an API (e.g., using HttpURLConnection or Retrofit)

// For simplicity, we're just returning a sample response

return "{...}"; // This would be the JSON response from the API

private List<Earthquake> parseEarthquakeData(String data) {

// Parse the earthquake data from JSON to a List of Earthquake objects


// Here, we're assuming the use of a library like Gson to parse the data

return new ArrayList<>(); // Return a list of Earthquake objects

private void updateUI(List<Earthquake> earthquakes) {

// Use a BroadcastReceiver, EventBus, or directly update UI components here

// For example, send a broadcast to notify the UI of new data:

Intent updateIntent = new Intent("com.example.ACTION_UPDATE_EARTHQUAKE_LIST");

updateIntent.putParcelableArrayListExtra("earthquake_list", new
ArrayList<>(earthquakes));

sendBroadcast(updateIntent);

Step 2: Declare the Service in the Manifest

In the AndroidManifest.xml, declare the EarthquakeUpdateIntentService to ensure the


system knows about the service.

<service android:name=".EarthquakeUpdateIntentService" android:enabled="true"


android:exported="false"/>

Step 3: Start the Service

You can trigger the EarthquakeUpdateIntentService using an Intent from an Activity or


any other component in your app. Here's an example of how to start the service:

Intent intent = new Intent(this, EarthquakeUpdateIntentService.class);

startService(intent);

This will initiate the service, which will then start fetching earthquake data in the background.

Step 4: Handle Results and Update the UI

After the data has been fetched and processed, you’ll likely need to notify the user. This can
be done in several ways, such as through:

 BroadcastReceiver: Sending a broadcast message that the main UI or other


components can listen for and act upon.

public class EarthquakeUpdateReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

// Handle the broadcast and update UI (e.g., update a ListView)

List<Earthquake> earthquakes = intent.getParcelableArrayListExtra("earthquake_list");

// Update UI components here

}
}

 EventBus: Using an event bus (like EventBus) to post events for easy communication
between the service and the UI.

 LiveData: For modern apps using architecture components, LiveData or ViewModel can
be used to communicate with the UI.

To register the BroadcastReceiver, you can do so either in your Activity or Fragment:

EarthquakeUpdateReceiver receiver = new EarthquakeUpdateReceiver();

IntentFilter filter = new IntentFilter("com.example.ACTION_UPDATE_EARTHQUAKE_LIST");

registerReceiver(receiver, filter);

Step 5: Handle Edge Cases (No Network)

In real-world applications, network connectivity issues are common. You should handle these
gracefully by checking the network state before attempting to fetch data. If the device is
offline, you can show an error message or retry the operation later.

private boolean isNetworkAvailable() {

ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

return activeNetwork != null && activeNetwork.isConnected();

private String fetchEarthquakeData() {

if (!isNetworkAvailable()) {

return null; // Handle the lack of network, maybe return cached data or error message

// Proceed with fetching data

Step 6: Stop the Service

The IntentService automatically stops after the onHandleIntent() method finishes


executing. There’s no need to manually stop it. However, if needed, you can stop the service
by calling stopSelf() explicitly.

Advantages of Using IntentService for Earthquake Update Service

1. Simplicity: The IntentService handles threading and task queuing automatically,


allowing you to focus on implementing the task logic without worrying about the
complexity of managing threads or worker pools.

2. Asynchronous Operations: Since IntentService runs in the background, it won’t


block the UI thread, making it perfect for tasks like fetching earthquake data or other
long-running operations.

3. Sequential Execution: IntentService processes intents sequentially, meaning you


don’t have to manage concurrency issues manually. This is useful if you need to fetch
updates in a specific order.

4. Efficient Lifecycle Management: Once the task is complete, IntentService stops


itself, freeing up resources.

Unit 4

Write a short note on Android Field Service App


An Android Field Service App is a specialized mobile application designed to help
businesses manage and optimize field operations, specifically for employees who work
outside the office, such as service technicians, delivery drivers, maintenance workers, or
sales representatives. These apps are typically used in industries like utilities, repair services,
delivery, and sales.

Key Features of an Android Field Service App:

1. Job Scheduling & Dispatching:

o The app allows managers to assign tasks to field agents in real-time, optimizing
routes and schedules.

o Dispatchers can track job statuses and ensure that technicians reach their
appointments on time.

2. Work Order Management:

o Field workers can access detailed work orders, including customer information,
service history, and issue reports, directly on their Android device.

o Technicians can update the status of tasks (e.g., completed, in progress, delayed)
and log any issues encountered.

3. Inventory & Parts Management:

o The app allows technicians to check the availability of required parts or


equipment in real time.

o It can track inventory levels and notify managers when items need to be
restocked.

4. Customer Management & Communication:

o Technicians can interact directly with customers, providing status updates,


estimated arrival times, or requesting additional details about the issue.

o The app may include features for collecting customer feedback or signatures to
confirm service completion.

5. Data Capture & Reporting:


o Field agents can use the app to capture photos, videos, and notes related to the
service job.

o Data can be automatically uploaded to the system to generate reports, which


help in documentation and invoicing.

6. Offline Functionality:

o Many Android Field Service Apps are designed to work offline, allowing field
workers to continue their tasks even when there is no internet connection.

o Once connectivity is restored, data is synced with the central system.

7. Navigation & Route Optimization:

o The app integrates with mapping and GPS features to help technicians navigate
to their destinations efficiently.

o It can optimize travel routes, minimizing fuel costs and time spent on the road.

8. Real-Time Updates & Notifications:

o Technicians can receive real-time notifications about new jobs, changes to


schedules, or urgent issues.

o Managers can track the progress of field agents and receive status updates.

9. Time Tracking & Billing:

o The app may include features for logging work hours, which helps in accurate
billing and payroll calculations.

o It can also generate invoices for services rendered, making billing more seamless
and faster.

Benefits:

 Improved Efficiency: Automating task scheduling and route optimization saves time,
which leads to more jobs completed in a day.

 Enhanced Communication: Real-time updates improve communication between field


workers and the back office.

 Better Customer Experience: Timely updates and efficient service delivery increase
customer satisfaction.

 Reduced Operational Costs: Optimized routes and efficient use of resources reduce
fuel consumption and unnecessary delays.

 Data Accuracy: Real-time data entry ensures fewer errors and better reporting.

In summary, an Android Field Service App provides a centralized solution for businesses that
rely on mobile workers. By streamlining operations and improving efficiency, it allows
businesses to offer better service, optimize resources, and ultimately drive growth.
Explain about Mobile agents and peer-to-peer architecture
Mobile Agents in Mobile Computing
In Mobile Computing, Mobile Agents are the composition of computer software and data that
can autonomously move from one computer to another computer and continue its execution
on the destination computer.

In other words, you can say that An Mobile Agent is an autonomous program that is capable
of moving from host to host in a network and interact with resources and other agents. In this
process, the chance of data loss is scarce because the state of the running program is saved
and then transported to the new host. It allows the program to continue execution from
where it left off before migration. The most significant advantage of mobile agents is the
possibility of moving complex processing functions to the location where you have enormous
amounts of data and that have to be processed.

Mobile Agents are also called as transportable agents. They are classified into two types:

o Mobile Agents with pre-defined path: They have a static migration path.

o Mobile Agents with undefined path i.e., Roamer: They have dynamic migration
paths. The mobile agents choose their path according to the present network condition.

Features of Mobile Agents

The mobile agents are autonomous with intelligence, social ability, learning, and the most
important feature is their mobility. They are independent in nature, self-driven and do not
require a corresponding node for communication. They can work efficiently even after the
user gets disconnected from the network.

1. Intelligence

Mobile Agents are capable of learning and searching for knowledge about their domain.
That's why they are called intelligent agents because they possess a degree of domain
knowledge. They can also transport their state from one environment to another without
disturbing the previous holding data and be capable of performing appropriately in the new
environment.

2. Autonomous

The Mobile Agents are Autonomous. It means the agents are not only motivated by the
outside actions initiated by the users or system but also they have internal events that
decided their performance and behavior. The mobile agents can also take an autonomous
decision while selecting a node.

3. Mobility

Mobile Agents contain some degree of mobility. The agent is not limited to its home node
only. They can migrate from one node to another and can carry out tasks along with them.
This feature distributes the processing and balancing of the load. Another benefit of this
capability is that when the user goes offline, the agents will still keep functioning.

4. Communicative

Mobile Agents can communicate effectively with other agents, users and systems. The mobile
agents use a communication language for inter-agent communication.

Life Cycle of Mobile Agents

The life cycle of mobile agents ensures the following conditions:


o They can adapt to the environment. For example, either home or foreign environment.

o They are capable of switching among the positions of one node to another.

o They are autonomous and focused on the final output.

Advantages of Mobile Agents

The following are some advantages of mobile agents over conventional agents:

o Mobile Agents are autonomous and self-driven in nature.

o They are maintenance-friendly or easily maintainable.

o They are Fault-tolerant. It means they are able to operate without an active connection
between client and server.

o They reduce the compilation time.

o They provide less delay in the network.

o They provide fewer loads on the network.

o They facilitate parallel processing. It means they can be asynchronously executed on


multiple heterogeneous network hosts.

o They provide dynamic adaptation in which their actions are dependent on the state of
the host environment.

Disadvantages of Mobile Agents

The following are some disadvantages of mobile agents:

o The most significant disadvantage of mobile agents is their security. They are less
secured

Applications of Mobile Agents

Mobile agents are used in the following applications:

o Mobile Agents are applied in a wide range of domains such as E-commerce, traffic
control, network management, robotics, data-intensive applications etc.

o They are also used in grid computing, parallel computing, distributed computing and
mobile computing etc.
What is a Peer-to-Peer (P2P) architecture?
Peer-to-peer (P2P) architecture is a distributed computing model where nodes in the network
behave as equals, communicating and sharing resources directly with each other. Unlike
client-server architectures that rely on centralized servers to facilitate communication and
resource sharing, P2P networks use the collective power of individual nodes to
achieve scalability, fault tolerance, and resilience.

Characteristics of Peer-to-Peer (P2P) Networks

 Decentralization: P2P networks operate without a central authority, allowing nodes to


communicate and share resources directly.

 Scalability: P2P networks can be easily scaled to accommodate a large number of


nodes without relying on a centralized infrastructure.

 Fault tolerance: P2P networks are resilient to node failure because the absence of a
central server means that the network can continue to function even if some nodes
become unavailable.

 Resource sharing: P2P network participants can share files, data, and computing
resources directly with each other.

 Autonomy: Each node in a P2P network has autonomy over its own resources and
decisions, which contributes to the overall resilience and flexibility of the network.

Types of Peer-to-Peer (P2P) Networks

Below are the types of P2P Networks:

1. Pure P2P Networks

Also known as decentralized or true P2P networks, pure P2P networks operate without any
central authority or dedicated infrastructure.

 Peers in these networks have equal privileges and responsibilities, and they directly
communicate and share resources with each other.

 Examples include BitTorrent and Gnutella.

2. Hybrid P2P Networks

Hybrid P2P networks combine elements of both decentralized and centralized architectures.

 They typically include some central servers or super peers that coordinate network
activities, manage resources, or provide additional services.

 Hybrid P2P networks aim to achieve a balance between decentralization and efficiency.
Examples include Skype and eDonkey.

3. Overlay P2P Networks

Overlay P2P networks create a virtual network on top of an existing infrastructure, such as
the internet.

 Peers in these networks establish direct connections with each other, forming an
overlay structure that facilitates resource sharing and communication.

 Overlay P2P networks often employ distributed hash tables (DHTs) or other routing
mechanisms to locate and retrieve resources efficiently. Examples include Chord and
Kademlia.
4. Structured P2P Networks

Structured P2P networks organize peers into a specific topology or structure, such as a ring,
tree, or mesh.

 Peers maintain routing tables or other data structures to facilitate efficient resource
lookup and data retrieval.

 Structured P2P networks offer predictable performance and scalability but may require
additional overhead for maintenance. Examples include CAN (Content Addressable
Network) and Pastry.

5. Unstructured P2P Networks

In contrast to structured P2P networks, unstructured P2P networks do not impose any specific
topology or organization on peers.

 Peers in these networks typically rely on flooding or random search algorithms to locate
resources, resulting in lower efficiency but greater flexibility and simplicity.

 Examples include early versions of Gnutella and Freenet.

Key components of Peer-to-Peer (P2P) Systems

Below are the key components of Peer-to-Peer (P2P) Systems:

 Peer Nodes: Individual participants in a P2P network, each acting as both a client and
a server.

 Overlay Network: A virtual network topology that connects peer nodes and facilitates
communication and resource sharing.

 Indexing Mechanisms: Systems for organizing and indexing shared resources,


enabling efficient search and retrieval.

 Bootstrapping Mechanisms: Processes for node discovery and network initialization


that allow new nodes to join the network seamlessly.

Bootstrapping in Peer-to-Peer (P2P) Networks

The bootstrapping process in P2P networks involves discovering and initializing new nodes.
This typically includes mechanisms for node discovery, network configuration, and
connection protocols. Common bootstrap techniques include centralized bootstrap servers,
distributed hash tables (DHTs), and peer exchange protocols.

Data management in Peer-to-Peer (P2P) networks

Data management in Peer-to-Peer (P2P) networks involves the storage, retrieval, replication,
and consistency maintenance of data distributed across multiple peers.

 Decentralized Storage:

o Unlike centralized systems where data is stored on dedicated servers, in P2P


networks, each peer stores a portion of the shared data locally.

o This decentralized approach eliminates reliance on a single point of failure and


enhances data availability.

 Data Retrieval:
o Peers in a P2P network need to locate specific data items dispersed across other
peers.

o This involves querying the network using distributed search algorithms or


structured overlay networks to efficiently find and retrieve the desired data.

 Replication:

o To improve data availability and fault tolerance, shared data is often replicated
across multiple peers.

o Replication ensures that even if some peers become unavailable, the data
remains accessible from other replicas.

o Various replication strategies are employed based on factors such as data


popularity and network characteristics.

 Consistency Management:

o Maintaining consistency among distributed data replicas is challenging due to the


decentralized and dynamic nature of P2P networks.

o Consistency management strategies aim to ensure that all replicas remain


synchronized despite concurrent updates and network partitions.

Routing algorithms in Peer-to-Peer (P2P) networks

Routing algorithms in P2P networks determine how data packets are routed between nodes.
Common routing algorithms include flooding, random walks, and greedy routing. The goal of
these algorithms is to balance efficiency, scalability, and resilience in decentralized networks.

 Flooding:

o This simple algorithm involves a peer forwarding a query to all its neighbors.
Each neighbor repeats this process until the query reaches its destination or
expires.

o While straightforward, flooding can lead to redundant traffic and scalability


issues, especially in large networks.

 Random Walks:

o Peers select random neighbors to forward queries, repeating this process until
the target is found.

o Random walks are decentralized but may be inefficient for large networks and
can take longer to locate resources.

 Distributed Hash Tables (DHTs):

o DHTs are structured routing algorithms that use a distributed hash table to map
keys to peers responsible for storing corresponding data.

o Examples include Chord, Kademlia, and Pastry. DHTs organize peers into a
structured overlay network, providing efficient and scalable routing with
logarithmic time complexity for resource location.

 Small-World Networks:

o Small-world routing algorithms aim to exploit the "small-world phenomenon,"


where most nodes can be reached from any other node in a small number of
hops.

o These algorithms combine local and global knowledge to efficiently route queries
in a decentralized manner.

Advantages of Peer-to-Peer (P2P) Networks

Below are the advantages of Peer-to-Peer (P2P) Networks:

 Decentralization: P2P networks distribute control and resources among peers,


eliminating the need for a central server. This decentralization increases resilience and
reduces the risk of a single point of failure.

 Load Distribution: Workload is distributed across multiple peers in a P2P network,


improving resource utilization and overall performance, particularly under heavy loads.

 Cost Reduction: P2P networks can significantly reduce costs associated with
infrastructure, maintenance, and bandwidth, as they rely on resources contributed by
peers rather than centralized servers.

 Content Redundancy and Availability: Content replication across multiple peers


ensures redundancy and continuous availability, even if some peers go offline or
experience failures.

Challenges of Peer-to-Peer (P2P) architecture

Below are the challenges of Peer-to-Peer (P2P) Networks:

 Scalability: P2P networks face scalability challenges as they grow in size. Managing a
large number of peers and ensuring efficient communication between them becomes
increasingly complex.

 Security: Security is a significant concern in P2P networks due to the decentralized


nature, making them susceptible to various threats such as malicious peers, data
tampering, and unauthorized access. Protecting data integrity and ensuring secure
communication among peers is essential.

 Content Availability and Quality: The availability and quality of content can vary
widely in P2P networks due to factors like peer churn, network dynamics, and
heterogeneous resources. Maintaining consistent access to high-quality content across
the network poses a challenge.

 Data Management and Consistency: Managing distributed data in P2P networks


involves storing, retrieving, replicating, and ensuring consistency across multiple peers.
Achieving data consistency and coherence while dealing with peer dynamics and
network partitions is a complex task.

Techniques for Securing Peer-to-Peer (P2P) Communication

Securing Peer-to-Peer (P2P) communication involves implementing various techniques to


protect the confidentiality, integrity, and authenticity of data exchanged between peers.

 Encryption: Utilize cryptographic techniques to encode data, safeguarding it from


unauthorized access. This ensures that even if intercepted, the data remains
unreadable.

 Public Key Infrastructure (PKI): Implement a system that manages digital


certificates, facilitating secure authentication and trust between peers. Digital
certificates verify the identity of communicating parties, enabling secure
communication channels.

 Secure Hash Algorithms: Employ algorithms like SHA-256 to generate unique hash
values for data. These hashes act as digital fingerprints, verifying the integrity of
transmitted data and detecting any tampering.

 Digital Signatures: Use digital signatures to validate the authenticity and integrity of
messages. Signatures, created with the sender's private key, can be decrypted with the
sender's public key to verify origin and ensure data integrity.

 Secure Communication Protocols: Implement protocols like TLS or SSL to establish


encrypted connections between peers. These protocols ensure confidentiality, integrity,
and authentication of data exchanged over P2P networks, safeguarding against
eavesdropping and data manipulation.

P2P Applications Use Cases

The P2P architecture has many applications in various domains, including:

 File sharing: Platforms like BitTorrent and eDonkey use P2P networks for efficient and
decentralized file sharing.

 Content Distribution: P2P-based Content Delivery Networks (CDNs) distribute


multimedia content and software updates to users around the world.

 Collaboration and Communication: P2P messaging and collaboration tools enable


real-time communication and collaboration between users.

 Distributed Computing: P2P computing platforms use distributed resources for tasks
such as scientific computing, data analysis, and cryptocurrency mining.

How to Save Data using the Shared Preferences Object.


Explain?
Save simple data with SharedPreferences
If you have a relatively small collection of key-values that you'd like to save, you can use
the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value
pairs and provides simple methods to read and write them. Each SharedPreferences file is
managed by the framework and can be private or shared.

This page shows you how to use the SharedPreferences APIs to store and retrieve simple
values.

Caution: DataStore is a modern data storage solution that you should use instead
of SharedPreferences. It builds on Kotlin coroutines and Flow, and overcomes many of the
drawbacks of SharedPreferences.

Read the DataStore guide for more information.

The SharedPreferences APIs are for reading and writing key-value pairs, and you shouldn't
confuse them with the Preference APIs, which help you build a user interface for your app
settings (although they also use SharedPreferences to save the user's settings). For
information about the Preference APIs, see the Settings developer guide.
Get a handle to shared preferences

You can create a new shared preference file or access an existing one by calling one of these
methods:

 getSharedPreferences(): Use this if you need multiple shared preference files


identified by name, which you specify with the first parameter. You can call this from
any Context in your app.

 getPreferences(): Use this from an Activity if you need to use only one shared
preference file for the activity. Because this retrieves a default shared preference file
that belongs to the activity, you don't need to supply a name.

For example, the following code accesses the shared preferences file that's identified by the
resource string R.string.preference_file_key and opens it using the private mode so the file is
accessible by only your app:

val sharedPref = activity?.getSharedPreferences(

getString(R.string.preference_file_key), Context.MODE_PRIVATE)

When naming your shared preference files, you should use a name that's uniquely
identifiable to your app. A good way to do this is prefix the file name with your application ID.
For example: "com.example.myapp.PREFERENCE_FILE_KEY"

Alternatively, if you need just one shared preference file for your activity, you can use
the getPreferences() method:

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)

Caution: The MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE modes have


been deprecated since API level 17.

Starting with Android 7.0 (API level 24), Android throws a SecurityException if you use
them. If your app needs to share private files with other apps, it may use a FileProvider with
the FLAG_GRANT_READ_URI_PERMISSION. For more information, also see Sharing Files.

If you're using the SharedPreferences API to save app settings, you should instead
use getDefaultSharedPreferences() to get the default shared preference file for your entire
app. For more information, see the Settings developer guide.

Write to shared preferences

To write to a shared preferences file, create a SharedPreferences.Editor by calling edit() on


your SharedPreferences.

Pass the keys and values you want to write with methods such as: putInt() andputString().
Then call apply() or commit() to save the changes. For example:

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return

with (sharedPref.edit()) {

putInt(getString(R.string.saved_high_score_key), newHighScore)

apply()

apply() changes the in-memory SharedPreferences object immediately but writes the updates
to disk asynchronously. Alternatively, you can use commit() to write the data to disk
synchronously. But because commit() is synchronous, you should avoid calling it from your
main thread because it could pause your UI rendering.

Read from shared preferences

To retrieve values from a shared preferences file, call methods such


as getInt() and getString(), providing the key for the value you want, and optionally a default
value to return if the key isn't present. For example:

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return

val defaultValue = resources.getInteger(R.integer.saved_high_score_default_key)

val highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue)

Write a code to store one line in file which resides in sdcard?


External Storage in Android with Example
Android gives various options for storing apps data which uses a file system similar to the
disk-based system on computer platforms

 App-Specific storage: Store data files within internal volume directories or external.
These data files are meant only for the app’s use. It uses internal storage directories to
save sensitive information such as a username and password that other app should not
access.

 Shared Storage: Store data files such as images, audio, video, documents, etc. that
the app may need to share with other apps.

 Shared Preferences: Store primitive data type such as integer, float, boolean, string,
long in key-value pairs.

 Databases: Store structured data such as user-information(name, age, phone, email,


address, etc.) into private databases.

Developers are advised to use the options available to store data depending upon the space
required, reliable data access, and privacy of data. The data files saved over external
storage devices are publicly accessible on shared external storage using USB mass storage
transfer. Data files stored over external storage using a FileOutputStream object and can
be read using a FileInputStream object.

External Storage Availability

In order to avoid crashing the app first, we need to check storage SD Card is available for
reading and write operations. The method getExternalStorageState() is used to determine
the state of mounted storage media such as SD Card is missing, read-only or readable, and
writable. Below is the code snippet which we will use to check the availability of external
storage. If you’re developing an app that needs external storage and want to implement it
using Kotlin, the Android Mastery with Kotlin: Beginner to Advanced course guides
you through implementing storage features efficiently

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

boolean isAvailable= false;

boolean isWritable= false;

boolean isReadable= false;

String state = Environment.getExternalStorageState();

if(Environment.MEDIA_MOUNTED.equals(state)) {

// Operation possible - Read and Write

isAvailable= true;

isWritable= true;

isReadable= true;

} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {

// Operation possible - Read Only

isAvailable= true;

isWritable= false;

isReadable= true;

} else {

// SD card not available

isAvailable = false;

isWritable= false;

isReadable= false;

Methods to Store data in External Storage

 getExternalStoragePublicDirectory(): This is the present recommended method to


keep files public and these files are not deleted even when the app is uninstalled from
the system. For eg: Images clicked by the camera are still available even after we
uninstall the camera.

 getExternalFilesDir(String type): This method is used to store private data that are
specific to the app only. And data are removed as we uninstall the app.

 getExternalStorageDirectory(): This method is not recommended. It is now absolute


and it is used to access external storage in older versions, API Level less than 7.

Example

In this example, we would store text data into the external storage and fetch to see that data.
A sample GIF is given below to get an idea about what we are going to do in this article. Note
that we are going to implement this project using the Java language.
Step by Step Implementation

Step 1: Create a New Project

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

Step 2: Access Permission to External Storage

To read and write data to external storage, the app


required WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system
permission. These permissions are added to the AndroidManifest.xml file. Add these
permissions just after the package name.

<manifest ... >

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

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

<application ... >

<activity android:name=".MainActivity" ... >

...

</activity>

</application>

</manifest>

Step 3: Before creating the layout and corresponding java files let’s add a few
string attributes which we are using in our layout files

Go to app > res > values > string.xml and insert the following code snippet

<resources>

...

<string name="text_view_data">Enter the Text Data</string>

<string name="edit_text_data">Enter your information</string>

<string name="view_button">View Information</string>

<string name="save_button_public">Save Publicly</string>

<string name="save_button_private">Save Privately</string>

<string name="text_view_saved_data">Saved Text Data</string>

<string name="saved_information">Click to view saved information</string>

<string name="back_button">Go Back</string>

<string name="show_button_public">Public Data</string>

<string name="show_button_private">Private Data</string>


...

</resources>

Now go to app > res > values > colors.xml and change the color attributes as following in
order to make App Bar more attractive.

<resources>

<color name="colorPrimary">#0F9D58</color>

<color name="colorPrimaryDark">#16E37F</color>

<color name="colorAccent">#03DAC5</color>

<color name="buttonColor">#0F9D58</color>

<color name="textColor">#FFFFFF</color>

</resources>

Again go to app > res > drawable and create a new Drawable Resource File and name it
as button_layout. In this, we are modifying our button style for a better UX/UI.

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

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

android:shape="rectangle">

<corners

android:bottomLeftRadius="25dp"

android:bottomRightRadius="25dp"

android:radius="50dp"

android:topLeftRadius="25dp"

android:topRightRadius="25dp" />

<padding

android:bottom="0dp"

android:left="0dp"

android:right="0dp"

android:top="0dp" />

<size

android:width="64dp"

android:height="16dp" />
<solid android:color="@color/buttonColor" />

</shape>

Step 4: Working with the activity_main.xml file

Go to res > layout > activity_main.xml and write down the following code. In this layout
file, we are creating a multiline EditText View for getting the data from users and Buttons to
save that data over internal and external storage media.

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

<RelativeLayout

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

<Button

android:id="@+id/saveButton_public"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentEnd="true"

android:layout_below="@+id/editText_data"

android:layout_marginEnd="48dp"

android:layout_marginTop="8dp"

android:background="@drawable/button_layout"

android:onClick="savePublicly"

android:padding="8dp"

android:text="@string/save_button_public"

android:textAllCaps="false"

android:textColor="@color/textColor" />

<Button

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

android:layout_height="wrap_content"

android:layout_alignParentStart="true"

android:layout_below="@+id/editText_data"

android:layout_marginStart="48dp"

android:layout_marginTop="8dp"

android:layout_toEndOf="@+id/saveButton_public"

android:background="@drawable/button_layout"

android:onClick="savePrivately"

android:padding="8dp"

android:text="@string/save_button_private"

android:textAllCaps="false"

android:textColor="@color/textColor" />

<Button

android:id="@+id/viewButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/saveButton_public"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:background="@drawable/button_layout"

android:onClick="viewInformation"

android:padding="8dp"

android:text="@string/view_button"

android:textAllCaps="false"

android:textColor="@color/textColor" />

<EditText

android:id="@+id/editText_data"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@+id/textView_data"

android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"

android:autofillHints=""

android:hint="@string/edit_text_data"

android:inputType="textMultiLine" />

<TextView

android:id="@+id/textView_data"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentTop="true"

android:layout_centerHorizontal="true"

android:layout_marginTop="8dp"

android:text="@string/text_view_data"

android:textAllCaps="true"

android:textStyle="bold" />

</RelativeLayout>

Step 5: Working with the MainActivity.java file

In MainActivity we define the functions that handled the onClick behavior of the buttons. And
fetch the data from the EditText and save it in external storage publicly and privately. We also
display a Toast message of the path where the data is stored.

import android.Manifest;

import android.content.Intent;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import androidx.core.app.ActivityCompat;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;
public class MainActivity extends AppCompatActivity {

// After API 23 the permission request for accessing external storage is changed

// Before API 23 permission request is asked by the user during installation of app

// After API 23 permission request is asked at runtime

private int EXTERNAL_STORAGE_PERMISSION_CODE = 23;

EditText editText;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// findViewById return a view, we need to cast it to EditText View

editText = (EditText) findViewById(R.id.editText_data);

public void savePublicly(View view) {

// Requesting Permission to access External Storage

ActivityCompat.requestPermissions(this, new String[]


{Manifest.permission.READ_EXTERNAL_STORAGE},

EXTERNAL_STORAGE_PERMISSION_CODE);

String editTextData = editText.getText().toString();

// getExternalStoragePublicDirectory() represents root of external storage, we are using


DOWNLOADS

// We can use following directories: MUSIC, PODCASTS, ALARMS, RINGTONES,


NOTIFICATIONS, PICTURES, MOVIES

File folder =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

// Storing the data in file with name as geeksData.txt

File file = new File(folder, "geeksData.txt");

writeTextData(file, editTextData);

editText.setText("");
}

public void savePrivately(View view) {

String editTextData = editText.getText().toString();

// Creating folder with name GeeksForGeeks

File folder = getExternalFilesDir("GeeksForGeeks");

// Creating file with name gfg.txt

File file = new File(folder, "gfg.txt");

writeTextData(file, editTextData);

editText.setText("");

public void viewInformation(View view) {

// Creating an intent to start a new activity

Intent intent = new Intent(MainActivity.this, ViewInformationActivity.class);

startActivity(intent);

// writeTextData() method save the data into the file in byte format

// It also toast a message "Done/filepath_where_the_file_is_saved"

private void writeTextData(File file, String data) {

FileOutputStream fileOutputStream = null;

try {

fileOutputStream = new FileOutputStream(file);

fileOutputStream.write(data.getBytes());

Toast.makeText(this, "Done" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (fileOutputStream != null) {

try {

fileOutputStream.close();
} catch (IOException e) {

e.printStackTrace();

Step 6: Create a new Empty Activity

We will create a new activity and name it ViewInformationActivity. We use this activity to
display the saved data from the external storage. So, first, we create a layout for this activity
similar to the MainActivity layout. activity_view_information.xml layout code snippet:

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

<RelativeLayout

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

<Button

android:id="@+id/showButton_public"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentEnd="true"

android:layout_below="@+id/textView_get_saved_data"

android:layout_marginEnd="48dp"

android:layout_marginTop="8dp"

android:background="@drawable/button_layout"

android:onClick="showPublicData"

android:padding="8dp"

android:text="@string/show_button_public"

android:textAllCaps="false"

android:textColor="@color/textColor" />
<Button

android:id="@+id/showButton_private"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentStart="true"

android:layout_below="@+id/textView_get_saved_data"

android:layout_marginStart="48dp"

android:layout_marginTop="8dp"

android:layout_toEndOf="@+id/showButton_public"

android:background="@drawable/button_layout"

android:onClick="showPrivateData"

android:padding="8dp"

android:text="@string/show_button_private"

android:textAllCaps="false"

android:textColor="@color/textColor" />

<Button

android:id="@+id/goBackButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/showButton_public"

android:layout_centerHorizontal="true"

android:layout_marginTop="16dp"

android:background="@drawable/button_layout"

android:onClick="back"

android:padding="8dp"

android:text="@string/back_button"

android:textAllCaps="false"

android:textColor="@color/textColor" />

<TextView

android:id="@+id/textView_get_saved_data"

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

android:layout_below="@+id/textView_saved_data"

android:layout_marginTop="8dp"

android:gravity="center"

android:hint="@string/saved_information" />

<TextView

android:id="@+id/textView_saved_data"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="8dp"

android:gravity="center"

android:text="@string/text_view_saved_data"

android:textAllCaps="true"

android:textStyle="bold" />

</RelativeLayout>

Now, we will create a corresponding java code for ViewInformationActivity. In this, we


define methods showPublicData() and showPrivateData() over buttons that will fetch the
data from the files saved to external storage and add the data to buffer, and then populate
the data to TextView in order to show them. ViewInformationAcitity.java code snippet:

import android.content.Intent;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

public class ViewInformationActivity extends AppCompatActivity {

TextView textView;
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_view_information);

// findViewById returns a view, we need to cast it into TextView

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

public void showPublicData(View view) {

// Accessing the saved data from the downloads folder

File folder =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

// geeksData represent the file data that is saved publicly

File file = new File(folder, "geeksData.txt");

String data = getdata(file);

if (data != null) {

textView.setText(data);

} else {

textView.setText("No Data Found");

public void showPrivateData(View view) {

// GeeksForGeeks represent the folder name to access privately saved data

File folder = getExternalFilesDir("GeeksForGeeks");

// gft.txt is the file that is saved privately

File file = new File(folder, "gfg.txt");

String data = getdata(file);

if (data != null) {

textView.setText(data);
} else {

textView.setText("No Data Found");

public void back(View view) {

Intent intent = new Intent(ViewInformationActivity.this, MainActivity.class);

startActivity(intent);

// getdata() is the method which reads the data

// the data that is saved in byte format in the file

private String getdata(File myfile) {

FileInputStream fileInputStream = null;

try {

fileInputStream = new FileInputStream(myfile);

int i = -1;

StringBuffer buffer = new StringBuffer();

while ((i = fileInputStream.read()) != -1) {

buffer.append((char) i);

return buffer.toString();

} catch (Exception e) {

e.printStackTrace();

} finally {

if (fileInputStream != null) {

try {

fileInputStream.close();

} catch (IOException e) {

e.printStackTrace();

return null;
}

Output: Run on Emulator

Create a simple registration form using EditText, Radio


Button, and store the user value in Shared Preference.
Here’s an example of how to create a simple Registration Form in an Android app using
EditText, RadioButton, and storing the user values in SharedPreferences:

1. Create the Layout (XML)

In your res/layout/activity_main.xml, define the EditText fields for user input (like name and
email), a RadioButton for gender selection, and a Button to submit the form.

xml

Copy code

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<!-- Name EditText -->

<EditText

android:id="@+id/etName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Enter your name"

android:inputType="textPersonName" />

<!-- Email EditText -->

<EditText

android:id="@+id/etEmail"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:hint="Enter your email"

android:inputType="textEmailAddress" />

<!-- Gender Radio Buttons -->

<RadioGroup

android:id="@+id/radioGroupGender"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal">

<RadioButton

android:id="@+id/radioMale"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Male" />

<RadioButton

android:id="@+id/radioFemale"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Female" />

</RadioGroup>

<!-- Submit Button -->

<Button

android:id="@+id/btnSubmit"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Register" />

</LinearLayout>

2. Activity Code (Java)


In your MainActivity.java, handle the logic of reading user input from the EditText fields,
RadioButton, and storing the data in SharedPreferences when the submit button is
clicked.

java

Copy code

package com.example.registrationform;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.RadioButton;

import android.widget.RadioGroup;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText etName, etEmail;

private RadioGroup radioGroupGender;

private RadioButton radioMale, radioFemale;

private Button btnSubmit;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize UI components

etName = findViewById(R.id.etName);

etEmail = findViewById(R.id.etEmail);

radioGroupGender = findViewById(R.id.radioGroupGender);

radioMale = findViewById(R.id.radioMale);
radioFemale = findViewById(R.id.radioFemale);

btnSubmit = findViewById(R.id.btnSubmit);

// Set click listener for the Submit button

btnSubmit.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Get values from EditText fields

String name = etName.getText().toString();

String email = etEmail.getText().toString();

// Get selected gender from RadioButton

String gender = "";

if (radioMale.isChecked()) {

gender = "Male";

} else if (radioFemale.isChecked()) {

gender = "Female";

// Store the data in SharedPreferences

if (!name.isEmpty() && !email.isEmpty() && !gender.isEmpty()) {

SharedPreferences sharedPreferences = getSharedPreferences("UserDetails",


MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("name", name);

editor.putString("email", email);

editor.putString("gender", gender);

editor.apply(); // Commit the data

Toast.makeText(MainActivity.this, "Registration Successful",


Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(MainActivity.this, "Please fill all fields",


Toast.LENGTH_SHORT).show();

}
}

});

Explanation:

1. UI Components:

o EditText: For the user to input their name and email.

o RadioGroup with RadioButton: For the user to select their gender.

o Button: When clicked, the app collects all the values entered and stores them in
SharedPreferences.

2. SharedPreferences:

o We use SharedPreferences to store the data entered by the user (name, email,
gender). This data is saved persistently and can be retrieved even if the app is
closed and reopened.

3. Button Click Listener:

o When the Submit button is clicked, we:

 Collect data from the EditText and RadioButton.

 Check if the fields are filled.

 Store the collected data in SharedPreferences.

4. Toast Message:

o We use Toast.makeText() to show a confirmation message ("Registration


Successful") or an error message if any field is missing.

3. Accessing Stored Data

To retrieve the stored data from SharedPreferences, you can use the following code
(perhaps in another activity or for displaying the data):

SharedPreferences sharedPreferences = getSharedPreferences("UserDetails",


MODE_PRIVATE);

String name = sharedPreferences.getString("name", "No Name");

String email = sharedPreferences.getString("email", "No Email");

String gender = sharedPreferences.getString("gender", "No Gender");

Toast.makeText(MainActivity.this, "Name: " + name + "\nEmail: " + email + "\nGender: " +


gender, Toast.LENGTH_LONG).show();

This code fetches the values from SharedPreferences and displays them in a Toast
message.

Conclusion:
In this example, we created a simple Registration Form using EditText, RadioButton, and
SharedPreferences. The user inputs their details, and upon submitting the form, the data is
saved in SharedPreferences. You can later retrieve the saved data as needed.

Define Shared preferences. List and explain data storage


options available.
Covered above

Differentiate between internal storage and external storage.


Internal Storage and External Storage are two types of storage options available on
mobile devices, including Android. Both have their own characteristics, uses, and advantages.
Here’s a detailed comparison between the two:

1. Location and Access

 Internal Storage:

o Location: Internal storage is a part of the device's built-in storage (e.g., the
phone's internal flash memory).

o Access: It is private to the app and can only be accessed by the app itself and
system processes. Other apps cannot access the data in internal storage unless
explicitly allowed.

o Usage: Used for storing sensitive app data (e.g., databases, preferences, and
application-specific files).

 External Storage:

o Location: External storage refers to the removable or secondary storage, such


as an SD card (external memory card), or in some cases, a shared storage
partition in the device.

o Access: It is public and can be accessed by any app on the device, given that the
app has the necessary permissions.

o Usage: Used for storing user files (e.g., photos, music, and video) that need to be
shared with other apps or need larger storage.

2. Security and Privacy

 Internal Storage:

o Security: Data stored in internal storage is private to the app. Other apps cannot
read the data unless they have the proper permissions.

o Encryption: Internal storage can be encrypted, making it more secure for storing
sensitive data.

 External Storage:

o Security: Data on external storage is less secure. It can be accessed by any app
with the necessary permissions, and if the storage device is removed, the data is
exposed.

o Encryption: External storage is generally not encrypted by default, and the data
may be more susceptible to unauthorized access.

3. Storage Capacity

 Internal Storage:

o Capacity: The size of internal storage is typically fixed and much smaller
compared to external storage. It's often used for system files, installed apps, and
app data.

o Limitations: When internal storage is full, the user cannot install more apps or
save additional data.

 External Storage:

o Capacity: The capacity of external storage can vary based on the external
storage device (e.g., SD card), and it is typically larger than internal storage.

o Limitations: External storage can be expanded (by adding or swapping SD


cards), but it is limited by the maximum supported capacity of the device.

4. Performance

 Internal Storage:

o Performance: Internal storage generally provides faster read and write speeds
compared to external storage because it is integrated into the device's hardware
(e.g., NAND flash memory).

o Use Case: Ideal for storing app data, system files, and caches, which need fast
access.

 External Storage:

o Performance: External storage tends to be slower, especially if it involves SD


cards, as they typically offer lower read/write speeds compared to internal
storage.

o Use Case: Best suited for media files (photos, music, videos), which don't require
high-speed access.

5. Lifetime and Durability

 Internal Storage:

o Durability: Internal storage is more durable as it is part of the device's core


hardware and is less likely to be physically damaged.

o Lifetime: It typically has a longer lifespan than external storage as it is designed


for continuous use and is less prone to wear.

 External Storage:

o Durability: External storage (especially SD cards) is more prone to physical


damage, wear, and tear, as it is removable and can be exposed to external
factors.
o Lifetime: SD cards, for instance, have a limited number of read/write cycles and
may degrade over time.

6. Mounting and Unmounting

 Internal Storage:

o Mounting: Internal storage is automatically mounted when the device is


powered on. The user does not need to manually mount or unmount it.

o Unmounting: It cannot be unmounted (it is always available for access while the
device is on).

 External Storage:

o Mounting: External storage, like an SD card, must be mounted by the operating


system for access. On Android, external storage is automatically mounted when
inserted, but can be manually unmounted by the user.

o Unmounting: The user can unmount external storage (e.g., SD card) safely
through the device settings to avoid data corruption.

7. Usage Example in Android Development

 Internal Storage:

o Used to store sensitive or app-specific data, such as SharedPreferences, app


databases, or files that need to be private.

o Example:

java

Copy code

FileOutputStream fos = openFileOutput("myfile.txt", Context.MODE_PRIVATE);

fos.write(data.getBytes());

fos.close();

 External Storage:

o Used for media files like photos, videos, and audio, which need to be accessible
to the user and shared across apps.

o Example:

java

Copy code

File externalStorage = new File(Environment.getExternalStorageDirectory(), "myfile.txt");

FileOutputStream fos = new FileOutputStream(externalStorage);

fos.write(data.getBytes());

fos.close();

8. Mounting and Unmounting

 Internal Storage:
o Internal storage is always mounted and available as long as the device is on.

 External Storage:

o External storage can be manually unmounted, meaning it can be removed or


safely ejected, especially in the case of removable storage (like SD cards).

Summary Table:

Feature Internal Storage External Storage


Location Built-in storage, non- Removable, such as SD cards
removable
Security More secure, app data is Less secure, publicly
private accessible
Capacity Limited and fixed Larger and expandable
Performa Faster read/write speeds Slower, especially with SD
nce cards
Durability More durable, part of the Prone to wear and physical
device damage
Usage Sensitive app data, system Media files, user data
files
Lifetime Longer lifespan Limited read/write cycles
Unmounti Cannot be unmounted Can be unmounted manually
ng
Conclusion:

 Internal Storage is best suited for storing app-specific, sensitive, or system-related


data that needs to be private and secure. It is more reliable and faster but has limited
capacity.

 External Storage is better for storing large files like images, videos, and audio that
need to be shared between apps and can be expanded with additional storage media
(e.g., SD cards). However, it is less secure and can be prone to performance and
durability issues.

What is SQLite database? How to provide database


connection using SQLite database.
What is SQLite?
 SQLite is a lightweight, serverless, self-contained, and highly
reliable SQL database engine. It is widely used due to its simplicity, ease of setup and
zero-configuration nature.

 SQLite is an in-process library that implements a self-contained, serverless, zero-


configuration, transactional SQL database engine. It is a popular choice as an
embedded database for local/client storage in application software such as web
browsers. It is also used in many other applications that need a lightweight, embedded
database.

 SQLite is ACID-compliant and implements most of the SQL standards, using a


dynamically and weakly typed SQL syntax that does not guarantee domain integrity.
 To use SQLite in a C/C++ program, you can use the SQLite3 API, which provides a
lightweight, simple, self-contained, high-reliability, full-featured, and SQL database
engine. The API is implemented as a library of C functions that can be called from your
program.

 One of the main benefits of using SQLite is that it is very easy to get started with. To
create a new database in SQLite, you simply need to create a new file on your
filesystem and connect to it using the SQLite3 API.

Database connection using SQLite database


To provide a database connection using SQLite in an Android application, you will typically
follow these steps:

1. Create a Database Helper Class: This class will extend SQLiteOpenHelper and
manage database creation, version management, and upgrading.

2. Define the Database Schema: You will define the database structure (tables,
columns) in this class.

3. Opening/Accessing the Database: The database can be accessed in read or write


mode using SQLiteDatabase.

4. Performing CRUD Operations: You can insert, update, delete, and query data from
the database using SQLite queries or ContentValues.

Here's a step-by-step guide to creating an SQLite database connection in an Android


application:

1. Create SQLite Database Helper Class

First, create a class that extends SQLiteOpenHelper. This class will help in creating and
managing the database.

package com.example.mydatabaseapp;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

// Database name and version

private static final String DATABASE_NAME = "UserDB";

private static final int DATABASE_VERSION = 1;

// Table and column names

public static final String TABLE_USERS = "users";

public static final String COLUMN_ID = "_id";


public static final String COLUMN_NAME = "name";

public static final String COLUMN_EMAIL = "email";

// SQL query to create the table

private static final String CREATE_TABLE_USERS =

"CREATE TABLE " + TABLE_USERS + " (" +

COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

COLUMN_NAME + " TEXT, " +

COLUMN_EMAIL + " TEXT);";

// Constructor

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

// Create the table when the database is created

db.execSQL(CREATE_TABLE_USERS);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// Drop old tables if they exist and recreate them

db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);

onCreate(db);

2. Opening and Accessing the Database

To perform operations on the database, you will need to create an instance of the
DatabaseHelper class and get a readable or writable database object.

For instance, inside an activity or service, you can open the database:

DatabaseHelper dbHelper = new DatabaseHelper(context);

SQLiteDatabase db = dbHelper.getWritableDatabase(); // For write operations


// Or use getReadableDatabase() for read-only operations

3. CRUD Operations on the Database

Here is how to perform CRUD (Create, Read, Update, Delete) operations:

a. Insert Data

To insert data into the database, you will typically use SQLiteDatabase.insert() method or
ContentValues to insert key-value pairs.

ContentValues values = new ContentValues();

values.put(DatabaseHelper.COLUMN_NAME, "John Doe");

values.put(DatabaseHelper.COLUMN_EMAIL, "[email protected]");

SQLiteDatabase db = dbHelper.getWritableDatabase();

long rowId = db.insert(DatabaseHelper.TABLE_USERS, null, values);

if (rowId != -1) {

// Data inserted successfully

b. Query Data

You can query data using SQLiteDatabase.query() or using raw SQL queries with
SQLiteDatabase.rawQuery().

// Example: Query all users

String[] columns = {DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_NAME,


DatabaseHelper.COLUMN_EMAIL};

SQLiteDatabase db = dbHelper.getReadableDatabase();

Cursor cursor = db.query(DatabaseHelper.TABLE_USERS, columns, null, null, null, null, null);

if (cursor != null) {

while (cursor.moveToNext()) {

String name =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));

String email =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_EMAIL));

// Use the retrieved data

cursor.close();

}
c. Update Data

To update data, you can use the SQLiteDatabase.update() method:

ContentValues values = new ContentValues();

values.put(DatabaseHelper.COLUMN_NAME, "Jane Doe");

values.put(DatabaseHelper.COLUMN_EMAIL, "[email protected]");

String whereClause = DatabaseHelper.COLUMN_ID + "=?";

String[] whereArgs = {"1"}; // Update user with ID 1

SQLiteDatabase db = dbHelper.getWritableDatabase();

int rowsUpdated = db.update(DatabaseHelper.TABLE_USERS, values, whereClause,


whereArgs);

if (rowsUpdated > 0) {

// Data updated successfully

d. Delete Data

To delete data, you can use SQLiteDatabase.delete() method:

String whereClause = DatabaseHelper.COLUMN_ID + "=?";

String[] whereArgs = {"1"}; // Delete user with ID 1

SQLiteDatabase db = dbHelper.getWritableDatabase();

int rowsDeleted = db.delete(DatabaseHelper.TABLE_USERS, whereClause, whereArgs);

if (rowsDeleted > 0) {

// Data deleted successfully

4. Closing the Database

Don't forget to close the database when you are done with it to avoid memory leaks:

db.close(); // Close the database connection

5. Complete Example Code

Here is the complete example that demonstrates how to use SQLiteOpenHelper to manage
database connections and perform CRUD operations.

DatabaseHelper.java
package com.example.mydatabaseapp;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.content.ContentValues;

import android.database.Cursor;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "UserDB";

private static final int DATABASE_VERSION = 1;

public static final String TABLE_USERS = "users";

public static final String COLUMN_ID = "_id";

public static final String COLUMN_NAME = "name";

public static final String COLUMN_EMAIL = "email";

private static final String CREATE_TABLE_USERS =

"CREATE TABLE " + TABLE_USERS + " (" +

COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

COLUMN_NAME + " TEXT, " +

COLUMN_EMAIL + " TEXT);";

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(CREATE_TABLE_USERS);

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);

onCreate(db);

public void addUser(String name, String email) {

ContentValues values = new ContentValues();

values.put(COLUMN_NAME, name);

values.put(COLUMN_EMAIL, email);

SQLiteDatabase db = getWritableDatabase();

db.insert(TABLE_USERS, null, values);

db.close();

public Cursor getAllUsers() {

SQLiteDatabase db = getReadableDatabase();

return db.query(TABLE_USERS, null, null, null, null, null, null);

MainActivity.java

package com.example.mydatabaseapp;

import android.database.Cursor;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

DatabaseHelper dbHelper;

TextView textView;
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

dbHelper = new DatabaseHelper(this);

textView = findViewById(R.id.textView);

Button btnAddUser = findViewById(R.id.btnAddUser);

Button btnShowUsers = findViewById(R.id.btnShowUsers);

btnAddUser.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

dbHelper.addUser("John Doe", "[email protected]");

});

btnShowUsers.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Cursor cursor = dbHelper.getAllUsers();

StringBuilder stringBuilder = new StringBuilder();

while (cursor.moveToNext()) {

String name =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));

String email =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_EMAIL));

stringBuilder.append("Name: ").append(name).append(", Email:


").append(email).append("\n");

textView.setText(stringBuilder.toString());

cursor.close();
}

});

Conclusion

 SQLiteOpenHelper helps in creating, upgrading, and managing the database.

 You can perform various operations such as inserting, reading, updating, and
deleting data.

 Always remember to close the database connection to avoid memory leaks.

With this approach, you can easily integrate SQLite database operations in your Android app
for local data storage.

What is SQLite database? Write code for adding, updating and


removing data from SQLite database.
Covered above

Write an android application for login & registration using


SQLite database connectivity.
To create a simple Android application for Login and Registration using SQLite database
connectivity, follow these steps:

1. Create a Database Helper Class: This class will help you create and manage the
SQLite database.

2. Create Registration and Login Screens: UI to collect the user’s information and
authenticate the user.

3. Store User Data: Use SQLite to store user information during registration.

4. Authenticate Users: During login, authenticate the entered credentials against the
database.

Below is the full implementation of the app:

1. Database Helper Class

First, we need to create a helper class to manage database creation and operations.

DatabaseHelper.java

java

Copy code

package com.example.loginregisterapp;
import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "UserDB";

private static final int DATABASE_VERSION = 1;

public static final String TABLE_USERS = "users";

public static final String COLUMN_ID = "_id";

public static final String COLUMN_USERNAME = "username";

public static final String COLUMN_PASSWORD = "password";

private static final String CREATE_TABLE_USERS =

"CREATE TABLE " + TABLE_USERS + " (" +

COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +

COLUMN_USERNAME + " TEXT, " +

COLUMN_PASSWORD + " TEXT);";

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase db) {

// Create the users table

db.execSQL(CREATE_TABLE_USERS);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


// Drop the existing table and create a new one

db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);

onCreate(db);

// Insert user data into the database (for registration)

public boolean addUser(String username, String password) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues contentValues = new ContentValues();

contentValues.put(COLUMN_USERNAME, username);

contentValues.put(COLUMN_PASSWORD, password);

long result = db.insert(TABLE_USERS, null, contentValues);

db.close();

return result != -1; // If the result is -1, insertion failed

// Check if a user exists (for login)

public boolean checkUser(String username, String password) {

SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_USERS, null, COLUMN_USERNAME + "=? AND " +


COLUMN_PASSWORD + "=?",

new String[]{username, password}, null, null, null);

boolean exists = cursor != null && cursor.getCount() > 0;

cursor.close();

return exists;

2. Registration Activity

This activity will allow the user to register by entering a username and password, which will
be stored in the SQLite database.

RegisterActivity.java

java
Copy code

package com.example.loginregisterapp;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class RegisterActivity extends AppCompatActivity {

EditText usernameInput, passwordInput;

Button registerButton;

DatabaseHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_register);

usernameInput = findViewById(R.id.usernameInput);

passwordInput = findViewById(R.id.passwordInput);

registerButton = findViewById(R.id.registerButton);

dbHelper = new DatabaseHelper(this);

registerButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String username = usernameInput.getText().toString().trim();

String password = passwordInput.getText().toString().trim();


// Validate input

if (username.isEmpty() || password.isEmpty()) {

Toast.makeText(RegisterActivity.this, "Please enter both username and


password", Toast.LENGTH_SHORT).show();

} else {

// Add user to the database

boolean isInserted = dbHelper.addUser(username, password);

if (isInserted) {

Toast.makeText(RegisterActivity.this, "Registration successful!",


Toast.LENGTH_SHORT).show();

startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

} else {

Toast.makeText(RegisterActivity.this, "Registration failed! Try again.",


Toast.LENGTH_SHORT).show();

});

3. Login Activity

This activity will authenticate the user by checking their credentials against the database.

LoginActivity.java

java

Copy code

package com.example.loginregisterapp;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {

EditText usernameInput, passwordInput;

Button loginButton, registerButton;

DatabaseHelper dbHelper;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

usernameInput = findViewById(R.id.usernameInput);

passwordInput = findViewById(R.id.passwordInput);

loginButton = findViewById(R.id.loginButton);

registerButton = findViewById(R.id.registerButton);

dbHelper = new DatabaseHelper(this);

loginButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String username = usernameInput.getText().toString().trim();

String password = passwordInput.getText().toString().trim();

// Validate input

if (username.isEmpty() || password.isEmpty()) {

Toast.makeText(LoginActivity.this, "Please enter both username and password",


Toast.LENGTH_SHORT).show();

} else {

// Check if the user exists in the database

boolean isUserValid = dbHelper.checkUser(username, password);

if (isUserValid) {

Toast.makeText(LoginActivity.this, "Login successful!",


Toast.LENGTH_SHORT).show();
// Proceed to main activity or dashboard

} else {

Toast.makeText(LoginActivity.this, "Invalid username or password",


Toast.LENGTH_SHORT).show();

});

registerButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Redirect to the Registration activity

startActivity(new Intent(LoginActivity.this, RegisterActivity.class));

});

4. XML Layout Files

activity_login.xml

xml

Copy code

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<EditText

android:id="@+id/usernameInput"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Username" />
<EditText

android:id="@+id/passwordInput"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Password"

android:inputType="textPassword" />

<Button

android:id="@+id/loginButton"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Login" />

<Button

android:id="@+id/registerButton"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Register" />

</LinearLayout>

activity_register.xml

xml

Copy code

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

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

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<EditText

android:id="@+id/usernameInput"

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

android:hint="Username" />

<EditText

android:id="@+id/passwordInput"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Password"

android:inputType="textPassword" />

<Button

android:id="@+id/registerButton"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Register" />

</LinearLayout>

5. MainActivity (Optional)

You may create a MainActivity that will be launched after successful login. For simplicity, we
won’t dive into it here.

6. AndroidManifest.xml

Don't forget to add your activities in the AndroidManifest.xml.

xml

Copy code

<activity android:name=".LoginActivity" />

<activity android:name=".RegisterActivity" />

Conclusion

1. Database Helper handles the creation, management, and operations (add, check) of
the SQLite database.

2. Registration stores the user data, while Login authenticates the user.

3. You can enhance this basic app with more features, such as password hashing,
validation checks, and UI improvements.

This simple app demonstrates SQLite-based login and registration functionalities in Android.
How to Store and Retrieve all contacts from the Table Using
Database Programmatically. Explain?
Covered above

Define SQLite. Explain example table for SQLite store data in


tables.
Covered above

What is a Cursor? Explain cursor classes and methods.


Cursors
Cursors are what contain the result set of a query made against a database in Android.
The Cursor class has an API that allows an app to read (in a type-safe manner) the columns
that were returned from the query as well as iterate over the rows of the result set.

Reading Cursor Data

Once a cursor has been returned from a database query, an app needs to iterate over the
result set and read the column data from the cursor. Internally, the cursor stores the rows of
data returned by the query along with a position that points to the current row of data in the
result set. When a cursor is returned from a query() method, its position points to the
spot before the first row of data. This means that before any rows of data can be read from
the cursor, the position must be moved to point to a valid row of data.

The Cursor class provides the following methods to manipulate its internal position:

 boolean Cursor.move(int offset): Moves the position by the given offset

 boolean Cursor.moveToFirst(): Moves the position to the first row

 boolean Cursor.moveToLast(): Moves the position to the last row

 boolean Cursor.moveToNext(): Moves the cursor to the next row relative to the current
position

 boolean Cursor.moveToPosition(int position): Moves the cursor to the specified position

 Cursor.moveToPrevious(): Moves the cursor to the previous row relative to the current
position

Each move() method returns a boolean to indicate whether the operation was successful or
not. This flag is useful for iterating over the rows in a cursor.

Listing 5.10 shows the code to read data from a cursor containing all the data from
the people table.

Listing 5.10 Reading Cursor Data

SQLiteDatabase db = getDatabase();

String[] columns = {"first_name",

"last_name",
"id"};

Cursor cursor = db.query("people",

columns,

null,

null,

null,

null,

null);

while(cursor.moveToNext()) {

int index;

index = cursor.getColumnIndexOrThrow("first_name");

String firstName = cursor.getString(index);

index = cursor.getColumnIndexOrThrow("last_name");

String lastName = cursor.getString(index);

index = cursor.getColumnIndexOrThrow("id");

long id = cursor.getLong(index);

//... do something with data

The code in Listing 5.10 uses a while loop to iterate over the rows in the cursor returned from
the query() method. This pattern is useful if the code performing the iteration “controls” the
cursor and has sole access to it. If other code can access the cursor (for example, if the
cursor is passed into a method as a parameter), the cursor should also be set to a known
position as the current position may not be the position ahead of the first row.

Once the cursor’s position is pointing to a valid row, the columns of the row can be read from
the cursor. To read the data, the code in Listing 5.10 uses two methods from the cursor
class: Cursor.getColumnIndexOrThrow() and one of the type get() methods from
the Cursor class.

The Cursor.getColumnIndexOrThrow() method takes a String parameter that indicates which


column to read from. This String value needs to correspond to one of the strings in
the columns parameter that was passed to the query() method. Recall that
the columns parameter determines what table columns are part of the result
set. Cursor.getColumnIndexOrThrow()throws an exception if the column name does not exist
in the cursor. This usually indicates that the column was not part of the columns parameter of
the query(). The Cursor class also contains a Cursor.getColumnIndex() method that does not
throw an exception if the column name is not found.
Instead, Cursor.getColumnIndex() returns a -1 value to represent an error.

Once the column index is known, it can be passed to one of the cursor’s get() methods to
return the typed data of the row. The get() methods return the data from the column in the
row which can then be used by the app. The Cursor class contains the following methods for
retrieving data from a row:

 byte[] Cursor.getBlob(int columnIndex): Returns the value as a byte[]

 double Cursor.getDouble(int columnIndex): Returns the value as a double

 float Cursor.getFloat(int columnIndex): Returns the value as a float

 int Cursor.getInt(int columnIndex): Returns the value as an int

 long Cursor.getLong(int columnIndex): Returns the value as a long

 short Cursor.getShort(int columnIndex): Returns the value as a short

 String Cursor.getString(int columnIndex): Returns the value as a String

Managing the Cursor

The internals of a cursor can contain a lot of resources such as all the data returned from the
query along with a connection to the database. Because of this, it is important to handle a
cursor appropriately and tell it to clean up when it is no longer in use to prevent memory
leaks. To perform the cleanup, the Cursor class contains the Cursor.close() method, which
needs to be called when an activity or fragment no longer needs the cursor.

In versions of Android before 3.0, cursor maintenance was left to developers. They either had
to handle the closing of the cursor themselves or had to make sure they informed an activity
that it was using a cursor so the activity would close the cursor at an appropriate time.

Android 3.0 introduced the loader framework that takes care of managing cursors for
activities/fragments. To support older versions of Android, the loader framework has also
been backported and added to the support library. When using the loader framework, apps
no longer need to worry about calling Cursor.close() or informing an activity/fragment of a
cursor that it needs to manage.

What is Content Provider? What are the Operations supported


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

Content URI

Content URI(Uniform Resource Identifier) is the key concept of Content providers. To


access the data from a content provider, URI is used as a query string.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

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

Details of different parts of Content URI:

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

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

 optionalPath – Specifies the type of data provided by the content provider. It is


essential as this part helps content providers to support different types of data that are
not related to each other like audio and video files.

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


particular record.

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


based URI.

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

Operations in Content Provider

Four fundamental operations are possible in Content Provider


namely Create , Read , Update , and Delete . These operations are often termed as CRUD
operations .
 Create: Operation to create data in a content provider.

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

 Update: To modify existing data.

 Delete: To remove existing data from the storage.

Working of the Content Provider

UI components of android applications like Activity and Fragments use an


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

Creating a Content Provider

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

 Create a class in the same directory where the that MainActivity file resides and this
class must extend the ContentProvider base class.

 To access the content, define a content provider URI address.

 Create a database to store the application data.

 Implement the six abstract methods of ContentProvider class.

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

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

Abstract Description
Method
query() A method that accepts arguments and fetches the data
from the
desired table. Data is retired as a cursor object.
insert() To insert a new row in the database of the content
provider.
It returns the content URI of the inserted row.
update() This method is used to update the fields of an existing
row.
It returns the number of rows updated.
delete() This method is used to delete the existing rows.
It returns the number of rows deleted.
getType() This method returns the Multipurpose Internet Mail
Extension(MIME)
type of data to the given Content URI.
onCreate() As the content provider is created, the android system
calls
this method immediately to initialise the provider.
Example

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

Note: Following steps are performed on Android Studio version 4.0

Creating a Content Provider:

Step 1: Create a new project

1. Click on File, then New => New Project.

2. Select language as Java/Kotlin.

3. Choose empty activity as a template

4. Select the minimum SDK as per your need.

Step 2: Modify the strings.xml file

All the strings used in the activity are stored here.

<resources>

<string name="app_name">Content_Provider_In_Android</string>

<string name="hintText">Enter User Name</string>

<string name="heading">Content Provider In Android</string>

<string name="insertButtontext">Insert Data</string>

<string name="loadButtonText">Load Data</string>

</resources>

Step 3: Creating the Content Provider class

1. Click on File, then New => Other => ContentProvider.

2. Name the ContentProvider

3. Define authority (it can be anything for example “com.demo.user.provider” )

4. Select Exported and Enabled option

5. Choose the language as Java/Kotlin


This class extends the ContentProvider base class and override the six abstract methods.
Below is the complete code to define a content provider.

package com.example.contentprovidersinandroid;

import android.content.ContentProvider;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.Context;

import android.content.UriMatcher;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteException;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteQueryBuilder;

import android.net.Uri;

import java.util.HashMap;

public class MyContentProvider extends ContentProvider {

public MyContentProvider() {

// defining authority so that other application can access it

static final String PROVIDER_NAME = "com.demo.user.provider";

// defining content URI

static final String URL = "content://" + PROVIDER_NAME + "/users";

// parsing the content URI

static final Uri CONTENT_URI = Uri.parse(URL);

static final String id = "id";

static final String name = "name";

static final int uriCode = 1;

static final UriMatcher uriMatcher;


private static HashMap<String, String> values;

static {

// to match the content URI

// every time user access table under content provider

uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

// to access whole table

uriMatcher.addURI(PROVIDER_NAME, "users", uriCode);

// to access a particular row

// of the table

uriMatcher.addURI(PROVIDER_NAME, "users/*", uriCode);

@Override

public String getType(Uri uri) {

switch (uriMatcher.match(uri)) {

case uriCode:

return "vnd.android.cursor.dir/users";

default:

throw new IllegalArgumentException("Unsupported URI: " + uri);

// creating the database

@Override

public boolean onCreate() {

Context context = getContext();

DatabaseHelper dbHelper = new DatabaseHelper(context);

db = dbHelper.getWritableDatabase();

if (db != null) {

return true;

return false;
}

@Override

public Cursor query(Uri uri, String[] projection, String selection,

String[] selectionArgs, String sortOrder) {

SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

qb.setTables(TABLE_NAME);

switch (uriMatcher.match(uri)) {

case uriCode:

qb.setProjectionMap(values);

break;

default:

throw new IllegalArgumentException("Unknown URI " + uri);

if (sortOrder == null || sortOrder == "") {

sortOrder = id;

Cursor c = qb.query(db, projection, selection, selectionArgs, null,

null, sortOrder);

c.setNotificationUri(getContext().getContentResolver(), uri);

return c;

// adding data to the database

@Override

public Uri insert(Uri uri, ContentValues values) {

long rowID = db.insert(TABLE_NAME, "", values);

if (rowID > 0) {

Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);

getContext().getContentResolver().notifyChange(_uri, null);

return _uri;

throw new SQLiteException("Failed to add a record into " + uri);

}
@Override

public int update(Uri uri, ContentValues values, String selection,

String[] selectionArgs) {

int count = 0;

switch (uriMatcher.match(uri)) {

case uriCode:

count = db.update(TABLE_NAME, values, selection, selectionArgs);

break;

default:

throw new IllegalArgumentException("Unknown URI " + uri);

getContext().getContentResolver().notifyChange(uri, null);

return count;

@Override

public int delete(Uri uri, String selection, String[] selectionArgs) {

int count = 0;

switch (uriMatcher.match(uri)) {

case uriCode:

count = db.delete(TABLE_NAME, selection, selectionArgs);

break;

default:

throw new IllegalArgumentException("Unknown URI " + uri);

getContext().getContentResolver().notifyChange(uri, null);

return count;

// creating object of database

// to perform query

private SQLiteDatabase db;

// declaring name of the database


static final String DATABASE_NAME = "UserDB";

// declaring table name of the database

static final String TABLE_NAME = "Users";

// declaring version of the database

static final int DATABASE_VERSION = 1;

// sql query to create the table

static final String CREATE_DB_TABLE = " CREATE TABLE " + TABLE_NAME

+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "

+ " name TEXT NOT NULL);";

// creating a database

private static class DatabaseHelper extends SQLiteOpenHelper {

// defining a constructor

DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

// creating a table in the database

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(CREATE_DB_TABLE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// sql query to drop a table

// having similar name

db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);


onCreate(db);

Step 4: Design the activity_main.xml layout

One Textview , EditText field, two Buttons , and a Textview to display the stored
data will be added in the activity using the below code.

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

android:background="#168BC34A"

tools:context=".MainActivity">

<LinearLayout

android:id="@+id/linearLayout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:orientation="vertical"

app:layout_constraintBottom_toTopOf="@+id/imageView"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintVertical_bias="0.13"

tools:ignore="MissingConstraints">

<TextView

android:id="@+id/textView1"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:layout_marginTop="40dp"

android:layout_marginBottom="70dp"

android:fontFamily="@font/roboto"

android:text="@string/heading"

android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Large"

android:textColor="@android:color/holo_green_dark"

android:textSize="36sp"

android:textStyle="bold" />

<EditText

android:id="@+id/textName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="20dp"

android:layout_marginEnd="20dp"

android:layout_marginBottom="40dp"

android:fontFamily="@font/roboto"

android:hint="@string/hintText" />

<Button

android:id="@+id/insertButton"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginStart="20dp"

android:layout_marginTop="10dp"

android:layout_marginEnd="20dp"

android:layout_marginBottom="20dp"

android:background="#4CAF50"

android:fontFamily="@font/roboto"

android:onClick="onClickAddDetails"

android:text="@string/insertButtontext"

android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"

android:textStyle="bold" />

<Button

android:id="@+id/loadButton"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginStart="20dp"

android:layout_marginTop="10dp"

android:layout_marginEnd="20dp"

android:layout_marginBottom="20dp"

android:background="#4CAF50"

android:fontFamily="@font/roboto"

android:onClick="onClickShowDetails"

android:text="@string/loadButtonText"

android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Display1"

android:textColor="#FFFFFF"

android:textStyle="bold" />

<TextView

android:id="@+id/res"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="20dp"

android:layout_marginEnd="20dp"

android:clickable="false"

android:ems="10"

android:fontFamily="@font/roboto"

android:textColor="@android:color/holo_green_dark"

android:textSize="18sp"

android:textStyle="bold" />

</LinearLayout>
<ImageView

android:id="@+id/imageView"

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:srcCompat="@drawable/banner" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 5: Modify the MainActivity file

Button functionalities will be defined in this file. Moreover, the query to be performed while
inserting and fetching the data is mentioned here. Below is the complete code.

JavaKotlin

package com.example.contentprovidersinandroid;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.view.MotionEvent;

import android.view.View;

import android.view.inputmethod.InputMethodManager;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

@Override

public boolean onTouchEvent(MotionEvent event) {

InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

return true;

public void onClickAddDetails(View view) {

// class to add values in the database

ContentValues values = new ContentValues();

// fetching text from user

values.put(MyContentProvider.name, ((EditText)
findViewById(R.id.textName)).getText().toString());

// inserting into database through content URI

getContentResolver().insert(MyContentProvider.CONTENT_URI, values);

// displaying a toast message

Toast.makeText(getBaseContext(), "New Record Inserted", Toast.LENGTH_LONG).show();

public void onClickShowDetails(View view) {

// inserting complete table details in this text field

TextView resultView= (TextView) findViewById(R.id.res);

// creating a cursor object of the

// content URI
Cursor cursor =
getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null,
null, null);

// iteration of the cursor

// to print whole table

if(cursor.moveToFirst()) {

StringBuilder strBuild=new StringBuilder();

while (!cursor.isAfterLast()) {

strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));

cursor.moveToNext();

resultView.setText(strBuild);

else {

resultView.setText("No Records Found");

Step 6: Modify the AndroidManifest file

The AndroidManifest file must contain the content provider name, authorities, and
permissions which enable the content provider to be accessed by other applications.

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

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

package="com.example.content_provider_in_android">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<provider
android:name="com.example.contentprovidersinandroid.MyContentProvider"

android:authorities="com.demo.user.provider"

android:enabled="true"

android:exported="true"></provider>

<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>

<meta-data

android:name="preloaded_fonts"

android:resource="@array/preloaded_fonts" />

</application>

</manifest>

Creating another application to access the Content Provider:

Step 1: Create a new Project

1. Click on File, then New => New Project.

2. Select language as Java/Kotlin.

3. Choose empty activity as a template

4. Select the minimum SDK as per your need.

Step 2: Modify strings.xml file

All the strings used in the activity are stored in this file.

<resources>

<string name="app_name">Accessing_Content_Provider</string>

<string name="heading">Accessing data of Content Provider</string>

<string name="loadButtonText">Load Data</string>

</resources>

Step 3: Designing the activity_main.xml layout


Two TextView are added in the activity, one for heading and one to display the stored data in
a content provider. One Button is also added to receive the command to display data. Below
is the code to implement this design.

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

android:background="#168BC34A"

tools:context=".MainActivity">

<LinearLayout

android:id="@+id/linearLayout"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerVertical="true"

android:orientation="vertical"

app:layout_constraintBottom_toTopOf="@+id/imageView"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintVertical_bias="0.13"

tools:ignore="MissingConstraints">

<TextView

android:id="@+id/textView1"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="40dp"

android:layout_marginBottom="70dp"

android:fontFamily="@font/roboto"

android:text="@string/heading"
android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Large"

android:textColor="@android:color/holo_green_dark"

android:textSize="36sp"

android:textStyle="bold" />

<Button

android:id="@+id/loadButton"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:layout_marginStart="20dp"

android:layout_marginTop="10dp"

android:layout_marginEnd="20dp"

android:layout_marginBottom="20dp"

android:background="#4CAF50"

android:fontFamily="@font/roboto"

android:onClick="onClickShowDetails"

android:text="@string/loadButtonText"

android:textAlignment="center"

android:textAppearance="@style/TextAppearance.AppCompat.Display1"

android:textColor="#FFFFFF"

android:textStyle="bold" />

<TextView

android:id="@+id/res"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="20dp"

android:layout_marginEnd="20dp"

android:clickable="false"

android:ems="10"

android:fontFamily="@font/roboto"

android:textColor="@android:color/holo_green_dark"
android:textSize="18sp"

android:textStyle="bold" />

</LinearLayout>

<ImageView

android:id="@+id/imageView"

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:srcCompat="@drawable/banner" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Modify the MainActivity file

The ContentURI of the previous application is mentioned here and the same functions which
were used in the previous app to display the records will also be used here. Below is the
complete code:

JavaKotlin

package com.example.accessingcontentprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Uri CONTENT_URI = Uri.parse("content://com.demo.user.provider/users");


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

public void onClickShowDetails(View view) {

// inserting complete table details in this text field

TextView resultView= (TextView) findViewById(R.id.res);

// creating a cursor object of the

// content URI

Cursor cursor =
getContentResolver().query(Uri.parse("content://com.demo.user.provider/users"), null, null,
null, null);

// iteration of the cursor

// to print whole table

if(cursor.moveToFirst()) {

StringBuilder strBuild=new StringBuilder();

while (!cursor.isAfterLast()) {

strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));

cursor.moveToNext();

resultView.setText(strBuild);

else {

resultView.setText("No Records Found");

Output: Run on Emulator

Video Player
Step 5: Modify the AndroidManifest.xml file

Don’t forget to add <query> permission (API 30 and above).

For more details refer here .

<queries>

<package android:name="com.example.contentprovidersinandroid"/>

</queries>

<application>

</application>

How the packaging and deploying is done to make apps


available on play store?
Packaging and deploying an Android app to the Google Play Store involves several key
steps. The process ensures that your app is properly built, packaged, and prepared for
distribution. Here’s a detailed guide on how to package and deploy your app to the Play
Store:

1. Prepare Your App for Release

Before packaging your app, ensure it is ready for production and follows all necessary
guidelines for a smooth deployment.

 Test Thoroughly: Ensure your app works well on various devices and screen sizes.
Test functionality, usability, and performance.

 Remove Debugging Code: Ensure that debugging logs (e.g., Log.d() statements) and
any test code are removed from your app.

 Optimize Your App: This involves optimizing the app's size and performance (e.g.,
optimizing images, using ProGuard to shrink code, etc.).

 Check App Permissions: Verify that your app requests only the necessary
permissions and that they are clearly stated in the app's manifest.

 Update the Version Number: Update the version code and version name in the
build.gradle file.

android {

defaultConfig {

versionCode 2 // Increase with every new release

versionName "1.1" // App version


}

2. Generate a Signed APK or AAB

You need to sign your app to prove its authenticity and ownership before you can submit it to
the Play Store. The APK or AAB file will be signed using a private key.

a. Generate a Keystore File

If you don't have a keystore file, you need to create one. You can do this using the keytool
command or through Android Studio.

 Creating a Keystore in Android Studio:

1. Go to Build > Generate Signed Bundle / APK.

2. Choose Android App Bundle or APK and click Next.

3. Enter your key store path, key alias, and key password. These should be kept
secure.

4. After completing the required fields, Android Studio will create a keystore for
you.

b. Generate Signed APK or AAB in Android Studio

Once you have the keystore, you can generate a signed APK or AAB.

 In Android Studio:

1. Build > Generate Signed Bundle / APK.

2. Select either Android App Bundle (recommended by Google) or APK.

3. Choose your keystore file and enter the credentials (password, alias).

4. Click Next and select the build variant (usually release).

5. Click Finish to generate the signed APK or AAB file.

Note: The App Bundle (.aab) format is preferred by Google as it is more efficient in terms of
size and optimization, and it supports the Play Store's dynamic delivery.

3. Create a Developer Account

If you don’t already have a Google Developer account, you need to sign up. This involves:

 Going to the Google Play Console.

 Paying a one-time registration fee (currently $25 USD).

 Completing your account setup with required details (business info, tax info, etc.).

4. Prepare App Store Assets

You’ll need to provide several details and assets for your app’s Play Store listing.

 App Title: The name of your app (this will appear in the store).

 Short Description: A concise, clear description of your app's functionality (up to 80


characters).
 Full Description: A longer explanation of your app's features, functionality, and what
makes it special.

 Screenshots: At least 2-3 high-quality screenshots that show your app in action.

 App Icon: A high-quality 512x512 px icon (in PNG format) for your app.

 Feature Graphic: A 1024x500 px promotional graphic for your app.

 Video URL (optional): A YouTube video URL showing how your app works (optional
but recommended).

 Privacy Policy URL: If your app uses sensitive data, you must provide a privacy policy
URL.

5. Upload the APK/AAB to Google Play Console

Now you can upload the signed APK or AAB file to the Google Play Console:

1. Log in to the Google Play Console.

2. Select Create Application and choose the default language.

3. Fill out the app’s information (title, description, categorization, etc.).

4. Go to the Release section (under the "Release Management" or "App Releases" tab).

5. Select the track you want to publish on: Production, Beta, or Alpha.

6. Click Create Release and upload your APK or AAB file.

7. Fill in the release notes (what's new in this version).

8. Review all details and make sure your app is ready for release.

9. Save and proceed to the next step.

6. Set Up Pricing and Distribution

 Pricing: You can choose whether your app is Free or Paid. Note that once you set your
app to free, you can't change it to paid later.

 Countries: Select the countries or regions where your app will be available.

 Distribution Options: Choose whether your app should be available on specific


devices (e.g., tablets, phones) or in certain categories (e.g., education, lifestyle).

7. App Content and Rating

 Content Rating: Complete the questionnaire for content rating to ensure your app is
categorized correctly (e.g., E for everyone, T for teens).

 Target Audience: Declare the target audience of your app (e.g., children, adults).

 Privacy Policy: If your app collects sensitive information, you’ll need a privacy policy.
You must provide a link to it in the Play Store listing and your app’s settings page.

8. Submit the App for Review

Once you’ve filled out all the necessary information and uploaded your APK/AAB, submit
your app for review. Google Play will perform an automatic review, which may take a few
hours to several days depending on the complexity of your app.
 Google Play checks for compliance with their policies (e.g., app content, privacy
requirements, malware checks).

 You will be notified by email once the review is complete, and your app will either be
approved or rejected.

 If your app is rejected, you’ll receive feedback on what needs to be fixed.

9. Post-Launch Activities

After your app is approved and live on the Play Store, here are some post-launch activities:

 Monitor Performance: Use Google Play Console to track app downloads, crashes,
reviews, and other performance metrics.

 User Feedback: Regularly monitor and respond to user reviews, addressing any
concerns or feedback.

 Updates: When you release updates, always update the version number, provide new
features, and improve the app based on user feedback. Re-submit the new APK/AAB for
review.

Write a note on Android multimedia and android agents.


Multimedia Framework in Android
Android multimedia framework is designed to provide a reliable interface for java service. It is
a system that includes multimedia applications, frameworks, an OpenCore engine, hardware
devices for audio/video/ input, output devices also several core dynamic libraries such as
libmedia, libmediaplayservices, and so on.

The Media Server creates the corresponding media service to the multimedia application. The
communication between the media server and Libmedia forms a client-server model. The PV
player processes the media data stream by demuxing the media data to separate the
video/audio data stream, decode video/audio data, sync video, and audio time, and send the
decoded data out.

The Android Multimedia framework is a set of APIs for developers which enables them to
create a multimedia application on an android platform. This framework provides support for
audio, video, and images, which provides a range of features such as media playback,
recording, editing, streaming, etc.
Looking to become an expert in Android App Development? Whether you're a student or a
professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Components of Android Multimedia Framework

1. Media Codec

It provides low-level access to hardware and software codecs for encoding and decoding
audio and video data. Format of media codec/format, container, and network protocol
supported by the android platform-

 Container: It is used to store audio file format on a system, where data can be
manipulated to reduce the size or change the quality of audio.

 Audio Format: Any format or codec can be used including the ones provided by android
devices. However, it is recommended to use the specified file formats as per devices.

 Network Protocol: Protocols supported in audio and video playback are RTSP,
HTTP/HTTPS progressive streaming, and live streaming draft protocol.

Common media codec formats used in android multimedia applications include

 H.264: Widely used video codec format that provides high-quality compression and is
supported by most modern devices and software.

 AAC: Popular audio codec format that provides high-quality compression and is widely
supported by devices and software.

 MP3: Well-known audio codec format that provides good compression and is supported
by most devices and software.

 VP9: Video codec format that provides high-quality compression and is supported by
some modern devices and software.

 JPEG: Image codec format that provides good compression and is widely supported by
devices and software.

 PNG: Image codec format That provides lossless compression which is supported by
devices and software.

2. Media Player

It is a component in the multimedia framework that provides high-level access to the media
playback functionality of Android that enables developers to play audio/video files and
stream. It is also a core component of the Android multimedia framework that enables
developers to play audio and video files in their applications and provides a simple and
flexible API for playing media files from different sources. The sources are local files, network
streams, and content providers. Media player supports a wide range of audio and video
formats which includes MP3, AAC, WAV, MPEG-4, H.264, etc.

Some key features of media players are:

 Playback control: This helps in controlling media files by providing a range of methods
such as start(), pause(), stop(), and seekTo().

 Playback State: This feature informs the developer about the playback state by
providing functions that are onPrepared(), onCompletion(), and onError().
 Audio Focus: This feature comes into the picture when multiple audio sources are
playing simultaneously and the developer has to manage all of it.

 Media Streaming: The media player supports streaming media from various sources
such as HTTP, RTSP, and RTP so to handle the streaming media developers use
setDataSourse() method to set the source for streaming media and use the
prepareAsync() method to prepare the media player for asynchronous playback.

 Media Playback with the surface: To set the surface on which the video should be
rendered setSurface() is used.

3. Media Recorder

Provides high-level access to the media recording functionality of Android which allows
developers to capture audio/video data from a device’s microphone and camera. It provides a
simple and flexible API for recording media from different sources such as the device’s
microphone or camera. Features of the media recorder are:

 Recording control: This feature provides methods like start(), stop(), and reset() for
controlling the recording of media files.

 Recording state: This feature enables the user to notify about the state of recording by
using methods onInfo() and onError().

 Audio and Video Sources: This feature provides two methods setAudioSource and
setVideoSource() which enable developers to select appropriate audio and video
sources for their recordings.

 Audio and Video Encoding: For video formatting, this feature contains methods such as
setOutputFormat() method. setAudioEncoder() and setVideoEncoder() methods are
used to select appropriate encoding for audio and video.

4. Surface View

The surface provides a facility to play video content on android devices. It is a subclass of the
view class and provides a dedicated drawing surface for applications that need to display
video or graphics which are more complicated than simple views. Feature of Surface View:

 Drawing surface: This feature is used by developers to draw complex graphics or


display video frames.

 Efficient rendering: This is used when developers when designing efficient rendering is
needed and provides better performance compared to other View classes when
rendering large images or video frames.

 Compatibility with Android Graphics Framework: It is compatible with OpenGL ES, which
is a 3D graphics library that can be used to create advanced multimedia applications.

5. Audio Manager

Controls the overall audio settings such as volume and routing. It allows developers to
manage audio settings and control audio playback for various applications and devices.
Functions of Audio Manager:

 Controlling Audio Volume

 Managing Audio Routing

 Handling Audio Focus


 Monitoring audio States

6. Image Reader

Provides access to raw image data from a device’s camera or image sensors. It is a part of
the android Camera2 API and is available in Android API level 19 and higher. Function that
ImageReader class include:

 Capturing raw images

 Processing captured images

 Configuring capture settings

 Handling image buffers

Android Agents:
In the context of Android development, Android agents generally refer to specialized
software or components that perform specific tasks on an Android device, often running in
the background or being used for monitoring, automation, or network communication
purposes. These agents can either be applications or services that perform tasks
autonomously on behalf of a user, a system, or a developer. Below are some key aspects of
Android agents:

1. Definition of Android Agent

An Android agent is typically a background application or service running on an Android


device that is responsible for executing specific tasks like monitoring system performance,
handling network requests, automating processes, or collecting data. It might not have direct
interaction with the user but is used to enhance the functionality of the device.

2. Types of Android Agents

 Monitoring Agents: These agents monitor system performance or user activities.


Examples include apps that track battery usage, network traffic, or system resources.
Some system administrators or developers use such agents for debugging and
optimizing applications.

 Automation Agents: These agents are designed to automate tasks or perform certain
actions at specific times or based on conditions. For example, Tasker is an Android
automation tool that can act as an agent to automate actions like turning on Wi-Fi,
adjusting the volume, or sending messages based on user triggers.

 Network Agents: These agents work in the background to handle network operations
such as synchronizing data with a server, updating content, or ensuring secure
connections. They are crucial in apps that require continuous data syncing or cloud-
based operations, like email clients, social media apps, and messaging apps.

 Security Agents: These agents can monitor or enforce security policies on an Android
device. Examples of this are mobile device management (MDM) solutions, antivirus
agents, or privacy-focused apps that scan for threats, block malicious content, and
provide encryption services.

 App Monitoring Agents: Some developers use agents to monitor app performance,
track crashes, log system events, or collect crash reports. Libraries like Firebase
Crashlytics or Bugfender provide agents that work seamlessly in the background to
collect critical crash data for analysis.

3. Role of Android Agents in Security

Android agents are commonly used in enterprise environments to enforce security policies
on Android devices. These include:

 Mobile Device Management (MDM) solutions: These agents are deployed in


business environments to enforce security policies like encryption, remote wipe, app
whitelisting, and device tracking. Examples include AirWatch, MobileIron, and
Samsung Knox.

 Antivirus and Anti-malware Agents: Android security agents are employed to scan
for viruses, malware, and potential threats. Security apps like Norton Mobile
Security, McAfee Mobile Security, and Avast Mobile Security act as agents that
regularly check for malicious activity and offer real-time protection.

4. How Android Agents Work

 Background Services: Many Android agents work as services running in the


background. Services allow apps to continue performing tasks even when the app is not
in the foreground. For instance, an agent that tracks location data for an app might run
as a service in the background without the user having to interact with it.

 Broadcast Receivers: Android agents often use broadcast receivers to listen for
system events like screen unlock, Wi-Fi connection, or charging status. For example, an
agent that changes phone settings based on location can listen for the device's location
change through broadcast receivers.

 Job Scheduler: Some Android agents use the JobScheduler API or WorkManager to
schedule tasks that need to be performed periodically or under specific conditions. This
is particularly useful for tasks like syncing data or fetching updates.

5. Example Use Cases of Android Agents

 Battery Optimizers: Apps like Greenify act as agents to automatically manage and
optimize battery usage by hibernating apps running in the background when not in use,
helping to extend battery life.

 Security Monitoring: Apps like Cerberus act as a security agent to track and lock the
device if stolen, remotely wiping sensitive data or taking photos of the thief using the
front camera.

 Geolocation Services: Apps such as Google Maps or Uber use location tracking
agents to determine the user's current position for providing location-based services,
without requiring the user to manually input location data.

 Health and Fitness Apps: Google Fit or Samsung Health use agents to track
physical activity, sleep, and other health metrics by running background services that
use sensors such as accelerometers or GPS.

6. Advantages of Android Agents

 Efficiency: Android agents can help automate tasks, such as backing up data,
checking for updates, or adjusting settings based on conditions like location or battery
life.
 User Convenience: These agents enable smooth and seamless background tasks
without requiring the user to interact with them directly. For example, background sync
ensures that data is always up to date.

 Resource Management: By automating and offloading specific tasks, agents can help
optimize resource usage, such as saving battery or reducing network data usage.

7. Challenges with Android Agents

 Battery Drain: Some agents, especially those that track location, consume significant
battery power. Developers must ensure that agents are designed efficiently to avoid
excessive battery drain.

 Privacy Concerns: Since some agents collect sensitive data (like location, usage
statistics, or personal information), it is crucial for developers to ensure that user data
is handled securely and in compliance with privacy regulations (like GDPR).

 Background Task Limitations: Android's strict background execution policies,


especially with recent Android versions (like Doze Mode), can restrict how long agents
can run in the background, which may affect performance or functionality.

 App Approval: Apps using agents for background tasks (especially if the tasks are
perceived as intrusive or data-collecting) might face approval issues on the Google Play
Store due to privacy and security concerns.

Explain performance best practices in android location


mobility. What are the issues will face in location mobility?
Performance best practices in android location mobility
When working with location-based features in Android apps, performance optimization is
crucial for both efficient battery usage and providing a seamless user experience. Here are
the best practices for managing location-based features effectively in Android:

1. Minimize Location Requests

 Requesting Frequent Updates: Continuously requesting location updates drains


battery. You should minimize the frequency of location requests and request location
data only when necessary.

 Use getLastKnownLocation(): If your app can tolerate some stale data, use
getLastKnownLocation() to retrieve the last available location. This reduces battery
consumption since it doesn't require continuous location tracking.

2. Use the Appropriate Location Providers

 GPS vs. Network vs. Fused Location Provider: The FusedLocationProviderClient is


generally the best choice for location tracking because it intelligently combines GPS,
Wi-Fi, and cell data, prioritizing accuracy and efficiency.

o GPS: High accuracy but heavy on battery usage and performance. Use for
precise navigation or location-based actions.

o Network: Uses Wi-Fi and cell towers, less accurate but more power-efficient.
Great for general location-based services when high precision isn't required.
 FusedLocationProviderClient: This is a part of the Google Play Services API, which
offers more power-efficient location updates by intelligently switching between different
providers.

3. Set Location Request Parameters Appropriately

 Adjust Accuracy and Interval: Adjust the accuracy (LocationRequest.setPriority())


and interval (LocationRequest.setInterval()) based on the use case.

o High Accuracy: Use for navigation or critical tasks (GPS, high battery
consumption).

o Balanced Accuracy: Use for background tasks (e.g., using Wi-Fi and cell towers
for better battery efficiency).

o Low Power: Use when accuracy is not crucial (e.g., occasional updates,
background monitoring).

 Use the setFastestInterval(): If your app only needs rapid location updates for a
short time (e.g., during a user’s activity), use setFastestInterval() to get updates faster
but still control the max interval for updates.

4. Handle Background Location Properly

 Background Location Restrictions: Android 10 (API level 29) and later require apps
to request the ACCESS_BACKGROUND_LOCATION permission to access location data
while the app is in the background. To comply with best practices:

o Only request background location if absolutely necessary.

o Provide clear use cases for accessing background location (especially in the app's
UI and privacy policy).

 Use JobScheduler or WorkManager: For tasks that need to happen periodically in


the background (like tracking location), consider using JobScheduler or WorkManager.
These APIs help schedule jobs efficiently without draining the battery.

5. Use Geofencing

 Geofencing is an excellent alternative to continuous location tracking. If you only need


to know when a user enters or exits a specific area, use the geofence feature of the
GeofencingClient. This reduces battery consumption by only tracking location at key
moments, based on defined areas.

6. Handle Location Permissions Effectively

 Request location permissions at runtime (for Android 6.0 and above).

 Always check for appropriate permissions before trying to access location data
(ACCESS_FINE_LOCATION for precise location and ACCESS_COARSE_LOCATION for
approximate location).

 Be transparent with users about why you need their location and provide an easy way
to revoke the permissions.

7. Throttle Location Requests

 Use LocationRequest.setMaxWaitTime(): Instead of querying for location updates


constantly, use the setMaxWaitTime() method to throttle the request, reducing the
frequency of updates. This is especially useful in use cases where the app doesn't
require real-time accuracy.

8. Optimize for Battery and Resource Usage

 Background Updates: Use the system's ability to combine background tasks


efficiently. If your app doesn’t need precise location updates constantly, rely on
Android's Doze mode or App Standby to reduce background location tracking and
minimize battery consumption.

 Use BatteryOptimizations and Doze Mode: Make sure your app is optimized for
Android’s battery-saving features like Doze mode. Background tasks should be
designed to pause when the device is idle.

9. Use Proximity Alerts

 Use proximity alerts when you need to monitor whether the device enters a
region: These are a more efficient solution than continuous location tracking if your
use case revolves around detecting presence within a predefined area.

10. Test on Different Devices and Conditions

 Test your app on a variety of devices and network conditions (e.g., weak GPS signals,
Wi-Fi, etc.). This helps in identifying performance bottlenecks and adapting to real-
world usage patterns.

 Simulate poor GPS signals to test how your app behaves when location data is noisy or
unavailable.

11. Handling Location Data in the Background

 Use Foreground Services: For apps that require location tracking while in the
background (such as fitness apps), use a foreground service with a notification. This
ensures that the system knows the app is actively using location data and can manage
resources accordingly.

Issues will face in location mobility


Location-based services and mobility in mobile apps can encounter several challenges,
especially when dealing with dynamic environments where users are constantly moving.
These issues affect both user experience and technical performance, so it's important to be
aware of them. Here are the primary issues you'll face in location mobility:

1. Battery Consumption

 Continuous Location Tracking: Constantly tracking a user’s location (especially with


high accuracy, such as GPS) can quickly drain the device’s battery. The location APIs
consume significant power, and if updates are too frequent or the app is using high-
accuracy settings unnecessarily, battery life can be impacted.

 Background Location: Running location services in the background, especially


without user interaction, consumes more power. This is a common problem for apps
that track users even when they aren’t actively using the app.

2. Network Dependency

 Weak GPS Signal: GPS location services can be inaccurate or unavailable in areas
with poor satellite visibility, such as indoors, under dense tree cover, or in urban
canyons with tall buildings. Users may experience poor location accuracy or delays in
getting updated coordinates.

 Poor Network Connectivity: If the app relies on network-based location (such as cell
towers or Wi-Fi), weak or unavailable network signals will result in degraded accuracy
or no location updates. This is especially problematic in rural areas or places with
limited cellular/Wi-Fi coverage.

 Latency: Network delays or high latency can result in delays in receiving updated
location information. This is particularly important for real-time applications like
navigation or ride-hailing apps.

3. Location Accuracy

 Inaccurate GPS Coordinates: GPS can have varying degrees of accuracy depending
on the environment and the device. In areas with poor GPS reception, the accuracy can
degrade significantly, leading to erroneous location data.

 Trade-offs Between Accuracy and Power Consumption: In location mobility


applications, you need to balance location accuracy with battery usage. High-accuracy
location tracking (using GPS) is more power-hungry, while less accurate methods (such
as Wi-Fi or cellular location) conserve energy but may not be precise enough for certain
use cases.

4. Geofencing and Region Monitoring Challenges

 Entry/Exit Delays: When using geofencing for detecting when a user enters or exits a
particular region, the system may have delays in detecting these events, especially in
areas with poor GPS or network connectivity. This can lead to missed or delayed
triggers for geofencing actions.

 Accuracy of Geofences: The accuracy of geofencing is also dependent on the


underlying location services. If location data is inaccurate, the geofence event (entering
or exiting a region) might be triggered incorrectly.

5. Privacy and Security

 Location Data Privacy Concerns: Collecting and storing users’ location data raises
privacy concerns. Users may be hesitant to share their real-time location, and
mishandling this data could lead to security breaches or violate privacy laws (e.g.,
GDPR, CCPA). Apps must be transparent about location data collection and provide
adequate security measures.

 Permission Management: Users must be prompted for location permissions at


runtime (on Android 6.0 and higher). Handling permissions incorrectly or asking for
unnecessary permissions can lead to poor user trust and app uninstalls.

6. Legal and Regulatory Issues

 Compliance with Privacy Laws: In many regions, there are strict regulations about
how location data can be used and stored (e.g., the EU’s General Data Protection
Regulation (GDPR), California Consumer Privacy Act (CCPA)). Developers need to ensure
compliance with these laws by implementing consent management systems and
transparent data usage policies.

 Restricted Background Location Access: Recent Android versions (e.g., Android 10


and later) require apps to request additional permissions to access location data while
running in the background. These restrictions may limit app functionality if not
managed carefully.

7. User Experience Issues

 Accuracy Expectations vs. Reality: Users may have expectations of perfect, real-
time location accuracy. However, due to environmental factors (e.g., GPS interference,
weather conditions, device limitations), the actual accuracy may not meet
expectations, leading to dissatisfaction.

 Disruptive Notifications or Alerts: When apps use location-based features like


geofencing or push notifications based on movement, excessive or poorly timed alerts
can frustrate users, leading to uninstalls.

 Lack of Contextual Awareness: Apps may struggle to adapt to the user’s context.
For example, location updates may not consider whether the user is driving, walking, or
stationary, which may affect how the app responds to those updates.

8. Data Storage and Processing

 Storing and Processing Location Data: Constantly tracking and storing location
data for every user can create storage and processing challenges, especially if the app
operates at scale. Handling large amounts of data can lead to increased database size
and more complex query and data processing operations, potentially slowing down the
app.

 Real-Time Processing: Some applications, such as ride-sharing or delivery apps,


require processing and updating locations in real-time to match users with drivers or
optimize routes. This can result in performance bottlenecks, particularly when dealing
with a large volume of users or real-time data updates.

9. Device-Specific Variability

 Differences in GPS Hardware: Different devices may have varying quality of GPS
hardware, leading to inconsistencies in location accuracy and update frequency across
devices. Older or budget devices may have less accurate GPS chips, which can affect
app performance.

 Device Manufacturers' Customizations: Manufacturers often customize the Android


OS, which can lead to variability in how location services are implemented across
different devices. This can result in inconsistent performance or bugs that are device-
specific.

10. Compatibility Issues

 OS and API Changes: Android updates can introduce changes to location APIs and
permissions, causing compatibility issues with existing apps. For instance, new
restrictions around background location access (introduced in Android 10 and later) can
break apps that previously accessed location in the background without additional
permissions.

 App Fragmentation: Android devices run different versions of the operating system,
so apps need to ensure compatibility with a wide range of devices, screen sizes, and
configurations. Handling these variations while maintaining consistent location
functionality can be challenging.

11. Location Spoofing


 GPS Spoofing: Some users might spoof their location (using apps or device
modifications), which can affect location-based services. Apps that rely on precise
location data for authentication or geo-fencing (e.g., for security, gaming, or location-
based services) may be vulnerable to location spoofing attacks.

Solutions and Mitigations

To address these issues, the following best practices can help:

 Efficient Location Updates: Use FusedLocationProviderClient for optimized power


and performance management, and limit location updates based on the need for
accuracy.

 Location Caching: Use cached or last-known location data when high accuracy is not
required to reduce network and GPS dependency.

 User Education and Permissions: Clearly communicate why location permissions


are needed and how data will be used. Provide users with control over their privacy
settings.

 Fallback Mechanisms: Implement fallback strategies (e.g., fallback to network-based


location when GPS is unavailable) to improve accuracy in less-than-ideal conditions.

 Adaptive Geofencing: Use adaptive geofencing that considers device speed and
environment to adjust when and how geofencing events are triggered.

Discuss how Android Stores and Retrieves data through SQL


Applications?
Covered above

How data is stored and retrieved in android?


Covered above

Give an overview of Mobile Agents? Discuss location-based


services in Android?
Mobile Agents in Mobile Computing
In Mobile Computing, Mobile Agents are the composition of computer software and data that
can autonomously move from one computer to another computer and continue its execution
on the destination computer.

In other words, you can say that An Mobile Agent is an autonomous program that is capable
of moving from host to host in a network and interact with resources and other agents. In this
process, the chance of data loss is scarce because the state of the running program is saved
and then transported to the new host. It allows the program to continue execution from
where it left off before migration. The most significant advantage of mobile agents is the
possibility of moving complex processing functions to the location where you have enormous
amounts of data and that have to be processed.
Mobile Agents are also called as transportable agents. They are classified into two types:

o Mobile Agents with pre-defined path: They have a static migration path.

o Mobile Agents with undefined path i.e., Roamer: They have dynamic migration
paths. The mobile agents choose their path according to the present network condition.

Features of Mobile Agents

The mobile agents are autonomous with intelligence, social ability, learning, and the most
important feature is their mobility. They are independent in nature, self-driven and do not
require a corresponding node for communication. They can work efficiently even after the
user gets disconnected from the network.

 Intelligence

Mobile Agents are capable of learning and searching for knowledge about their domain.
That's why they are called intelligent agents because they possess a degree of domain
knowledge. They can also transport their state from one environment to another
without disturbing the previous holding data and be capable of performing
appropriately in the new environment.

 Autonomous

The Mobile Agents are Autonomous. It means the agents are not only motivated by the
outside actions initiated by the users or system but also they have internal events that
decided their performance and behavior. The mobile agents can also take an
autonomous decision while selecting a node.

 Mobility

Mobile Agents contain some degree of mobility. The agent is not limited to its home
node only. They can migrate from one node to another and can carry out tasks along
with them. This feature distributes the processing and balancing of the load. Another
benefit of this capability is that when the user goes offline, the agents will still keep
functioning.

 Communicative

Mobile Agents can communicate effectively with other agents, users and systems. The
mobile agents use a communication language for inter-agent communication.

Life Cycle of Mobile Agents

The life cycle of mobile agents ensures the following conditions:

o They can adapt to the environment. For example, either home or foreign environment.

o They are capable of switching among the positions of one node to another.

o They are autonomous and focused on the final output.


Advantages of Mobile Agents

The following are some advantages of mobile agents over conventional agents:

o Mobile Agents are autonomous and self-driven in nature.

o They are maintenance-friendly or easily maintainable.

o They are Fault-tolerant. It means they are able to operate without an active connection
between client and server.

o They reduce the compilation time.

o They provide less delay in the network.

o They provide fewer loads on the network.

o They facilitate parallel processing. It means they can be asynchronously executed on


multiple heterogeneous network hosts.

o They provide dynamic adaptation in which their actions are dependent on the state of
the host environment.

Disadvantages of Mobile Agents

The following are some disadvantages of mobile agents:

o The most significant disadvantage of mobile agents is their security. They are less
secured

Applications of Mobile Agents

Mobile agents are used in the following applications:

o Mobile Agents are applied in a wide range of domains such as E-commerce, traffic
control, network management, robotics, data-intensive applications etc.

o They are also used in grid computing, parallel computing, distributed computing and
mobile computing etc.

Location-based services in Android


Location-based services (LBS) in Android are essential for providing location-aware
features in applications. These services use the device's built-in sensors and APIs to gather
location data, enabling apps to provide functionalities like navigation, geofencing, and user
tracking. Android offers various tools and APIs to access location data, which can help
enhance user experiences by tailoring content based on their geographical location.

Here’s a breakdown of the location-based services in Android:

1. Fused Location Provider (FLP)

The FusedLocationProviderClient is part of the Google Play Services API and is the
recommended method for accessing location data in Android. It intelligently combines
multiple sources of location data (GPS, Wi-Fi, and cellular data) to deliver the most accurate
location while optimizing power consumption.

Advantages:

 Power-efficient: It uses smart algorithms to select the most appropriate provider


based on accuracy and battery life.
 High Accuracy: Provides location data from GPS, Wi-Fi, Bluetooth, or cell towers.

 Easy to implement: Provides simplified methods for getting current location, location
updates, and handling background location tracking.

Key Features:

 FusedLocationProviderClient: Primary interface to access location data.

 LocationRequest: Used to configure location update frequency, priority (accuracy), and


interval.

 LocationCallback: Allows listening for location updates asynchronously.

Usage:

FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(context);

fusedLocationClient.getLastLocation()

.addOnSuccessListener(location -> {

// Handle the location update

});

2. GPS (Global Positioning System)

GPS is one of the most accurate location tracking methods, as it uses satellite signals to
determine the user's position. It is commonly used when high accuracy is necessary, such as
in navigation apps or location-based gaming.

Advantages:

 High accuracy (10–30 meters).

 Ideal for real-time navigation and location-based services in open outdoor areas.

Limitations:

 Consumes more battery power.

 Ineffective in indoor or obstructed environments (e.g., urban canyons, inside buildings).

3. Network-based Location (Wi-Fi and Cell Towers)

Android can estimate a device's location using nearby Wi-Fi networks and cell towers
when GPS is not available or accurate. This method is less precise than GPS but more power-
efficient.

Advantages:

 Battery efficient: Uses less power than GPS.

 Works indoors or in areas with a high concentration of Wi-Fi access points.

Limitations:

 Lower accuracy (can be up to several hundred meters).

 Dependent on nearby Wi-Fi or cellular towers.

4. Geofencing
Geofencing is a location-based service that allows an app to define geographical boundaries
(virtual "fences") around certain areas. When the device enters or exits this area, an event is
triggered (such as sending a notification).

Applications:

 Location-based notifications: Notify users when they enter a store, location, or


venue.

 Tracking and monitoring: For example, in fleet management or children’s safety


apps.

Key APIs:

 GeofencingClient: Used to add and remove geofences, and to receive geofence events.

 Geofence: Defines a boundary, including its radius, center, and transition type (enter,
exit).

Usage:

GeofencingClient geofencingClient = LocationServices.getGeofencingClient(context);

Geofence geofence = new Geofence.Builder()

.setRequestId("1")

.setCircularRegion(latitude, longitude, radius)

.setExpirationDuration(Geofence.NEVER_EXPIRE)

.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)

.build();

GeofencingRequest geofencingRequest = new GeofencingRequest.Builder()

.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)

.addGeofence(geofence)

.build();

5. Location History and Activity Recognition

Activity Recognition and Location History allow apps to understand a user’s activity
(walking, running, biking, driving, etc.) or track their past locations.

 Activity Recognition: Can detect the user's current activity in real-time, such as
walking, running, or in a vehicle.

 Location History: Tracks the user's movements over time to provide context about
their typical routes and places.

APIs:

 ActivityRecognitionClient: Detects the current activity of the user.

 History API: Allows you to fetch historical location data (requires


ACCESS_BACKGROUND_LOCATION permission).
6. Google Maps API

The Google Maps SDK for Android offers location-based features such as displaying maps,
adding markers, and drawing routes. It also integrates with location services for real-time
navigation, tracking, and location-based visualizations.

Features:

 Show current location on map.

 Route navigation and turn-by-turn directions.

 Custom markers and geospatial features like polygons and polylines.

Usage:

// Display current location

GoogleMap map = googleMap; // Get your GoogleMap instance

map.setMyLocationEnabled(true);

7. Location Permissions

Android requires apps to request location permissions at runtime for accessing location
data. Depending on the level of accuracy needed, apps must request either
ACCESS_COARSE_LOCATION (approximate location) or ACCESS_FINE_LOCATION (precise
GPS location). From Android 6.0 (API level 23) onward, location permissions must be
requested dynamically.

Permissions:

 ACCESS_FINE_LOCATION: Access precise location (e.g., GPS).

 ACCESS_COARSE_LOCATION: Access approximate location (e.g., via Wi-Fi or cell


towers).

 ACCESS_BACKGROUND_LOCATION: To access location data when the app is in the


background (introduced in Android 10).

Usage:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

== PackageManager.PERMISSION_GRANTED) {

// Permission granted

} else {

ActivityCompat.requestPermissions(this, new String[]


{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

8. Background Location

Android’s background location permission is required if your app needs to access location
data while running in the background. This is important for use cases such as fitness trackers,
ride-sharing apps, or security apps.

Starting from Android 10 (API 29), accessing background location requires a separate
permission (ACCESS_BACKGROUND_LOCATION), which must be granted by the user.
Usage:

 Request foreground location permission first.

 Request background location permission if necessary for your use case.

9. Location Services and Doze Mode

Android’s Doze mode (introduced in Android 6.0) can limit location updates when the device
is idle or in a low-power state. Apps should be aware of Doze mode to avoid interruptions to
background location updates.

Best Practices:

 Use WorkManager or JobScheduler for periodic background tasks that need location
updates.

 Use the setExact() or setWindow() methods in JobScheduler to control when your


background task runs, respecting battery-saving modes.

Key Considerations for Location-based Services:

1. Battery Efficiency: Always balance the accuracy of the location with the power
consumption. Use Fused Location Provider, which intelligently switches between GPS,
Wi-Fi, and cellular signals based on your needs.

2. User Privacy: Ensure you handle location data responsibly by requesting permission,
explaining the need for location access, and using encryption for sensitive data.

3. Permission Requests: Follow Android's permission model carefully to avoid runtime


issues, especially with background location access introduced in newer Android
versions.

Write a program to display the Current Location?


How to Get Current Location in Android?
As a developer when you work on locations in Android then you always have some doubts
about selecting the best and efficient approach for your requirement. So in this article, we are
going to discuss how to get the user’s current location in Android. There are two ways to get
the current location of any Android device:

1. Android’s Location Manager API

2. Fused Location Provider: Google Play Services Location APIs

Question: Which one is efficient and why?

Answer: Fused Location Provider because it optimizes the device’s use of battery power.

For those looking to master advanced Android development techniques like location-based
services, consider enrolling in the Android Development with Kotlin course from
GeeksforGeeks. This course covers essential features such as handling location data,
enabling you to build sophisticated apps with Kotlin.

Before moving any of the above methods we will have to take location permission.
Looking to become an expert in Android App Development? Whether you're a student or a
professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Taking Location Permission

Step 1: Define uses permissions for location access in the manifest file

<!– To request foreground location access, declare one of these permissions. –>

<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />

<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” />

<!– Required only when requesting background location access on Android 10 (API level 29) –
>

<uses-permission android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />

Note:

In order to receive location updates from NETWORK_PROVIDER or GPS_PROVIDER, you must


request the user’s permission by declaring either the ACCESS_COARSE_LOCATION or
ACCESS_FINE_LOCATION permission, respectively, in your Android manifest file. Without
these permissions, your application will fail at runtime when requesting location updates.

If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request
only the ACCESS_FINE_LOCATION permission, because it includes permission for both
providers. Permission for ACCESS_COARSE_LOCATION allows access only to
NETWORK_PROVIDER.

Step 2: Define uses permission for internet access because we are going to use Internet
Provider.

<uses-permission android:name=”android.permission.INTERNET”/>

Step 3: Write a function for checking that location permission is granted or not. If permission
is not granted then ask for the permissions in run time.

private fun isLocationPermissionGranted(): Boolean {

return if (ActivityCompat.checkSelfPermission(

this,

android.Manifest.permission.ACCESS_COARSE_LOCATION

) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(

this,

android.Manifest.permission.ACCESS_FINE_LOCATION

) != PackageManager.PERMISSION_GRANTED

){

ActivityCompat.requestPermissions(

this,

arrayOf(
android.Manifest.permission.ACCESS_FINE_LOCATION,

android.Manifest.permission.ACCESS_COARSE_LOCATION

),

requestcode

false

} else {

true

Now after handling location permissions, we are going to learn how can we get the location in
android.

First Method: By Android’s Location Manager API

We assume that the user has been granted Location Permission. If not then ask first.

Step 1: Creating an instance of LocationManager in the context of LOCATION_SERVICE.

private var currentLocation: Location? = null

lateinit var locationManager: LocationManager

locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

Step 2: Check that if the GPS and Network are available or not and if both are available then
we use one with greater accuracy.

val hasGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)

//------------------------------------------------------//

val hasNetwork =
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
Step 3: Creating an instance of LocationListener (package: android.location) for both(GPS
and Network).

val gpsLocationListener: LocationListener = object : LocationListener {

override fun onLocationChanged(location: Location) {

locationByGps= location

override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

override fun onProviderEnabled(provider: String) {}

override fun onProviderDisabled(provider: String) {}

//------------------------------------------------------//

val networkLocationListener: LocationListener = object : LocationListener {

override fun onLocationChanged(location: Location) {

locationByNetwork= location

override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}

override fun onProviderEnabled(provider: String) {}

override fun onProviderDisabled(provider: String) {}

Step 4: If any of the GPS or Network providers is enabled then we will request a current
location update from the LocationManager with LocationListener.

if (hasGps) {

locationManager.requestLocationUpdates(

LocationManager.GPS_PROVIDER,

5000,

0F,

gpsLocationListener

//------------------------------------------------------//

if (hasNetwork) {

locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,

5000,

0F,

networkLocationListener

Step 5: Now we check which provider has given us the more accurate location and then we
will use that location as per our requirement.

val lastKnownLocationByGps =

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)

lastKnownLocationByGps?.let {

locationByGps = lastKnownLocationByGps

//------------------------------------------------------//

val lastKnownLocationByNetwork =

locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)

lastKnownLocationByNetwork?.let {

locationByNetwork = lastKnownLocationByNetwork

//------------------------------------------------------//

if (locationByGps != null && locationByNetwork != null) {

if (locationByGps.accuracy > locationByNetwork!!.accuracy) {

currentLocation = locationByGps

latitude = currentLocation.latitude

longitude = currentLocation.longitude

// use latitude and longitude as per your need

} else {

currentLocation = locationByNetwork

latitude = currentLocation.latitude

longitude = currentLocation.longitude

// use latitude and longitude as per your need

}
Now after learning how can we get the location in android by Location Manager API, we are
moving to the second method Fused Location Provider (Google Play Services Location
APIs).

Second Method: By Fused Location Provider

We assume that the user has been granted Location Permission. If not then ask first. Fused
Location Provider is the Google Play services location APIs. It provides a simple API for getting
locations with high, medium, and low accuracy. It also optimizes the device’s use of battery
power. So we should prefer this method.

Step 1: Declare variables of FusedLocationProviderClient, LocationRequest, LocationCallback


and Location.

// FusedLocationProviderClient - Main class for receiving location updates.

private lateinit var fusedLocationProviderClient: FusedLocationProviderClient

// LocationRequest - Requirements for the location updates, i.e.,

// how often you should receive updates, the priority, etc.

private lateinit var locationRequest: LocationRequest

// LocationCallback - Called when FusedLocationProviderClient

// has a new Location

private lateinit var locationCallback: LocationCallback

// This will store current location info

private var currentLocation: Location? = null

Step 2: Initialize fusedLocationProviderClient.

fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)

Step 3: Initialize locationRequest.

locationRequest = LocationRequest().apply {

// Sets the desired interval for

// active location updates.

// This interval is inexact.

interval = TimeUnit.SECONDS.toMillis(60)

// Sets the fastest rate for active location updates.

// This interval is exact, and your application will never

// receive updates more frequently than this value

fastestInterval = TimeUnit.SECONDS.toMillis(30)
// Sets the maximum time when batched location

// updates are delivered. Updates may be

// delivered sooner than this interval

maxWaitTime = TimeUnit.MINUTES.toMillis(2)

priority = LocationRequest.PRIORITY_HIGH_ACCURACY

Step 4: Initialize locationCallback.

locationCallback = object : LocationCallback() {

override fun onLocationResult(locationResult: LocationResult?) {

super.onLocationResult(locationResult)

locationResult?.lastLocation?.let {

currentLocation = locationByGps

latitude = currentLocation.latitude

longitude = currentLocation.longitude

// use latitude and longitude as per your need

} ?: {

Log.d(TAG, "Location information isn't available.")

Step 5: Now that you initialized everything, you need to let the FusedLocationProviderClient
know that you want to receive updates. So Subscribe to location changes.

fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback,
Looper.myLooper())

Step 6: When the app no longer needs access to location information, it’s important to
unsubscribe from location updates.

val removeTask = fusedLocationProviderClient.removeLocationUpdates(locationCallback)

removeTask.addOnCompleteListener { task ->

if (task.isSuccessful) {

Log.d(TAG, "Location Callback removed.")

} else {

Log.d(TAG, "Failed to remove Location Callback.")

}
}

Now one more important point to give support for Android 10 and Android R. So
Let’s talk about it…

Support for Android 10

Step 1: Make these changes in build.gradle file.

1. Set compileSdkVersion to 29.

2. Set buildToolsVersion to “29.0.3”.

3. Set targetSdkVersion to 29.

Your code should look something like this:

android {

compileSdkVersion 29

buildToolsVersion “29.0.3”

defaultConfig {

applicationId “com.example.android.location”

minSdkVersion 26

targetSdkVersion 29

versionCode 1

versionName “1.0”

Step 2: If you have a foreground service, declare a foregroundServiceType of location in the


manifest.

android:foregroundServiceType=”location”

Your code should look something like this:

<application>

<!– Foreground services in Android 10+ require type. –>

<service

android:name=”com.example.android.location.ForegroundOnlyLocationService”

android:enabled=”true”

android:exported=”false”

android:foregroundServiceType=”location” />

</application>
Support for Android 11 or Android R

Great news, you don’t need to make changes to any files except for the build.gradle file!
Make these changes:

1. compileSdkVersion to “android-R”

2. targetSdkVersion to “R”

Your code should look something like this:

android {

compileSdkVersion “android-R”

buildToolsVersion “29.0.2”

defaultConfig {

applicationId “com.example.android.location”

minSdkVersion 26

targetSdkVersion “R”

versionCode 1

versionName “1.0”

Write a Program to how to display Current Location on the


Map in Mobile Application?
Android Google Map Displaying Current Location
In the previous tutorial of Android Google Map, we simply displayed the default coordinates
(location) set by the MapsActivity.java class file.

Now in this tutorial we will display and place marker at the user current location. For doing
this we need to generate Google Map API key. The process of generating Google Map API is
described in tutorial Android Google Map.

To display the user current location we need to implements some interfaces and there
callbacks methods.

Callback methods in Google Map

1. OnMapRreadyCallback: This callback interface invokes when it instance is set on


MapFragment object. The onMapReady(GoogleMap) method of OnMapReadyCallback
interface is called when the map is ready to used. In the onMapReady(GoogleMap)
method we can add markers, listeners and other attributes.
2. LocationListener: This interface is used to receive notification when the device
location has changed. The abstract method of LocationListener
onLocationChanged(Location) is called when the location has changed.

3. GoogleApiClient.ConnectionCallbacks: This interface provide callbacks methods


onConnected(Bundle) and onConnectionSuspended(int) which are called when the
device is to connected and disconnected.

4. GoogleApiClient.OnConnectionFailedListener: This interface provide callbacks


method onConnectionFailed(ConnectionResult) which is called when there was an error
in connecting the device to the service.

The setMyLocationEnabled() method of GoogleMap is used to enable location layer, which


allows device to interact with current location.

Example of Google Map Displaying Current Location

Let's see an example of Google Map which displays the current location of device.

activity_maps.xml

Add a SupportMapFragment in fragment in activity_maps.xml file.

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

2. xmlns:map="http://schemas.android.com/apk/res-auto"

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

4. android:id="@+id/map"

5. android:name="com.google.android.gms.maps.SupportMapFragment"

6. android:layout_width="match_parent"

7. android:layout_height="match_parent"

8. tools:context="example.com.mapexample.MapsActivity" />

build.gradel

Add the following dependencies in build.gradel file.

1. dependencies {

2. implementation fileTree(dir: 'libs', include: ['*.jar'])

3. implementation 'com.android.support:appcompat-v7:26.1.0'

4. implementation 'com.google.android.gms:play-services-maps:11.8.0'

5. compile 'com.google.android.gms:play-services-location:11.8.0'

6. testImplementation 'junit:junit:4.12'

7. androidTestImplementation 'com.android.support.test:runner:1.0.1'

8. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

9.

10. }

MapsActivity.java
Add the following code in MapsActivity.java file.

1. package example.com.mapexample;

2.

3.

4. import android.os.Build;

5. import android.support.v4.app.FragmentActivity;

6. import android.os.Bundle;

7.

8. import com.google.android.gms.common.api.GoogleApiClient;

9. import com.google.android.gms.maps.CameraUpdateFactory;

10. import com.google.android.gms.maps.GoogleMap;

11. import com.google.android.gms.maps.OnMapReadyCallback;

12. import com.google.android.gms.maps.SupportMapFragment;

13. import com.google.android.gms.maps.model.BitmapDescriptorFactory;

14. import com.google.android.gms.maps.model.LatLng;

15. import com.google.android.gms.maps.model.Marker;

16. import com.google.android.gms.maps.model.MarkerOptions;

17. import com.google.android.gms.location.LocationServices;

18.

19. import android.location.Location;

20. import android.Manifest;

21. import android.content.pm.PackageManager;

22. import android.support.v4.content.ContextCompat;

23. import com.google.android.gms.common.ConnectionResult;

24. import com.google.android.gms.location.LocationListener;

25. import com.google.android.gms.location.LocationRequest;

26.

27.

28. public class MapsActivity extends FragmentActivity implements OnMapReady


Callback,

29. LocationListener,GoogleApiClient.ConnectionCallbacks,

30. GoogleApiClient.OnConnectionFailedListener{

31.

32. private GoogleMap mMap;


33. Location mLastLocation;

34. Marker mCurrLocationMarker;

35. GoogleApiClient mGoogleApiClient;

36. LocationRequest mLocationRequest;

37.

38. @Override

39. protected void onCreate(Bundle savedInstanceState) {

40. super.onCreate(savedInstanceState);

41. setContentView(R.layout.activity_maps);

42. // Obtain the SupportMapFragment and get notified when the map is ready t
o be used.

43. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFra


gmentManager()

44. .findFragmentById(R.id.map);

45. mapFragment.getMapAsync(this);

46.

47. }

48.

49. @Override

50. public void onMapReady(GoogleMap googleMap) {

51. mMap = googleMap;

52.

53. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

54. if (ContextCompat.checkSelfPermission(this,

55. Manifest.permission.ACCESS_FINE_LOCATION)

56. == PackageManager.PERMISSION_GRANTED) {

57. buildGoogleApiClient();

58. mMap.setMyLocationEnabled(true);

59. }

60. }

61. else {

62. buildGoogleApiClient();

63. mMap.setMyLocationEnabled(true);

64. }
65.

66. }

67. protected synchronized void buildGoogleApiClient() {

68. mGoogleApiClient = new GoogleApiClient.Builder(this)

69. .addConnectionCallbacks(this)

70. .addOnConnectionFailedListener(this)

71. .addApi(LocationServices.API).build();

72. mGoogleApiClient.connect();

73. }

74.

75. @Override

76. public void onConnected(Bundle bundle) {

77.

78. mLocationRequest = new LocationRequest();

79. mLocationRequest.setInterval(1000);

80. mLocationRequest.setFastestInterval(1000);

81. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER
_ACCURACY);

82. if (ContextCompat.checkSelfPermission(this,

83. Manifest.permission.ACCESS_FINE_LOCATION)

84. == PackageManager.PERMISSION_GRANTED) {

85. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiC
lient, mLocationRequest, this);

86. }

87.

88. }

89.

90. @Override

91. public void onConnectionSuspended(int i) {

92.

93. }

94.

95. @Override

96. public void onLocationChanged(Location location) {


97.

98. mLastLocation = location;

99. if (mCurrLocationMarker != null) {

100. mCurrLocationMarker.remove();

101. }

102. //Place current location marker

103. LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

104. MarkerOptions markerOptions = new MarkerOptions();

105. markerOptions.position(latLng);

106. markerOptions.title("Current Position");

107. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescripto
rFactory.HUE_GREEN));

108. mCurrLocationMarker = mMap.addMarker(markerOptions);

109.

110. //move map camera

111. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

112. mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

113.

114. //stop location updates

115. if (mGoogleApiClient != null) {

116. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiC
lient, this);

117. }

118.

119. }

120.

121. @Override

122. public void onConnectionFailed(ConnectionResult connectionResult) {

123.

124. }

125.

126. }

Request Runtime Permission


Android device having Android 6.0 (Marshmallow) or later are required some permission at
runtime to access device functionality.

In the above MapsActivity.java file we added a runtime


permission Manifest.permission.ACCESS_FINE_LOCATION which request to access device
location. The runtime permission is checked using checkSelfPermission() method and
return PackageManager.PERMISSION_GRANTED or PackageManager.PERMISSION_DENIED. If
permission granted than app proceeds for operation.

Required Permission in AndroidManifest.xml

Add the following user-permission in AndroidManifest.xml file.

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

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

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

AndroidManifest.xml

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

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

3. package="example.com.mapexample">

4. <!--

5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to use

6. Google Maps Android API v2, but you must specify either coarse or fine

7. location permissions for the 'MyLocation' functionality.

8. -->

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

10. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCAT


ION" />

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

12.

13.

14. <application

15. android:allowBackup="true"

16. android:icon="@mipmap/ic_launcher"

17. android:label="@string/app_name"

18. android:roundIcon="@mipmap/ic_launcher_round"

19. android:supportsRtl="true"

20. android:theme="@style/AppTheme">

21. <!--

22. The API key for Google Maps-based APIs is defined as a string resource.
23. (See the file "res/values/google_maps_api.xml").

24. Note that the API key is linked to the encryption key used to sign the APK.

25. You need a different API key for each encryption key, including the releas
e key that is used to

26. sign the APK for publishing.

27. You can define the keys for the debug and release targets in src/debug/ a
nd src/release/.

28. -->

29. <meta-data

30. android:name="com.google.android.geo.API_KEY"

31. android:value="@string/google_maps_key" />

32.

33. <activity

34. android:name=".MapsActivity"

35. android:label="@string/title_activity_maps">

36. <intent-filter>

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

38.

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

40. </intent-filter>

41. </activity>

42. </application>

43.

44. </manifest>

Output
Write a Program to how to update the Current Location in the
Map?

Discuss the directory structure of an Android Project.


Android Project folder Structure
Android Studio is the official IDE (Integrated Development Environment) developed by the
JetBrains community which is freely provided by Google for android app development. After
completing the setup of Android Architecture we can create an android application in the
studio. We need to create a new project for each sample application and we should
understand the folder structure. It looks like this:

The android project contains different types of app modules, source code files, and resource
files. We will explore all the folders and files in the android app.

1. Manifests Folder

2. Java Folder

3. res (Resources) Folder

 Drawable Folder

 Layout Folder

 Mipmap Folder

 Values Folder

4. Gradle Scripts

Manifests Folder
Manifests folder contains AndroidManifest.xml for creating our android application. This file
contains information about our application such as the Android version, metadata, states
package for Kotlin file, and other application components. It acts as an intermediator
between android OS and our application.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Following is the manifests folder structure in the android application.

AndroidManifest.xml

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

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

package="com.geeksforgeeks.myapplication">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

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

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

</intent-filter>

</activity>

</application>
</manifest>

Java folder

The Java folder contains all the java and Kotlin source code (.java) files that we create during
the app development, including other Test files. If we create any new project using Kotlin, by
default the class file MainActivity.kt file will create automatically under the package name
“com.geeksforgeeks.myfirstkotlinapp” as shown below.

MainActivity.kt and MainActivity.java

package com.geeksforgeeks.myapplication;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Resource (res) folder

The resource folder is the most important folder because it contains all the non-code sources
like images, XML layouts, and UI strings for our android application.
res/drawable folder

It contains the different types of images used for the development of the application. We
need to add all the images in a drawable folder for the application development.

res/layout folder

The layout folder contains all XML layout files which we used to define the user interface of
our application. It contains 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=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello World!"

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

res/mipmap folder

This folder contains launcher.xml files to define icons that are used to show on the home
screen. It contains different density types of icons depending upon the size of the device such
as hdpi, mdpi, xhdpi.

res/values folder

Values folder contains a number of XML files like strings, dimensions, colors, and style
definitions. One of the most important files is the strings.xml file which contains the
resources.

<resources>

<string name="app_name">NameOfTheApplication</string>

<string name="checked">Checked</string>

<string name="unchecked">Unchecked</string>

</resources>

Gradle Scripts folder

Gradle means automated build system and it contains a number of files that are used to
define a build configuration that can be applied to all modules in our application. In
build.gradle (Project) there are buildscripts and in build.gradle (Module) plugins and
implementations are used to build configurations that can be applied to all our application
modules.
Unit 5

Write about How to Creating, Setting, and Cancelling Alarms


In Android development, alarms are used to schedule tasks to be performed at specific times,
even when the app isn't actively running. You can create alarms using AlarmManager, a
system service that provides access to the device's alarm services. The AlarmManager allows
you to schedule tasks for future execution, which can occur even if the app or device is in a
low-power state.

Here’s a step-by-step guide on how to create, set, and cancel alarms in an Android app.

1. Creating an Alarm

To create an alarm, you need to interact with the AlarmManager system service. The alarm
can trigger a BroadcastReceiver, Service, or Activity to perform a certain action when the
alarm goes off.

Steps:

1. Get an instance of AlarmManager.

2. Create an Intent that specifies the action to take when the alarm goes off.

3. Wrap the Intent in a PendingIntent.

4. Set the alarm using AlarmManager.

Example Code:
// Step 1: Get an instance of AlarmManager

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

// Step 2: Create an Intent to trigger when the alarm goes off

Intent intent = new Intent(this, AlarmReceiver.class); // AlarmReceiver is a BroadcastReceiver

// Step 3: Wrap the intent in a PendingIntent

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,


PendingIntent.FLAG_UPDATE_CURRENT);

// Step 4: Set the alarm to trigger at a specific time

long triggerTime = SystemClock.elapsedRealtime() + 10000; // 10 seconds from now

// Use setExact() for exact alarms or set() for inexact ones

alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pendingIntent);

Breakdown:

 SystemClock.elapsedRealtime() provides the system time since the device was booted,
which is often used for setting alarms relative to the device's uptime.

 AlarmManager.ELAPSED_REALTIME_WAKEUP wakes up the device if it's in a sleep mode


to trigger the alarm.
 setExact() is used for an exact alarm time, while set() could be used for inexact ones
(where timing is not critical).

2. Setting a Repeating Alarm

Sometimes, you need the alarm to repeat at regular intervals (e.g., every 30 minutes). You
can set repeating alarms using the setRepeating() method or setInexactRepeating() for less
precision.

Example Code for Repeating Alarm:


// Step 1: Get an instance of AlarmManager

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

// Step 2: Create an Intent to trigger when the alarm goes off

Intent intent = new Intent(this, AlarmReceiver.class);

// Step 3: Wrap the intent in a PendingIntent

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,


PendingIntent.FLAG_UPDATE_CURRENT);

// Step 4: Set a repeating alarm (e.g., every 1 hour)

long triggerTime = SystemClock.elapsedRealtime() + 60000; // Start after 1 minute

long interval = 3600000; // 1 hour in milliseconds

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, interval, pendingIntent);

Key Points:

 setRepeating() allows you to repeat an alarm at regular intervals.

 Interval is the duration between consecutive alarms (e.g., 1 hour in the example).

3. Handling the Alarm with a BroadcastReceiver

To handle the alarm when it goes off, you need to create a BroadcastReceiver. The receiver
is triggered by the alarm and performs a task, such as displaying a notification or starting a
service.

Example of BroadcastReceiver:
public class AlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

// Perform the action when the alarm goes off (e.g., display a notification)

Toast.makeText(context, "Alarm triggered!", Toast.LENGTH_SHORT).show();

You need to register this receiver in the AndroidManifest.xml or dynamically within the
app.
Example of Registering in AndroidManifest.xml:

<receiver android:name=".AlarmReceiver" android:enabled="true"


android:exported="false" />

4. Cancelling an Alarm

If you want to cancel a previously set alarm, you need to call AlarmManager.cancel() with the
same PendingIntent used when setting the alarm. This will cancel the alarm and prevent it
from being triggered.

Example Code to Cancel an Alarm:


// Step 1: Get an instance of AlarmManager

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

// Step 2: Create an Intent and PendingIntent as done when setting the alarm

Intent intent = new Intent(this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,


PendingIntent.FLAG_UPDATE_CURRENT);

// Step 3: Cancel the alarm using AlarmManager

alarmManager.cancel(pendingIntent);

5. Using WorkManager for Background Tasks (Modern Approach)

For modern Android apps, it's recommended to use WorkManager for scheduling
background tasks, including alarms, because it automatically handles scenarios like the app
being closed or the device going to sleep. WorkManager also ensures tasks are run even if
the app is not in the foreground.

Example Code Using WorkManager:


// Create a WorkRequest to schedule the task

OneTimeWorkRequest alarmWorkRequest = new OneTimeWorkRequest.Builder(MyWorker.class)

.setInitialDelay(10, TimeUnit.SECONDS) // Set initial delay

.build();

// Enqueue the work request

WorkManager.getInstance(context).enqueue(alarmWorkRequest);

In this example, MyWorker is a class that extends Worker and contains the logic to be
performed when the alarm triggers.

Best Practices

 Avoid using setRepeating() for exact intervals as it can have an impact on battery
life. For precise repeating tasks, use JobScheduler or WorkManager instead.

 Use WakeLocks cautiously. Android handles Doze Mode and App Standby
automatically, so make sure alarms are set in a way that respects power consumption.
 Always make sure you’re using the correct permissions in your app. For example, to
wake up the device from sleep, your app may need to request WAKE_LOCK
permission.

Create a Simple Own Service to start and stop the service in


Android?
Services overview
A Service is an application component that can perform long-running operations in the
background. It does not provide a user interface. Once started, a service might continue
running for some time, even after the user switches to another application. Additionally, a
component can bind to a service to interact with it and even perform interprocess
communication (IPC). For example, a service can handle network transactions, play music,
perform file I/O, or interact with a content provider, all from the background.

Caution: A service runs in the main thread of its hosting process; the service
does not create its own thread and does not run in a separate process unless you specify
otherwise. You should run any blocking operations on a separate thread within the service to
avoid Application Not Responding (ANR) errors.

Types of Services

These are the three different types of services:

Foreground

A foreground service performs some operation that is noticeable to the user. For example, an
audio app would use a foreground service to play an audio track. Foreground services must
display a Notification. Foreground services continue running even when the user isn't
interacting with the app.

When you use a foreground service, you must display a notification so that users are actively
aware that the service is running. This notification cannot be dismissed unless the service is
either stopped or removed from the foreground.

Learn more about how to configure foreground services in your app.

Note: The WorkManager API offers a flexible way of scheduling tasks, and is able to run these
jobs as foreground services if needed. In many cases, using WorkManager is preferable to
using foreground services directly.

Background

A background service performs an operation that isn't directly noticed by the user. For
example, if an app used a service to compact its storage, that would usually be a background
service.

Note: If your app targets API level 26 or higher, the system imposes restrictions on running
background services when the app itself isn't in the foreground. In most situations, for
example, you shouldn't access location information from the background. Instead, schedule
tasks using WorkManager.

Bound
A service is bound when an application component binds to it by calling bindService(). A
bound service offers a client-server interface that allows components to interact with the
service, send requests, receive results, and even do so across processes with interprocess
communication (IPC). A bound service runs only as long as another application component is
bound to it. Multiple components can bind to the service at once, but when all of them
unbind, the service is destroyed.

Although this documentation generally discusses started and bound services separately, your
service can work both ways—it can be started (to run indefinitely) and also allow binding. It's
simply a matter of whether you implement a couple of callback
methods: onStartCommand() to allow components to start it and onBind() to allow binding.

Regardless of whether your service is started, bound, or both, any application component can
use the service (even from a separate application) in the same way that any component can
use an activity—by starting it with an Intent. However, you can declare the service
as private in the manifest file and block access from other applications. This is discussed
more in the section about Declaring the service in the manifest.

Choosing between a service and a thread

A service is simply a component that can run in the background, even when the user is not
interacting with your application, so you should create a service only if that is what you need.

If you must perform work outside of your main thread, but only while the user is interacting
with your application, you should instead create a new thread in the context of another
application component. For example, if you want to play some music, but only while your
activity is running, you might create a thread in onCreate(), start running it in onStart(), and
stop it in onStop(). Also consider using thread pools and executors from
the java.util.concurrent package or Kotlin coroutines instead of the traditional Thread class.
See the Threading on Android document for more information about moving execution to
background threads.

Remember that if you do use a service, it still runs in your application's main thread by
default, so you should still create a new thread within the service if it performs intensive or
blocking operations.

The basics

To create a service, you must create a subclass of Service or use one of its existing
subclasses. In your implementation, you must override some callback methods that handle
key aspects of the service lifecycle and provide a mechanism that allows the components to
bind to the service, if appropriate. These are the most important callback methods that you
should override:

onStartCommand()

The system invokes this method by calling startService() when another component (such as
an activity) requests that the service be started. When this method executes, the service is
started and can run in the background indefinitely. If you implement this, it is your
responsibility to stop the service when its work is complete by
calling stopSelf() or stopService(). If you only want to provide binding, you don't need to
implement this method.

onBind()
The system invokes this method by calling bindService() when another component wants to
bind with the service (such as to perform RPC). In your implementation of this method, you
must provide an interface that clients use to communicate with the service by returning
an IBinder. You must always implement this method; however, if you don't want to allow
binding, you should return null.

onCreate()

The system invokes this method to perform one-time setup procedures when the service is
initially created (before it calls either onStartCommand() or onBind()). If the service is already
running, this method is not called.

onDestroy()

The system invokes this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, or receivers. This is the last call that the service receives.

If a component starts the service by calling startService() (which results in a call


to onStartCommand()), the service continues to run until it stops itself with stopSelf() or
another component stops it by calling stopService().

If a component calls bindService() to create the service and onStartCommand() is not called,
the service runs only as long as the component is bound to it. After the service is unbound
from all of its clients, the system destroys it.

The Android system stops a service only when memory is low and it must recover system
resources for the activity that has user focus. If the service is bound to an activity that has
user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's
rarely killed. If the service is started and is long-running, the system lowers its position in the
list of background tasks over time, and the service becomes highly susceptible to killing—if
your service is started, you must design it to gracefully handle restarts by the system. If the
system kills your service, it restarts it as soon as resources become available, but this also
depends on the value that you return from onStartCommand(). For more information about
when the system might destroy a service, see the Processes and Threading document.

In the following sections, you'll see how you can create


the startService() and bindService() service methods, as well as how to use them from other
application components.

Declaring a service in the manifest

You must declare all services in your application's manifest file, just as you do for activities
and other components.

To declare your service, add a <service> element as a child of the <application> element.
Here is an example:

<manifest ... >

...

<application ... >

<service android:name=".ExampleService" />

...

</application>
</manifest>

See the <service> element reference for more information about declaring your service in
the manifest.

There are other attributes that you can include in the <service> element to define properties
such as the permissions that are required to start the service and the process in which the
service should run. The android:name attribute is the only required attribute—it specifies the
class name of the service. After you publish your application, leave this name unchanged to
avoid the risk of breaking code due to dependence on explicit intents to start or bind the
service (read the blog post, Things That Cannot Change).

Caution: To ensure that your app is secure, always use an explicit intent when starting
a Service and don't declare intent filters for your services. Using an implicit intent to start a
service is a security hazard because you cannot be certain of the service that responds to the
intent, and the user cannot see which service starts. Beginning with Android 5.0 (API level
21), the system throws an exception if you call bindService() with an implicit intent.

You can ensure that your service is available to only your app by including
the android:exported attribute and setting it to false. This effectively stops other apps from
starting your service, even when using an explicit intent.

Note: Users can see what services are running on their device. If they see a service that they
don't recognize or trust, they can stop the service. In order to avoid having your service
stopped accidentally by users, you need to add the android:description attribute to
the <service> element in your app manifest. In the description, provide a short sentence
explaining what the service does and what benefits it provides.

Creating a started service

A started service is one that another component starts by calling startService(), which results
in a call to the service's onStartCommand() method.

When a service is started, it has a lifecycle that's independent of the component that started
it. The service can run in the background indefinitely, even if the component that started it is
destroyed. As such, the service should stop itself when its job is complete by
calling stopSelf(), or another component can stop it by calling stopService().

An application component such as an activity can start the service by


calling startService() and passing an Intent that specifies the service and includes any data
for the service to use. The service receives this Intent in the onStartCommand() method.

For instance, suppose an activity needs to save some data to an online database. The activity
can start a companion service and deliver it the data to save by passing an intent
to startService(). The service receives the intent in onStartCommand(), connects to the
Internet, and performs the database transaction. When the transaction is complete, the
service stops itself and is destroyed.

Caution: A service runs in the same process as the application in which it is declared and in
the main thread of that application by default. If your service performs intensive or blocking
operations while the user interacts with an activity from the same application, the service
slows down activity performance. To avoid impacting application performance, start a new
thread inside the service.

The Service class is the base class for all services. When you extend this class, it's important
to create a new thread in which the service can complete all of its work; the service uses your
application's main thread by default, which can slow the performance of any activity that
your application is running.

The Android framework also provides the IntentService subclass of Service that uses a worker
thread to handle all of the start requests, one at a time. Using this class is not
recommended for new apps as it will not work well starting with Android 8 Oreo, due to the
introduction of Background execution limits. Moreover, it's deprecated starting with Android
11. You can use JobIntentService as a replacement for IntentService that is compatible with
newer versions of Android.

The following sections describe how you can implement your own custom service, however
you should strongly consider using WorkManager instead for most use cases. Consult
the guide to background processing on Android to see if there is a solution that fits your
needs.

Extending the Service class

You can extend the Service class to handle each incoming intent. Here's how a basic
implementation might look:

KotlinJava

class HelloService : Service() {

private var serviceLooper: Looper? = null

private var serviceHandler: ServiceHandler? = null

// Handler that receives messages from the thread

private inner class ServiceHandler(looper: Looper) : Handler(looper) {

override fun handleMessage(msg: Message) {

// Normally we would do some work here, like download a file.

// For our sample, we just sleep for 5 seconds.

try {

Thread.sleep(5000)

} catch (e: InterruptedException) {

// Restore interrupt status.

Thread.currentThread().interrupt()

// Stop the service using the startId, so that we don't stop

// the service in the middle of handling another job

stopSelf(msg.arg1)
}

override fun onCreate() {

// Start up the thread running the service. Note that we create a

// separate thread because the service normally runs in the process's

// main thread, which we don't want to block. We also make it

// background priority so CPU-intensive work will not disrupt our UI.

HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND).apply {

start()

// Get the HandlerThread's Looper and use it for our Handler

serviceLooper = looper

serviceHandler = ServiceHandler(looper)

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {

Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show()

// For each start request, send a message to start a job and deliver the

// start ID so we know which request we're stopping when we finish the job

serviceHandler?.obtainMessage()?.also { msg ->

msg.arg1 = startId

serviceHandler?.sendMessage(msg)

// If we get killed, after returning from here, restart

return START_STICKY

override fun onBind(intent: Intent): IBinder? {

// We don't provide binding, so return null


return null

override fun onDestroy() {

Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show()

The example code handles all incoming calls in onStartCommand() and posts the work to
a Handler running on a background thread. It works just like an IntentService and processes
all requests serially, one after another. You could change the code to run the work on a thread
pool, for example, if you'd like to run multiple requests simultaneously.

Notice that the onStartCommand() method must return an integer. The integer is a value that
describes how the system should continue the service in the event that the system kills it.
The return value from onStartCommand() must be one of the following constants:

START_NOT_STICKY

If the system kills the service after onStartCommand() returns, do not recreate the service
unless there are pending intents to deliver. This is the safest option to avoid running your
service when not necessary and when your application can simply restart any unfinished
jobs.

START_STICKY

If the system kills the service after onStartCommand() returns, recreate the service and
call onStartCommand(), but do not redeliver the last intent. Instead, the system
calls onStartCommand() with a null intent unless there are pending intents to start the
service. In that case, those intents are delivered. This is suitable for media players (or similar
services) that are not executing commands but are running indefinitely and waiting for a job.

START_REDELIVER_INTENT

If the system kills the service after onStartCommand() returns, recreate the service and
call onStartCommand() with the last intent that was delivered to the service. Any pending
intents are delivered in turn. This is suitable for services that are actively performing a job
that should be immediately resumed, such as downloading a file.

For more details about these return values, see the linked reference documentation for each
constant.

Starting a service

You can start a service from an activity or other application component by passing
an Intent to startService() or startForegroundService(). The Android system calls the
service's onStartCommand() method and passes it the Intent, which specifies which service
to start.

Note: If your app targets API level 26 or higher, the system imposes restrictions on using or
creating background services unless the app itself is in the foreground. If an app needs to
create a foreground service, the app should call startForegroundService(). That method
creates a background service, but the method signals to the system that the service will
promote itself to the foreground. Once the service has been created, the service must call
its startForeground() method within five seconds.

For example, an activity can start the example service in the previous section (HelloService)
using an explicit intent with startService(), as shown here:

KotlinJava

startService(Intent(this, HelloService::class.java))

The startService() method returns immediately, and the Android system calls the
service's onStartCommand() method. If the service isn't already running, the system first
calls onCreate(), and then it calls onStartCommand().

If the service doesn't also provide binding, the intent that is delivered with startService() is
the only mode of communication between the application component and the service.
However, if you want the service to send a result back, the client that starts the service can
create a PendingIntent for a broadcast (with getBroadcast()) and deliver it to the service in
the Intent that starts the service. The service can then use the broadcast to deliver a result.

Multiple requests to start the service result in multiple corresponding calls to the
service's onStartCommand(). However, only one request to stop the service
(with stopSelf() or stopService()) is required to stop it.

Stopping a service

A started service must manage its own lifecycle. That is, the system doesn't stop or destroy
the service unless it must recover system memory and the service continues to run
after onStartCommand() returns. The service must stop itself by calling stopSelf(), or another
component can stop it by calling stopService().

Once requested to stop with stopSelf() or stopService(), the system destroys the service as
soon as possible.

If your service handles multiple requests to onStartCommand() concurrently, you shouldn't


stop the service when you're done processing a start request, as you might have received a
new start request (stopping at the end of the first request would terminate the second one).
To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the
service is always based on the most recent start request. That is, when you call stopSelf(int),
you pass the ID of the start request (the startId delivered to onStartCommand()) to which
your stop request corresponds. Then, if the service receives a new start request before you
are able to call stopSelf(int), the ID doesn't match and the service doesn't stop.

Caution: To avoid wasting system resources and consuming battery power, ensure that your
application stops its services when it's done working. If necessary, other components can
stop the service by calling stopService(). Even if you enable binding for the service, you
must always stop the service yourself if it ever receives a call to onStartCommand().

For more information about the lifecycle of a service, see the section below about Managing
the Lifecycle of a Service.

Creating a bound service

A bound service is one that allows application components to bind to it by


calling bindService() to create a long-standing connection. It generally doesn't allow
components to start it by calling startService().
Create a bound service when you want to interact with the service from activities and other
components in your application or to expose some of your application's functionality to other
applications through interprocess communication (IPC).

To create a bound service, implement the onBind() callback method to return an IBinder that
defines the interface for communication with the service. Other application components can
then call bindService() to retrieve the interface and begin calling methods on the service. The
service lives only to serve the application component that is bound to it, so when there are
no components bound to the service, the system destroys it. You do not need to stop a bound
service in the same way that you must when the service is started
through onStartCommand().

To create a bound service, you must define the interface that specifies how a client can
communicate with the service. This interface between the service and a client must be an
implementation of IBinder and is what your service must return from the onBind() callback
method. After the client receives the IBinder, it can begin interacting with the service through
that interface.

Multiple clients can bind to the service simultaneously. When a client is done interacting with
the service, it calls unbindService() to unbind. When there are no clients bound to the
service, the system destroys the service.

There are multiple ways to implement a bound service, and the implementation is more
complicated than a started service. For these reasons, the bound service discussion appears
in a separate document about Bound Services.

Sending notifications to the user

When a service is running, it can notify the user of events using snackbar
notifications or status bar notifications.

A snackbar notification is a message that appears on the surface of the current window for
only a moment before disappearing. A status bar notification provides an icon in the status
bar with a message, which the user can select in order to take an action (such as start an
activity).

Usually, a status bar notification is the best technique to use when background work such as
a file download has completed, and the user can now act on it. When the user selects the
notification from the expanded view, the notification can start an activity (such as to display
the downloaded file).

Managing the lifecycle of a service

The lifecycle of a service is much simpler than that of an activity. However, it's even more
important that you pay close attention to how your service is created and destroyed because
a service can run in the background without the user being aware.

The service lifecycle—from when it's created to when it's destroyed—can follow either of
these two paths:

 A started service

The service is created when another component calls startService(). The service then
runs indefinitely and must stop itself by calling stopSelf(). Another component can also
stop the service by calling stopService(). When the service is stopped, the system
destroys it.
 A bound service

The service is created when another component (a client) calls bindService(). The client
then communicates with the service through an IBinder interface. The client can close
the connection by calling unbindService(). Multiple clients can bind to the same service
and when all of them unbind, the system destroys the service. The service
does not need to stop itself.

These two paths aren't entirely separate. You can bind to a service that is already started
with startService(). For example, you can start a background music service by
calling startService() with an Intent that identifies the music to play. Later, possibly when the
user wants to exercise some control over the player or get information about the current
song, an activity can bind to the service by calling bindService(). In cases such as
this, stopService() or stopSelf() doesn't actually stop the service until all of the clients unbind.

Implementing the lifecycle callbacks

Like an activity, a service has lifecycle callback methods that you can implement to monitor
changes in the service's state and perform work at the appropriate times. The following
skeleton service demonstrates each of the lifecycle methods:

KotlinJava

class ExampleService : Service() {

private var startMode: Int = 0 // indicates how to behave if the service is killed

private var binder: IBinder? = null // interface for clients that bind

private var allowRebind: Boolean = false // indicates whether onRebind should be used

override fun onCreate() {

// The service is being created

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

// The service is starting, due to a call to startService()

return startMode

override fun onBind(intent: Intent): IBinder? {

// A client is binding to the service with bindService()

return binder

override fun onUnbind(intent: Intent): Boolean {


// All clients have unbound with unbindService()

return allowRebind

override fun onRebind(intent: Intent) {

// A client is binding to the service with bindService(),

// after onUnbind() has already been called

override fun onDestroy() {

// The service is no longer used and is being destroyed

Note: Unlike the activity lifecycle callback methods, you are not required to call the
superclass implementation of these callback methods.

Figure 2. The service lifecycle. The diagram on the left shows the lifecycle when the service
is created with startService() and the diagram on the right shows the lifecycle when the
service is created with bindService().
Figure 2 illustrates the typical callback methods for a service. Although the figure separates
services that are created by startService() from those created by bindService(), keep in mind
that any service, no matter how it's started, can potentially allow clients to bind to it. A
service that was initially started with onStartCommand() (by a client calling startService())
can still receive a call to onBind() (when a client calls bindService()).

By implementing these methods, you can monitor these two nested loops of the service's
lifecycle:

 The entire lifetime of a service occurs between the time that onCreate() is called and
the time that onDestroy() returns. Like an activity, a service does its initial setup
in onCreate() and releases all remaining resources in onDestroy(). For example, a music
playback service can create the thread where the music is played in onCreate(), and
then it can stop the thread in onDestroy().

Note: The onCreate() and onDestroy() methods are called for all services, whether they're
created by startService() or bindService().

 The active lifetime of a service begins with a call to


either onStartCommand() or onBind(). Each method is handed the Intent that was
passed to either startService() or bindService().

If the service is started, the active lifetime ends at the same time that the entire lifetime
ends (the service is still active even after onStartCommand() returns). If the service is bound,
the active lifetime ends when onUnbind() returns.

Note: Although a started service is stopped by a call to either stopSelf() or stopService(),


there isn't a respective callback for the service (there's no onStop() callback). Unless the
service is bound to a client, the system destroys it when the service is stopped—
onDestroy() is the only callback received.

For more information about creating a service that provides binding, see the Bound
Services document, which includes more information about the onRebind() callback method
in the section about Managing the lifecycle of a bound service.

What is a web service? Why it is required? How a web service


can be consumed in an Android application?
Covered above

What is Action Bar? Write a program to Add items in


ActionBar?
ActionBar in Android with Example
In Android applications, ActionBar is the element present at the top of the activity screen. It
is a salient feature of a mobile application that has a consistent presence over all its
activities. It provides a visual structure to the app and contains some of the frequently used
elements for the users. Android ActionBar was launched by Google in 2013 with the release
of Android 3.0(API 11). Before that, the name of this top most visual element was AppBar.
AppBar contains only the name of the application or current activity. It was not very much
useful for the users and developers also have negligible option to customize it.

Google announced a support library along with the introduction of ActionBar. This library is
a part of AppCompat and its purpose is to provide backward compatibility for older versions
of Android and to support tabbed interfaces. All applications that use the default theme
provided by the Android(Theme.AppCompat.Light.DarkActionBar), contains an ActionBar by
default. However, developers can customize it in several ways depending upon their needs.
Components included in the ActionBar are:

 App Icon: Display the branding logo/icon of the application.

 View Controls: Section that displays the name of the application or current activity.
Developers can also include spinner or tabbed navigation for switching between views.

 Action Button: Contains some important actions/elements of the app that may be
required to the users frequently.

 Action Overflow: Include other actions that will be displayed as a menu.

Designing a Custom ActionBar

The following example demonstrates the steps involved in creating a custom ActionBar for
the MainActivity of an application. All important aspects of visual elements like icon, title,
subtitle, action buttons, and overflow menu will be covered.

Looking to become an expert in Android App Development? Whether you're a student or a


professional aiming to advance your career in mobile app development, our course,
"Android App Development with Kotlin," available exclusively on GeeksforGeeks, is the
perfect fit for you.

Note: Following steps are performed on Android Studio version 4.0

Step 1: Default ActionBar

As mentioned earlier, every android app contains an ActionBar by default. This pre-included
ActionBar display title for the current activity that is managed by
the AncdroidManifest.xml file. The string value of the application’s title is provided
by @string/app_name resource present under the application nodes.

<application

…..

…..

android:label=”@string/app_name”

…..

</application>

Output:

Step 2: Creating a new directory and design items of ActionBar

To code the elements of ActionBar, create a new directory in the resource folder of the
application project files. Right-click on the res folder and selects New -> Directory. Give the
name “menu” to the new directory.

Further, create a new Menu Resource File by right click on the menu directory. As the
ActionBar is being created for the main Activity, type the name as “main” to the Menu
Resource File. With this, a new file named “main.xml” must be created under the menu
directory. In this file, one can declare the items which will be displayed as the action
buttons of the ActionBar.

For every menu items, the following attributes are needed to be configured:

 android:title: Its value contains the title of the menu item that will be displayed when
a user clicks and holds that item in the app.

 android:id: A unique ID for the menu item that will be used to access it anywhere in
the whole application files.

 android:orderInCategory: The value of this attribute specify the item’s position in


the ActionBar. There are two ways to define the position of different menu items. The
first one is to provide the same value of this attribute for all items and the position will
be defined in the same order as they are declared in the code. The second way is to
provide a different numeric value for all items and then the items will position
themselves according to ascending order of this attribute’s value.

 app:showAsAction: This attribute defines how the item is going to be present in the
action bar. There are four possible flags to choose from:

o a. always: To display the item in the ActionBar all the time.

o b. ifRoom: To keep the item if space is available.

o c. never: With this flag, the item will be not be displayed as an icon in ActionBar,
but will be present in the overflow menu.
o d. withText: To represent an item as both icon and the title, one can append this
flag with the always or ifRoom flag(always|withText or ifRoom|withText).

 android:icon: The icon of an item is referenced in the drawable directories through


this attribute.

Icon of an ActionBar Item

In order to provide an icon to an item, right-click on the res folder, select new, and
then Image Asset. A dialog box will appear, choose the Icon Type as Action Bar and Tab
Icons. Choose assets type as “Clip Art” and select an image from the clip art collection.
Provide a desired name to the icon. Click on Next, then Finish. This icon will now get loaded in
the drawable directory of the res folder. The name provided by the developers to these icons
will now be used to reference the item’s icon resource.

Below is the code to place a search icon, refresh icon, and an overflow menu in the ActionBar.

 XML

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

<menu xmlns:app="http://schemas.android.com/apk/res-auto"

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

<!-- action button for search -->

<item android:title="search"

android:id="@+id/search"
android:orderInCategory="100"

app:showAsAction="ifRoom"

android:icon="@drawable/search_icon"/>

<!-- action button for refresh -->

<item android:title="refresh"

android:id="@+id/refresh"

android:orderInCategory="100"

app:showAsAction="ifRoom"

android:icon="@drawable/refresh_icon"/>

<!-- action button for copy -->

<item android:title="copy"

android:id="@+id/copy"

android:orderInCategory="100"

app:showAsAction="never"

android:icon="@drawable/copy_icon"/>

</menu>

Output:

Step 3: Working with the Activity File

The items of an ActionBar is designed with a purpose to perform some operations. Those
operations/actions of the items are declared in that Activity file for which the ActionBar has
been designed. In this example, the target activity is the MainActivity file. Further, the
custom title, subtitle, and application logo are also defined in this file. Below is the proper
code to design all mentioned items and to display a toast message when a user clicks on the
items of ActionBar.

 Java

 Kotlin

import androidx.annotation.NonNull;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate( Bundle savedInstanceState ) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// calling this activity's function to

// use ActionBar utility methods

ActionBar actionBar = getSupportActionBar();

// providing title for the ActionBar

actionBar.setTitle(" GfG | Action Bar");

// providing subtitle for the ActionBar

actionBar.setSubtitle(" Design a custom Action Bar");

// adding icon in the ActionBar

actionBar.setIcon(R.drawable.app_logo);

// methods to display the icon in the ActionBar

actionBar.setDisplayUseLogoEnabled(true);

actionBar.setDisplayShowHomeEnabled(true);

// method to inflate the options menu when

// the user opens the menu for the first time


Output:

Step 4: Color of the ActionBar

Head over to style.xml file located in the values directory of the res folder. To change
the default color of the ActionBar, one has to change the colorPrimary resource. Below is
the code to make the ActionBar color ‘green’.

 XML

<resources>

<!-- Base application theme. -->

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

<!-- Customize your theme here. -->

<!-- provided green color to the ActionBar -->

<item name="colorPrimary">#0F9D58</item>

<item name="colorPrimaryDark">@color/colorPrimaryDark</item>

<item name="colorAccent">@color/colorAccent</item>

</style>

</resources>

Output:

Step 5: Working with activity_main.xml file

This file defines the layout of the activity. In this example, the prime focus is on ActionBar,
thus the activity will contain only a simple TextView. Below is the code.

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

android:background="#168BC34A"

tools:context=".MainActivity">

<!-- Adding a TextView in the activity -->

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello Geek!!"

android:textColor="#000000"

android:textSize="24sp"

android:textStyle="bold"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintLeft_toLeftOf="parent"

app:layout_constraintRight_toRightOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Output:

Video Player

00:00

00:23

Advantages of ActionBar

 Provides a customized area to design the identity of an app

 Specify the location of the user in the app by displaying the title of the current Activity.

 Provides access to important and frequently used actions

 Support tabs and a drop-down list for view switching and navigation.

Disadvantages of ActionBar

 All features of the ActionaBar are not introduced at once but were introduced with the
release of different API levels such as API 15, 17, and 19.

 The ActionBar behaves differently when it runs on different API levels.


 The features that were introduced with a particular API does not provide backward
compatibility.

Explain about Internet download Manager Usage in Android


Mobile Application?
Internet Download Manager
Internet Download Manager (IDM) is a popular download management tool widely used
on desktop platforms, particularly Windows, to enhance the speed, organization, and control
over file downloads. On Android, however, IDM itself is not directly available as it is primarily
designed for desktop use. However, the concept of download management in mobile apps
can still be implemented in a similar way, using Android's native download manager or third-
party libraries that offer similar functionality.

In this explanation, I’ll first clarify how download management works on Android, and then
explain how a mobile app could implement features similar to Internet Download Manager
(IDM) for handling downloads, including acceleration, pause/resume, and file management.

Internet Download Manager Features (IDM) Overview

IDM typically offers the following key features on desktop platforms:

1. Download Acceleration: IDM increases download speeds by using multiple


connections to download parts of a file simultaneously.

2. Pause and Resume: It allows you to pause downloads and resume them later, even
after closing the application or restarting the computer.

3. Scheduling: IDM lets users schedule downloads at specific times.

4. Batch Downloads: IDM can download multiple files at once and organize them
efficiently.

5. Integration with Browsers: IDM integrates with web browsers (like Chrome, Firefox)
to capture download links directly from the browser.

6. Error Recovery and Resume: IDM can recover from network errors and continue
from where it left off.

Although IDM itself isn't available natively on Android, its core concepts can be replicated on
the platform using tools provided by the Android SDK or third-party libraries.

Implementing IDM-like Features in an Android Mobile Application

1. Download Management in Android (Android Download Manager)

Android provides its own DownloadManager class to handle downloads. This system service
provides a simple interface for managing downloads in Android apps. It handles tasks like
download queue management, file saving, pause, resume, and retries on network failure,
making it ideal for implementing IDM-like features.

Key Features of Android’s DownloadManager:

 Automatic Handling of Background Downloads: Downloads continue even if the


app is not in the foreground.
 Pause and Resume: Downloads can be paused and resumed without losing progress.

 Error Recovery: It can automatically retry failed downloads due to network issues.

 Access to System Download History: Users can see the status of their downloads in
the system's notification shade.

Example of Using Android’s DownloadManager:

DownloadManager downloadManager = (DownloadManager)


getSystemService(Context.DOWNLOAD_SERVICE);

Uri downloadUri = Uri.parse("https://example.com/file_to_download.zip");

// Set up a request for the download

DownloadManager.Request request = new DownloadManager.Request(downloadUri);

request.setTitle("Downloading File");

request.setDescription("Please wait while the file downloads...");

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMP
LETED);

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
"file_to_download.zip");

// Enqueue the download request

long downloadId = downloadManager.enqueue(request);

This code will start downloading the file and show a notification to the user. The
DownloadManager class automatically handles the downloading process, including retries
and progress tracking.

2. Download Acceleration (Parallel Downloading)

While Android’s native DownloadManager does not natively support multi-threaded


downloading (splitting a file into multiple parts for simultaneous download), you can
implement parallel downloading manually in your app by downloading different parts of a
file using multiple HTTP connections.

To achieve this, you can use libraries such as OkHttp or Retrofit to manage custom HTTP
requests, splitting a file into parts (usually based on byte ranges) and then downloading
those parts concurrently. Once all parts are downloaded, you can merge them into the final
file.

For parallel downloading, you need to:

 Split the file into several chunks (e.g., based on byte ranges).

 Use multiple threads or asynchronous requests to download these chunks


simultaneously.

 Merge the downloaded parts into a single file.

Example (Conceptual):
// Pseudo-code to demonstrate parallel downloading

int numThreads = 4; // Split the file into 4 parts

long fileSize = 1000; // Size of the file in bytes

long chunkSize = fileSize / numThreads;

// Create download tasks for each part

for (int i = 0; i < numThreads; i++) {

long startByte = i * chunkSize;

long endByte = (i == numThreads - 1) ? fileSize : (startByte + chunkSize);

downloadPart(startByte, endByte, i);

In this example, downloadPart is a function that downloads a specific chunk of the file. Once
all parts are downloaded, they can be merged to form the complete file.

3. Pause and Resume Downloads

Android’s DownloadManager allows you to pause and resume downloads, but it doesn't
allow direct control for pausing and resuming by the app itself, since it is handled at the
system level.

If you want more control, like when to pause and resume based on app-specific logic (e.g.,
user-initiated actions), you could implement a custom solution using background services and
manual control over HTTP requests. You can use libraries like OkHttp to download files and
pause/resume downloads by managing the download state yourself.

Example (Conceptual):

// Pseudo-code to demonstrate pausing and resuming with custom download logic

if (isPaused) {

// Stop the download thread

} else {

// Start or resume downloading

4. Scheduling Downloads

To schedule downloads at specific times, Android’s JobScheduler or WorkManager can be


used. These APIs allow you to define tasks that should be executed at a later time, even if the
app is not running in the foreground.

Example using WorkManager to schedule a download:

OneTimeWorkRequest downloadWorkRequest = new


OneTimeWorkRequest.Builder(DownloadWorker.class)

.setInitialDelay(1, TimeUnit.HOURS) // Delay the download by 1 hour


.build();

WorkManager.getInstance(context).enqueue(downloadWorkRequest);

WorkManager is recommended because it respects Doze Mode and App Standby, ensuring
that your app behaves well in low-power situations.

5. Notifications and User Feedback

To replicate IDM-like notifications (like showing download progress or completion), you can
use NotificationManager to show notifications for your download tasks.

Example of showing a download progress notification:

NotificationManager notificationManager = (NotificationManager)


getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,


"download_channel")

.setContentTitle("Downloading File")

.setContentText("Downloading...")

.setSmallIcon(R.drawable.ic_download)

.setProgress(100, 0, false);

// Update progress as download proceeds

notificationBuilder.setProgress(100, progress, false);

notificationManager.notify(notificationId, notificationBuilder.build());

6. Handling Multiple Downloads

If you want to download multiple files simultaneously, you can enqueue multiple requests
using DownloadManager or manage the downloads manually by keeping track of each
download's status.

For batch downloads, you could:

 Use multiple DownloadManager requests to download files concurrently.

 Create a queue or batch system where the next file begins downloading only after the
current download completes.

How to Publishing your application on the Android Market.


Explain?
Publish your app

Important: From August 2021, new apps are required to publish with the Android App
Bundle on Google Play. New apps larger than 200 MB are now supported by either Play
Feature Delivery or Play Asset Delivery. From June 2023, new and existing TV apps are
required to be published as App Bundles.

Publishing is the general process that makes your Android app available to users. When you
publish an Android app, you do the following:

 Prepare the app for release.

During the preparation step, you build a release version of your app.

 Release the app to users.

During the release step, you publicize, sell, and distribute the release version of your
app, which users can download and install on their Android-powered devices.

This page provides an overview of the process for preparing to publish your app. If you plan
to publish on Google Play, read Release with confidence.

If you use a Continuous Integration server, you can configure it to automate the steps
outlined here. You can also configure it to push builds to your internal test distribution
channel.

Prepare your app for release

Preparing your app for release is a multistep process involving the following tasks:

 Configure your app for release.

At a minimum, you need to make sure that logging is disabled and removed and that
your release variant has debuggable false for Groovy or isDebuggable = false for Kotlin
script set. You should also set your app's version information.

 Build and sign a release version of your app.

You can use the Gradle build files with the release build type to build and sign a release
version of your app. For more information, see Build and run your app.

 Test the release version of your app.

Before you distribute your app, you should thoroughly test the release version on at
least one target handset device and one target tablet device. Firebase Test Lab is useful
for testing across a variety of devices and configurations.

 Update app resources for release.

Make sure that all app resources, such as multimedia files and graphics, are updated
and included with your app or staged on the proper production servers.

 Prepare remote servers and services that your app depends on.

If your app depends on external servers or services, make sure they are secure and
production ready.

You might need to perform several other tasks as part of the preparation process. For
example, you need to create an account on the app marketplace you want to use, if you don't
already have one. You also need to create an icon for your app, and you might want to
prepare an End User License Agreement (EULA) to protect yourself, your organization, and
your intellectual property.

To learn how to prepare your app for release, see Prepare for release for step-by-step
instructions for configuring and building a release version of your app.
When you are finished preparing your app for release, you have a signed APK file that you
can distribute to users.

Release your app to users

You can release your Android apps several ways. Typically, you release apps through an app
marketplace such as Google Play. You can also release apps on your own website or by
sending an app directly to a user.

Release through an app marketplace

If you want to distribute your apps to the broadest possible audience, release them through
an app marketplace.

Google Play is the premier marketplace for Android apps and is particularly useful if you want
to distribute your apps to a large global audience. However, you can distribute your apps
through any app marketplace, and you can use multiple marketplaces.

Release your apps on Google Play

Google Play is a robust publishing platform that helps you publicize, sell, and distribute your
Android apps to users around the world. When you release your apps through Google Play,
you have access to a suite of developer tools that let you analyze your sales, identify market
trends, and control who your apps are being distributed to.

Google Play also gives you access to several revenue-enhancing features such as in-app
billing and app licensing. The rich array of tools and features, coupled with numerous end-
user community features, makes Google Play the premier marketplace for selling and buying
Android apps.

Releasing your app on Google Play is a simple process that involves three basic steps:

 Prepare promotional materials.

To fully leverage the marketing and publicity capabilities of Google Play, you need to
create promotional materials for your app such as screenshots, videos, graphics, and
promotional text.

 Configure options and uploading assets.

Google Play lets you target your app to a worldwide pool of users and devices. By
configuring various Google Play settings, you can choose the countries you want to
reach, the listing languages you want to use, and the price you want to charge in each
country.

You can also configure listing details such as the app type, category, and content
rating. When you are done configuring options, you can upload your promotional
materials and your app as a draft app.

 Publish the release version of your app.

If you are satisfied that your publishing settings are correctly configured and your
uploaded app is ready to be released to the public, click Publish. Once it has passed
Google Play review, your app will be live and available for download around the world.

For more information, see How Google Play works.

Release through a website


If you don't want to release your app on a marketplace like Google Play, you can make the
app available for download on your own website or server, including on a private or
enterprise server.

To release through a website:

1. Prepare your app for release.

2. Host the release-ready APK file on your website.

3. Provide a download link to users.

When users browse to the download link from their Android-powered devices, the file is
downloaded and the Android system automatically starts installing it on the device.

Note: The installation process will start automatically only if the user has configured their
settings to allow the installation of apps from unknown sources.

Although it is relatively easy to release your app on your own website, it can be inefficient.
For example, if you want to monetize your app, you need to process and track all financial
transactions yourself, and you can't use Google Play's in-app billing service to sell in-app
products. You also can't use app licensing to help prevent unauthorized installation and use of
your app.

User opt-in for unknown apps and sources

Android protects users from inadvertent download and installation of apps from locations
other than a trusted, first-party app store, such as Google Play. Android blocks such installs
until the user opts into allowing the installation of apps from other sources. The opt-in
process depends on the version of Android running on the user's device:

Figure 1. The Install unknown apps system settings screen, where users grant permission
for a particular source to install unknown apps.

 On devices running Android 8.0 (API level 26) and higher, users must navigate to
the Install unknown apps system settings screen to enable app installations from a
particular source.

 On devices running Android 7.1.1 (API level 25) and lower, users must either enable
the Unknown sources system setting or allow a single installation of an unknown app.

Install unknown apps

On devices running Android 8.0 (API level 26) and higher, users must grant permission to
install apps from a source that isn't a first-party app store. To do so, they must enable
the Allow app installs setting for that source within the Install unknown apps system
settings screen, shown in figure 1.
Note: Users can change this setting for a particular source at any time. Therefore, a source
that installs unknown apps should always call canRequestPackageInstalls() to check
whether the user has granted that source permission to install unknown apps. If this method
returns false, the source should prompt the user to re-enable the Allow app installs setting
for that source.

Unknown sources

Figure 2. The Unknown sources setting determines whether users can install apps that
aren't downloaded from Google Play.

To permit the installation of apps from non-first-party sources on devices running Android
7.1.1 (API level 25) and lower, users enable the Unknown sources setting
in Settings > Security, as shown in Figure 2.

When users attempt to install an unknown app on a device running Android 7.1.1 (API level
25) or lower, the system sometimes shows a dialog that asks the user whether they want to
allow only one particular unknown app to be installed. In most cases, it is recommended that
users allow only one unknown app installation at a time, if the option is available.

In either case, users need to make this configuration change before they can download and
install unknown apps onto their devices.

Explain different skills required for Android Developer?


Android is an open-source operating system for mobiles developed by Google. Based on
the Linux operating system, Android has become a popular computing platform. Over the
past decade, Android has effectively become the world’s most popular operating system by
several measures. As technology continues to evolve rapidly, the role of an Android
developer remains crucial in shaping the digital landscape and driving innovations
in mobile application development.

In 2024, the expectations for Android developers have increased, requiring a diverse
set of technical and non-technical skills and adherence to best practices. From mastering
modern programming languages to creating scalable, secure, and efficient
applications, Android developers must stay updated with the latest trends and
technologies to deliver high-quality applications.

What is Android Development?

Android development refers to the process of creating applications that can be installed on
devices that run the Android Operating System. Android, an operating
system developed by Google, is a widely used mobile operating system across the
world, powering millions of smartphones, tablets, smartwatches, and other devices. Android
developers can use languages Java or Kotlin to develop Android applications, which further
has steps like coding, testing, and deployment of apps. The Android development
ecosystem is rich and large and offers features and libraries, that allow developers to create
seamless quality Android applications.
Top 10 Skills For Android Developers in 2024

In addition to technical skills, Android developers should also prioritize enhancing


their knowledge of design principles and user experience (UX) in 2024.
Understanding material design concepts, accessibility standards, and best practices for
delivering exceptional user experiences will be crucial. By staying updated with emerging
technologies such as Virtual Reality (VR), Augmented Reality (AR), Internet of Things
(IoT), and Machine Learning (ML), developers can also stay ahead of trends and meet the
demands of the evolving mobile app landscape.

1. Android Foundations

Android development's core is based on the programming languages Kotlin and Java. Java is
the traditional language for Android apps, while Kotlin offers a simpler, more modern
alternative. Developers should grasp key concepts like syntax, collections, concurrency, and
functional programming. User interfaces are designed using XML, which is linked to
Kotlin/Java files containing the app's logic. Android Studio, the primary development
environment, uses Gradle to manage builds and dependencies. Understanding Gradle's role
in the build process is essential for efficient app development.

Key Points:

 Proficiency in Kotlin and Java programming languages.

 Designing layouts using XML.

 Utilizing Android Studio and Gradle for development.

 Managing dependencies with Gradle.

2. Android Interactivity

User interaction in Android apps revolves around Activities, which are screens where users
interact with the app. Developers must handle events like gestures, keyboard input, and
screen orientation changes to enhance user experience. Each Activity can exist in portrait or
landscape mode, and maintaining stability during orientation changes is crucial.

Key Points:

 Handling user events and gestures.

 Managing screen orientation changes.

 Implementing interactive elements within Activities.

 Ensuring stability across different screen configurations.

3. Android UI

Creating a modern UI involves using layouts and widgets effectively. Developers should follow
Material Design guidelines and use tools like RecyclerView for lists, ConstraintLayout for
complex designs, and animations to enhance user experience. Adapting layouts for different
devices, like tablets and smartphones, is essential, and custom components may be needed
for unique requirements.

Key Points:

 Following Material Design guidelines.

 Using RecyclerView and ConstraintLayout for efficient layouts.


 Implementing animations for better UX.

 Adapting UI for multiple device types with Fragments.

4. Implementing Navigation

Effective navigation helps users move through the app seamlessly. Key elements include the
app bar (Toolbar), navigation drawer, and BottomNavigationView. These elements enable
users to switch between screens and access additional features. Intents, both explicit and
implicit, allow for launching new Activities or sharing data between apps.

Key Points:

 Using Toolbar and navigation drawer for primary navigation.

 Implementing BottomNavigationView for tab-based navigation.

 Employing ViewPager for swipeable tabs.

 Using Intents for Activity transitions and data sharing.

5. Notifications

Notifications are a powerful tool for boosting user engagement. They are messages that
appear outside your app’s interface to provide reminders, updates, or important information.
Users can tap notifications to open your app or perform actions directly from the notification
itself. To make the most of notifications, you should create and customize them, add
actionable elements, and group multiple notifications using notification channels.

Key Points:

 Enhance user engagement with timely notifications.

 Customize notification layout for better user experience.

 Add actions to notifications for direct user interaction.

 Use notification channels to group and manage multiple notifications.

6. Jetpack Compose

Jetpack Compose, is a modern UI toolkit for building native Android applications developed by
Google. Jetpack Compose uses a declarative approach to create user interfaces and
also allows developers to describe UI states and their behavior without worrying
about their complexities. By starting working with Jetpack Compose, developers can
streamline UI development, leverage its powerful features such as state management, and
deliver a seamless experience to users. To leverage its features developers are switching
from the Imperative approach to the Declarative approach.Knowing Jetpack Compose deeper
can help developers to keep themself walk with modern trends.

Key Features

 State management

 Understanding of Recomposition

 Composable lifecycle

 Theming and Styling

 Gestures handling
 Navigation handling

 Managing callbacks

7. MVVM Architecture

Implementing architecture in a project helps in maintaining and scaling large-size projects


easily. Model-View-View-Model (MVVM) architecture is a strong foundation for
building scalable and maintainable Android applications. Developers can decouple the
UI logic from business logic by using its components such as live data and ViewModel. With
MVVM architectures Android developers can ensure separation of concerns, enhance
testabilities, and also make collaboration among developers seamless. This can be
considered as primary skills that Android developers must take into consideration for
creating quality and seamless Android applications.

Below is the breakdown of each component of MVVM architecture.

 Model: The Model is independent of UI and does not interact directly with View or
VireModel.Typically it consists of data classes, data entities, and network API calls.

 View: The View component is responsible for displaying the user interface and handles
user interactions. The view can be Activyty, Fragments, or XML layouts.

 ViewModel: It contains the business logic, and acts as a messenger between View and
Model. It has its own lifecycle like Fragment and Activity.

8. Jetpack Components

Jetpack components are a collection of libraries, tools, and guidance offered by Google to
facilitate Android developers to build high-quality applications more easily and
efficiently. Jetpack components were introduced to mainly address the issues that
Android developers face in general such as navigation issues, lifecycle-related
issues, simplifying data persistence, and integration of platform API. All these
components are backward compatible, so they can work with a wide range of Android
operating systems. All components are modular which allows developers to adopt only
needed components.

Below are key components available in Jetpack components.

 ViewModel: The ViewModel component contains the business logic, it separates UI


data and logic from UI controllers such as Fragment and Activities.ViewModel stores UI-
related data that is generally lost due to device configuration changes.

 LiveData: Live data is an observable lifecycle-aware data holder class that respects
the lifecycle of other components such as Fragments and Activities. It helps to avoid
memory leaks and crashes that happen due to stale data. LiveData ensures UI
components will update when they are in the activity’s lifecycle.

 Navigation: Navigation components simplify the complex navigation flow and ensure
consistence navigation experience across the app. It allows developers to design
navigation graphs to manage navigation within the Android app.

 Pagging: Pagging components help in loading and displaying large data sets from local
storage or network APIs in the form of pagination. It loads data in chunks and handles
fetching more data on user scrolls by ensuring a smooth UI experience.

 Work Manager: The WorkManager library is used to manage background tasks in the
Android app such as network calls, DB operations, or periodic tasks. WorkManager
guarantees the execution of tasks whether the app exists or not.

9. Dependency Injections

Dependency injection facilitates the inversion of the control principle, it enables


developers to manage object dependencies more effectively by promoting
modular, reusable, and testable code. DI is a commonly used component in large-scale
projects as it makes projects easily maintainable due to its code modularization and code
reusability feature. With DI Developers can inject class instances rather than creating class
instances every time.

Key benefits of Dependency injection include Modularity, Testability, Flexibility,


and Reusability. Understanding DI is a bit tricky to start, but this is one of the must-have
skills that Android developers should consider.

There are a couple of libraries used to implement DI in Android projects such


as Dagger, Hilt, and Coin. Hilt is nowadays the most commonly used DI library by Android
developers due to its simple integration steps.

10. Firebase

Offered by Google, Firebase is a comprehensive platform that provides a range of


tools and backend services that help developers to build, improve, and grow their
mobile applications such as Android and iOS. Services provided by Firebase include
Authentication(Google, Firebase, GitHub, Twitter), real-time database, FireStore(Cloud
storage), analytics, crash reporting, cloud messaging, and many more services, all
seamlessly can be integrated and managed from a single console provided by
Firebase.Having Firebase skills hands-on is very helpful for Android developers as it allows
developers to create a complete app without the need for any other back-end
server(developers can use cloud storage provided by Firebase).

Below are key features of Firebase

 Authentication

 Real-time database

 FireStore database

 FileStorage

 Firebase cloud messaging

 Remote config

 Analytics

 Dynamic Links

 Crash reporting

 AdMob Integration

Discuss the architecture and working of Windows Phone.


Architecture and Working of Windows Phone
Windows Phone (often referred to as WP) was a line of smartphones developed by Microsoft.
It was designed as a successor to Windows Mobile and Windows CE, offering a modern,
efficient, and visually appealing user interface with a focus on simplicity and user experience.
Although Microsoft stopped supporting Windows Phone in 2017, it remains an interesting
case study in mobile operating systems.

The architecture of Windows Phone is built to be tightly integrated with both hardware and
software, ensuring optimal performance, security, and usability. Let's break down the key
components of the Windows Phone architecture and its workings.

1. Windows Phone Architecture Overview


The architecture of Windows Phone can be represented in a layered diagram that illustrates
the separation of different system components and how they interact. Here's a simplified
architecture diagram that showcases the major layers and components involved in the
Windows Phone operating system:

Windows Phone Architecture Diagram

Explanation of Each Layer:

1. Application Layer:

o This layer contains the Native apps (written using C#, XAML, Silverlight or
Windows Runtime) and Web apps (built with HTML, CSS, and JavaScript).

o Apps interact with the system through the Windows Phone Runtime APIs,
using a managed environment provided by the OS.

2. Windows Phone Runtime (App Platform):

o The runtime provides APIs for app development, such as file access, networking,
sensors, and multimedia.

o It also handles services like Push Notifications and Background Tasks,


enabling apps to run in the background.
3. User Interface (UI) Layer:

o The UI is based on the Metro UI, which is minimalist and tile-based. The Start
screen uses Live Tiles to show dynamic content such as notifications,
messages, and updates.

o This layer also handles the hardware buttons like the Back, Search, and Start
buttons.

4. Networking and Connectivity Layer:

o Handles 3G/4G, Wi-Fi, Bluetooth, GPS and other connectivity features.

o This layer also supports Cloud Storage (OneDrive) and Exchange


Synchronization for emails, contacts, and calendars.

5. Security Layer:

o Ensures app sandboxing (isolating apps for security), device encryption, and
secure boot mechanisms, which prevent unauthorized access and malware.

6. Windows Phone Kernel (Windows CE):

o The core of the system, providing low-level services like memory management,
process scheduling, and hardware abstraction (via the HAL).

7. Hardware Layer:

o Includes the physical components of the device, such as the CPU, GPU,
memory, camera, display, and other sensors.

o The Hardware Abstraction Layer (HAL) enables communication between the


software layers and hardware.

2. Working of Windows Phone


The working of Windows Phone can be understood by breaking down how the operating
system operates when a user interacts with the device, how apps run, and how the core
system features are managed.

Boot Process:

When a user powers on a Windows Phone device, the following steps occur:

1. Power On and Bootloader: The device performs the initial hardware checks and
hands control over to the bootloader, which loads the OS from storage.

2. Kernel Initialization: The Windows CE kernel is loaded, initializing system


processes and preparing the hardware abstraction layer.

3. User Interface Loading: After the kernel and system services are initialized, the UI
layer (Metro UI) is loaded, presenting the Start screen with Live Tiles.

4. App Launch: The user interacts with the device, launching apps through the UI. The
app is loaded from storage, and the operating system provides the necessary system
resources (e.g., memory, networking, sensors) for the app to function.

App Execution:

When you launch an app, it interacts with the system in the following way:
1. App Sandbox: The app is isolated within its own sandbox environment. It can only
access resources and data that are specifically allowed by the OS.

2. App API Access: Apps communicate with the OS through Windows Phone Runtime
APIs. These APIs allow access to hardware (like the camera, GPS), networking, sensors,
etc.

3. Multitasking: Windows Phone uses a task-switching model, allowing users to switch


between running apps. Apps are paused in the background to save resources, but
certain apps (like music players or navigation apps) can continue to run with limited
resources.

4. Notifications and Background Tasks: Apps can send notifications (e.g., incoming
messages or reminders) via the Notification Service. Background tasks allow apps to
periodically perform actions, like syncing data, even when they’re not actively running
on the screen.

App Store and Installation:

Apps are installed from the Windows Phone Store. After the user selects an app, the
following happens:

1. Store API Access: The app is downloaded and installed via the Windows Phone
Store APIs.

2. Installation: The app is placed in the app folder, and required system resources are
allocated (e.g., storage space, permissions).

3. App Lifecycle: Once installed, the app can be launched via the Start screen. The app’s
lifecycle (from launch, execution, to background and termination) is managed by the
operating system.

Background and Multitasking:

Windows Phone uses a lightweight multitasking system. While apps can run in the
background, only apps that have permission to run tasks in the background can perform
operations like syncing, location tracking, or playing music.

Discuss about windows phone and its platform.

Explain in detail the importance of delivery of Mobile


Application?
The Importance of Delivery in Mobile Application Development
The delivery of mobile applications refers to the process by which an application is made
available for end users to download, install, and use. This process is critical in mobile app
development, as it determines the app's accessibility, usability, security, and overall user
experience. Successful mobile application delivery impacts the success of the app in the
marketplace, its adoption by users, and its long-term performance.
There are several aspects of the mobile app delivery process, including preparing the app for
launch, choosing the right platforms for distribution, ensuring the app is optimized for the
best performance, managing updates, and monitoring the app after release. The importance
of proper delivery cannot be overstated, as it plays a central role in the success and
sustainability of a mobile app.

Key Elements of Mobile App Delivery

1. App Deployment Process

o App Store Submission: For Android and iOS apps, the primary method of
delivery is through the Google Play Store and Apple App Store. Developers
must ensure that the app complies with the platform’s guidelines, undergoes
rigorous testing, and meets the technical and design standards required for
approval.

o App Distribution Mechanisms: Delivery can also take place via Enterprise
app stores or through Direct APK installations (Android) or enterprise
distribution programs (iOS). These methods are often used for internal or
private apps within organizations.

o Cross-platform Delivery: Many developers aim to create cross-platform apps


(Android, iOS, etc.), which requires careful consideration of the tools used to build
the app and whether the app will be delivered through a hybrid approach (using
frameworks like React Native, Flutter, etc.) or as native apps.

2. App Store Optimization (ASO)

o Just like Search Engine Optimization (SEO) for websites, App Store
Optimization (ASO) plays a key role in improving the visibility of a mobile
application. ASO involves optimizing the app’s metadata (name, description,
keywords, screenshots, etc.) to increase discoverability in app stores.

o ASO ensures that an app reaches the maximum number of potential users. It
affects rankings in the app stores and plays a crucial role in improving
downloads.

3. App Compatibility

o Device Compatibility: Delivery of mobile apps must account for different types
of mobile devices. Apps should be compatible across a wide range of screen
sizes, hardware configurations, and OS versions.

o OS Compatibility: Mobile app developers need to ensure the app works


seamlessly across different mobile operating systems (Android, iOS). This may
involve creating separate codebases or utilizing cross-platform tools that help
maintain compatibility across platforms.

o Network Compatibility: Since mobile apps rely heavily on internet connections,


ensuring compatibility with various network types (Wi-Fi, 3G, 4G, and 5G) is also
vital for ensuring smooth performance.

4. Quality Assurance & Testing

o Before the app is delivered to the user, it must go through rigorous quality
assurance (QA) testing to ensure that it is bug-free, reliable, and offers a
seamless user experience.
o Automated testing, unit testing, UI testing, and load testing are critical
steps that ensure the app works well in all situations, handles crashes gracefully,
and performs well under varying network conditions.

o Beta Testing: Beta testing allows a select group of users to test the app before
full release. This phase helps identify potential issues and gives insights into user
preferences and the overall performance of the app.

5. Security and Privacy Compliance

o As mobile apps handle sensitive user data (such as personal, financial, and
location data), ensuring security during the delivery process is of utmost
importance.

o Developers must integrate robust data encryption, secure authentication


mechanisms, and compliance with regulations such as the General Data
Protection Regulation (GDPR) or the California Consumer Privacy Act
(CCPA) to safeguard user privacy.

o App delivery also requires developers to stay current with security updates and
ensure timely patches for vulnerabilities that could compromise user data.

6. User Experience (UX) and Performance Optimization

o The user experience is one of the most crucial factors determining an app’s
success. App delivery involves ensuring that the app is intuitive, user-friendly,
and well-optimized for different device types.

o Performance optimization during the delivery phase ensures that the app loads
quickly, functions smoothly, and uses system resources efficiently (memory,
battery, and CPU). It should also work effectively in low network conditions or
with limited resources.

7. App Launch and Marketing

o The launch of the mobile app is the point at which the app is officially delivered to
the users. The launch should be accompanied by a marketing strategy to
generate buzz and attract downloads.

o Public relations efforts, advertisements, social media promotions, and app


store features all help to ensure a successful launch.

o Well-executed marketing campaigns can drive initial downloads and contribute


significantly to the app’s early success.

8. Post-Launch Monitoring and Updates

o Post-launch monitoring is crucial for tracking user feedback, bug reports, app
crashes, and performance issues. Tools like Crashlytics, Google Analytics, and
Firebase help track and measure the app’s success and user engagement.

o Regular app updates improve the app's functionality, fix bugs, and add new
features. Versioning and managing backward compatibility are important to
ensure users receive timely and efficient updates.

o A/B testing and user feedback allow developers to fine-tune the app and
introduce enhancements based on real-world data.
Why Delivery is Important
1. User Adoption and Experience:

o The speed and reliability of the delivery process directly affect the user
adoption rate and their overall experience with the app.

o An app with slow downloads, poor performance, or frequent crashes will


likely receive poor reviews and uninstalls, while apps that offer seamless
installation, fast performance, and a smooth user experience retain more users.

2. Market Visibility:

o The app store ranking and visibility play a key role in app success. Apps that
are delivered well, optimized for the app stores, and promoted effectively tend to
rank higher in search results, leading to more downloads and better market
positioning.

o App Store Optimization (ASO) ensures better visibility, but the delivery process
(timing, launch, marketing, etc.) also significantly impacts how users discover
and engage with the app.

3. Revenue Generation:

o For freemium apps or apps with in-app purchases, successful delivery


ensures more downloads, which can translate into higher revenues.

o Proper pricing strategies, monetization models, and launch promotions


can help maximize profits and attract paying customers.

4. Security and Data Integrity:

o Security during delivery is essential for maintaining trust. A breach or poor


handling of sensitive user data during the app’s delivery can lead to legal issues,
loss of reputation, and a decrease in user retention.

o Ensuring the app complies with security and privacy regulations ensures that
users can trust your app and feel comfortable providing personal information.

5. Brand Reputation:

o A well-executed delivery process builds trust in your app and your brand. A poorly
delivered app with glitches, performance issues, or security problems can harm
the brand’s reputation and discourage future users from trying your apps.

o Regular updates and attention to user feedback show that the developer cares
about the app’s ongoing improvement.

Describe the process of mobile application for integration


with GPS.
Integrating GPS (Global Positioning System) functionality into a mobile application allows
you to provide location-based features such as navigation, geolocation tracking, and location-
based services. Whether you're building an Android or iOS application, the integration of GPS
involves accessing the device's location data and utilizing it to improve the user experience.
Below is a detailed process for integrating GPS functionality into a mobile application:
1. Set Permissions for Location Access

Before accessing the GPS, you need to ensure that the application has the appropriate
permissions to use the device's location services.

Android

 In Android, you need to request permissions in both the AndroidManifest.xml and


during runtime (for devices running Android 6.0 or later).

o Manifest Permission: You must declare the permission in the


AndroidManifest.xml.

o Runtime Permission: For Android 6.0 (API level 23) and higher, you need to
request permission at runtime.

Example of Android Manifest (in AndroidManifest.xml):

xml

Copy code

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

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

Example of runtime permission request:

java

Copy code

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]


{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);

iOS

 In iOS, you need to add the appropriate keys to your app's Info.plist file. The keys
explain to the user why the app needs access to their location.

Example of Info.plist configuration:

xml

Copy code

<key>NSLocationWhenInUseUsageDescription</key>

<string>Your location is needed for...</string>

<key>NSLocationAlwaysUsageDescription</key>

<string>Your location is needed for...</string>

2. Access Location Services

Once permissions are granted, you can access the GPS functionality and obtain the device's
location using native APIs for both Android and iOS.
Android (Using Google Play Services)

 Google Location Services API is used to obtain the device's location in Android. This
provides more accurate and efficient location updates compared to the standard
Android Location Manager API.

 To integrate Google Play services, add the dependency in your build.gradle file:

gradle

Copy code

implementation 'com.google.android.gms:play-services-location:18.0.0'

Example of accessing location:

java

Copy code

FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);

fusedLocationClient.getLastLocation()

.addOnSuccessListener(this, new OnSuccessListener<Location>() {

@Override

public void onSuccess(Location location) {

if (location != null) {

// Use the location data here

double latitude = location.getLatitude();

double longitude = location.getLongitude();

});

iOS (Using Core Location Framework)

 Core Location is the framework used in iOS for location-based services. To start
receiving location updates, you need to use CLLocationManager.

Example of accessing location:

swift

Copy code

import CoreLocation

let locationManager = CLLocationManager()


// Request permission to access location

locationManager.requestWhenInUseAuthorization()

// Start receiving location updates

locationManager.startUpdatingLocation()

// Handle location updates

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:


[CLLocation]) {

if let location = locations.first {

let latitude = location.coordinate.latitude

let longitude = location.coordinate.longitude

3. Configure Location Accuracy

To get the most accurate location information, configure the desired location accuracy in your
app. Mobile devices provide different accuracy levels, and you can specify whether you want
high accuracy (for navigation apps) or a lower accuracy (for battery savings).

Android

java

Copy code

LocationRequest locationRequest = LocationRequest.create();

locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // or
PRIORITY_BALANCED_POWER_ACCURACY

locationRequest.setInterval(10000); // Update location every 10 seconds

locationRequest.setFastestInterval(5000); // Fastest update interval

iOS

swift

Copy code

locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters // or
kCLLocationAccuracyBest

locationManager.distanceFilter = 10 // Minimum distance between updates in meters

4. Handle Location Updates

Once the location services are set up, you can begin receiving location updates. You can
either get the device’s current location or track location changes continuously, depending on
the requirements of your application.
 Single Location Fetch: Get the device’s location once.

 Continuous Location Updates: Monitor the device's location over time.

Android

java

Copy code

fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback,
Looper.getMainLooper());

iOS

swift

Copy code

locationManager.startUpdatingLocation() // Start continuous updates

5. Handling Location Changes

When tracking location over time, you will need to handle location changes. This could
involve updating the UI or performing background tasks when the user moves. You can use
either foreground updates or background updates depending on the app requirements.

 Foreground Updates: The app is active, and you can update the UI with the new
location.

 Background Updates: The app is in the background, and you must configure your
app to continue receiving location updates in the background.

Android (Background)

You must declare a background service or use JobIntentService to keep receiving location
updates in the background.

java

Copy code

LocationCallback locationCallback = new LocationCallback() {

@Override

public void onLocationResult(LocationResult locationResult) {

for (Location location : locationResult.getLocations()) {

// Use location data here

};

iOS (Background)

You need to request permission to access location services while the app is in the
background.

locationManager.allowsBackgroundLocationUpdates = true
locationManager.startMonitoringSignificantLocationChanges()

6. Handle Errors and Fallback Mechanisms

GPS may fail to provide a location due to several reasons, such as poor signal strength, no
permission, or GPS turned off by the user. It’s important to handle these cases appropriately:

 Location Unavailable: Provide a fallback mechanism, such as using Wi-Fi or cell tower
data for location.

 Permission Denied: Inform the user about why the app needs the location and
request permission again.

 No GPS: Provide alternative ways to detect the location, such as IP-based geolocation
or using a map for manual location input.

Android Example (Permission Denied Handling)

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

Toast.makeText(this, "Permission Denied. Please enable location access.",


Toast.LENGTH_LONG).show();

iOS Example (Permission Denied Handling)

if CLLocationManager.locationServicesEnabled() {

locationManager.delegate = self

locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters

locationManager.requestWhenInUseAuthorization()

locationManager.startUpdatingLocation()

} else {

print("Location services are not enabled.")

7. Displaying the Location on the Map

Once you have access to the GPS coordinates (latitude and longitude), you can display the
user's location on a map.

Android (Using Google Maps)

GoogleMap map = ...;

LatLng userLocation = new LatLng(latitude, longitude);

map.addMarker(new MarkerOptions().position(userLocation).title("You are here"));

map.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));

iOS (Using MapKit)

import MapKit

let mapView = MKMapView()


let userLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let annotation = MKPointAnnotation()

annotation.coordinate = userLocation

annotation.title = "You are here"

mapView.addAnnotation(annotation)

mapView.setRegion(MKCoordinateRegion(center: userLocation, span:


MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)), animated: true)

Conclusion

Integrating GPS into a mobile application provides valuable location-based features. The
process typically involves the following steps:

1. Requesting the necessary permissions for location access.

2. Using platform-specific APIs (Google Location Services for Android and Core Location for
iOS) to access the device's GPS data.

3. Configuring the desired level of accuracy and updating location continuously or once.

4. Handling location changes, errors, and providing fallbacks.

5. Displaying the location on a map for better user interaction.

By following these steps, you can effectively integrate GPS functionality into your mobile app,
enabling it to provide valuable services like real-time navigation, location tracking, and
geofencing.

Explain myths of security and hacking of Android application


with a suitable example.
Myths of Security:
When discussing the security of Android applications, several myths and misconceptions are
often presented. These myths can lead to a false sense of security or an underestimation of
the threats that Android apps face. Let's explore some of the most common myths, along
with examples to help explain them.

1. Myth: "Android is more secure than iOS because it's open-source."

 Reality: Being open-source does not inherently make Android more secure. While
open-source software allows for transparency, it also allows potential attackers to
review and exploit the code. Android’s openness does allow for greater customization
and flexibility, but it can also lead to more potential vulnerabilities. The security of an
app largely depends on how well the developer codes and implements security best
practices.

 Example: A popular open-source Android app might be vulnerable to attacks like Man-
in-the-Middle (MITM) because it uses weak encryption, even though its source code
is visible for review. On the other hand, iOS has a more controlled ecosystem with strict
guidelines, and apps must meet rigorous security standards, reducing the likelihood of
certain types of attacks.
2. Myth: "Android devices are less likely to be hacked due to Google Play's security
mechanisms."

 Reality: Google Play does have mechanisms to detect and remove malicious apps (like
Google Play Protect), but these protections are not foolproof. Malicious apps can still
slip through and find their way onto user devices. Also, users often install apps from
third-party sources (non-Google Play stores), which might not be as secure, exposing
them to greater risk.

 Example: A popular malicious app like Joker was able to bypass Google Play's
protections for a period, infecting hundreds of thousands of users. This app stole money
by subscribing users to premium services without their knowledge.

3. Myth: "Strong passwords are enough to keep an app secure."

 Reality: While strong passwords are important, they are only one aspect of app
security. An attacker can bypass password protections using techniques like brute
force attacks or credential stuffing. Moreover, many Android apps do not implement
additional layers of security, such as two-factor authentication (2FA) or encryption
of sensitive data.

 Example: If a mobile banking app uses only a password and does not encrypt sensitive
data, an attacker who gains access to the device (e.g., through a root exploit) could
retrieve the unencrypted data, even if the password is strong.

4. Myth: "Android is safe as long as it’s updated."

 Reality: While regular updates are crucial for maintaining security, many Android
devices do not receive timely updates, especially older models or devices from less-
known manufacturers. Additionally, even if a device is updated, app vulnerabilities can
still exist due to improper coding or lack of secure configurations.

 Example: In 2019, a significant vulnerability in the Android Bluetooth stack was


discovered (CVE-2019-2215), which affected millions of devices. Although updates were
released, many older Android devices never received this patch, leaving them exposed
to attacks.

5. Myth: "Permissions granted to an app are not a big concern if the app is from a
trusted source."

 Reality: Granting excessive or unnecessary permissions to apps can lead to serious


security risks, even with trusted apps. Malicious or poorly coded apps can misuse
permissions, accessing sensitive data such as location, contacts, microphone, or
camera, even if the app’s primary function does not require them.

 Example: The CamScanner app, which was once popular for scanning documents,
was found to contain malicious code that could access a user's files and send them to
remote servers. Although the app was on Google Play and considered trusted, the
unnecessary permissions it requested made it vulnerable to exploitation.

6. Myth: "Hacking Android apps requires physical access to the device."

 Reality: Many attacks on Android apps do not require physical access to the device.
Remote exploits can be carried out through malicious Wi-Fi networks, phishing, and
app vulnerabilities. Attacks like malware injection or network-based attacks
(e.g., MITM) can be performed remotely.
 Example: Stagefright, a vulnerability in Android's media processing system, allowed
attackers to send malicious multimedia messages (MMS) to phones and exploit a
device remotely without needing physical access. This vulnerability affected millions of
devices globally.

7. Myth: "Encryption is only needed for financial apps or apps with sensitive data."

 Reality: Encryption should be standard for all Android applications that store any form
of personal or private data, not just for those involving financial transactions. Even
seemingly innocuous apps can store sensitive information such as personal
preferences, login credentials, or health-related data.

 Example: An app that tracks fitness or health metrics (such as heart rate or steps)
could be a prime target for hackers if it doesn't properly encrypt user data. This data
might be valuable for identity theft, social engineering, or blackmail.

8. Myth: "Once an app is installed, it cannot be tampered with."

 Reality: It is possible to decompile or reverse-engineer Android apps, especially if they


do not have adequate obfuscation or protection measures. Malicious users can modify
the app's behavior, inject code, or intercept communication, which can lead to data
breaches or other security issues.

 Example: Tools like APKTool or JADX allow attackers to decompile Android APK files
and inspect the source code. If an app doesn’t properly secure sensitive functions (e.g.,
using hardcoded API keys), attackers can exploit these vulnerabilities by modifying the
app's code.

Hacking of Android Application:


Hacking an Android application typically involves identifying and exploiting vulnerabilities in
the app, its code, or its communication with servers. Hackers can take advantage of these
weaknesses to steal sensitive information, modify app behavior, or even take control of the
device. Below, I will explain how the hacking of an Android application works with a step-by-
step process and an example.

How Android Application Hacking Works

1. Reverse Engineering the APK (App Package)

Android applications are distributed as APK (Android Package) files. These files contain the
compiled code, resources, and manifest of the app. Hackers can reverse-engineer an APK to
decompile and analyze the app's code, looking for vulnerabilities or sensitive data.

 Tools Used for Reverse Engineering:

o APKTool: A tool used to decompile the APK, providing access to resources and
source code.

o JADX: A decompiler that converts APK code back into readable Java code.

o Android Studio: A development environment that can be used to inspect and


manipulate Android apps.

Example: A hacker might download an APK file of a popular app, like a social media app, and
use APKTool to decompile it. Upon inspection, they might find sensitive information
hardcoded into the code (e.g., API keys, usernames, passwords, or even access tokens).

2. Identifying Vulnerabilities
Once the APK is decompiled, the hacker looks for flaws in the code or app behavior. Common
vulnerabilities include:

 Hardcoded credentials: Storing passwords, API keys, or sensitive data directly in the
source code.

 Insecure data storage: Storing sensitive information, such as passwords or personal


data, in unencrypted files or databases on the device.

 Lack of proper authentication: Flaws in user login systems or improper session


management.

 Weak or missing encryption: Sending sensitive data over unsecured communication


channels (HTTP instead of HTTPS), allowing attackers to intercept data.

 Excessive permissions: Apps requesting unnecessary permissions (e.g., access to


the camera or microphone without justification).

Example: The hacker might find that the app stores sensitive API keys in plain text within the
app’s resources. This could allow them to directly access the app's backend or servers by
simply extracting the keys.

3. Exploiting the Vulnerability

After identifying a vulnerability, the hacker exploits it to gain unauthorized access or


manipulate the app. The exploitation method depends on the specific vulnerability found.

 Hardcoded API Keys: If the app has hardcoded API keys, a hacker can use those keys
to access the app’s backend services, making API calls that should otherwise be
restricted. This might allow them to retrieve user data or manipulate the app's
functionality.

 Insecure Data Storage: If the app stores user data (such as passwords) in plaintext
on the device, the hacker can access the device’s storage (either through a physical
connection or a root exploit) and steal this data.

 Lack of Proper Encryption: If the app does not encrypt sensitive data before sending
it over the network, the hacker can intercept the data through a Man-in-the-Middle
(MITM) attack on an unsecured Wi-Fi network and gain access to sensitive user
information.

Example: If the app uses weak encryption or no encryption at all for its network traffic, a
hacker might perform a Man-in-the-Middle (MITM) attack on a public Wi-Fi network. Using
tools like Wireshark or Burp Suite, the hacker intercepts data between the app and the
server, capturing usernames, passwords, and session tokens in plain text.

4. Modifying the App

Sometimes, hackers don’t just steal data but modify the app’s behavior. This could involve
changing how the app interacts with the server or the user.

 Removing Restrictions: A hacker could modify the app’s code to remove certain
restrictions, such as bypassing in-app purchases, unlocking premium features without
payment, or bypassing authentication checks.

 Injecting Malicious Code: Hackers may inject malicious code into the app to perform
unwanted actions, such as logging keystrokes, sending sensitive data to an external
server, or enabling backdoor access.
Example: The hacker may modify the APK to remove the authentication logic entirely,
allowing them to log in to any user account without the need for a password.

5. Repackaging and Distributing the Malicious App

After modifying the app, the hacker repackages it into a new APK file and may attempt to
distribute it to unsuspecting users. This is often done by uploading the malicious APK to third-
party app stores or distributing it through phishing tactics.

 Example: The hacker may upload the modified version of the app to a third-party app
store or send it via email to potential victims, claiming that it’s a "premium" version of
the original app. When users install the modified app, they unknowingly expose their
data or compromise their devices.

Real-World Example: Hacking of the "Joker" Malware

In 2020, Joker, a sophisticated Android malware, was discovered affecting over 1,700 apps
on the Google Play Store. Here's how it worked:

1. Malicious Apps: Joker malware was disguised as legitimate apps, like photo editors,
screen lock apps, and VPNs. These apps requested unnecessary permissions that
seemed harmless to users, such as access to contacts or SMS messages.

2. Exploiting Permissions: Once the app was installed, Joker malware would silently
sign up users for premium SMS services, without their knowledge or consent. It used
SMS and contacts data to carry out fraudulent actions.

3. Repackaging: The malware authors regularly updated the Joker malware, re-uploading
it to the Google Play Store to bypass detection. When users downloaded the infected
app, the malware would run in the background, sending premium-rate SMS messages
that charged the user.

o Impact: Joker infected millions of users worldwide and was able to steal money
by signing users up for fraudulent subscriptions. Despite efforts by Google to
remove the malware, it continued to reappear in new apps.

How to Protect Against Android App Hacking

To protect against Android app hacking, both developers and users need to take precautions:

 For Developers:

o Avoid hardcoding sensitive data like API keys or passwords in the code.

o Implement proper encryption for sensitive data both in storage and during
transmission.

o Use Secure HTTP (HTTPS) for communication to prevent MITM attacks.

o Regularly audit and update the app to fix vulnerabilities.

o Implement strong authentication and authorization mechanisms, such as two-


factor authentication (2FA).

 For Users:

o Only download apps from trusted sources like the Google Play Store.

o Avoid installing apps that ask for unnecessary permissions.

o Regularly update apps to ensure they have the latest security patches.
o Use mobile security software that can detect and prevent malicious apps.

o Be cautious when connecting to public Wi-Fi networks, especially when using


sensitive apps like banking or payment apps.

How performance, scalability and security address in mobile


applications?
Performance, scalability, and security are three crucial factors that need to be addressed
when developing mobile applications. Each of these aspects plays a critical role in ensuring
that the application functions efficiently, can handle increasing user demand, and protects
user data and privacy. Below is an explanation of how each of these factors can be addressed
in mobile applications:

1. Performance in Mobile Applications

Performance refers to how well an app functions in terms of speed, responsiveness, and
resource consumption (e.g., CPU, memory, battery). Addressing performance is vital to
ensure that the app provides a smooth user experience, minimizes lag, and doesn't drain
resources unnecessarily.

How to Address Performance:

 Efficient Code Optimization:

o Optimize algorithms: Make sure the code is optimized for performance, using
efficient algorithms and data structures to avoid bottlenecks in processing.

o Avoid blocking UI threads: Heavy tasks like network calls, database


operations, or image processing should be moved off the main UI thread to avoid
making the app unresponsive.

 Memory Management:

o Properly manage memory allocation to avoid memory leaks and excessive use
of memory, which could cause crashes or slow performance, especially on lower-
end devices.

o Use caching mechanisms (e.g., image caching) to avoid unnecessary reloading


of data or assets.

 Efficient Network Communication:

o Optimize API calls: Reduce the number of network requests and ensure they
are batched or minimized to optimize the app's network performance.

o Use lightweight data formats (e.g., JSON instead of XML) to reduce payload
size.

o Implement compression for images and files being transmitted over the
network to reduce the amount of data exchanged.

 Background Processing:

o Offload non-urgent tasks (e.g., data synchronization, backups) to run in the


background or during idle time so that the main app experience remains fast.

 Device Optimization:
o Consider the variety of devices (screen sizes, CPU capabilities, RAM) when
developing the app and optimize the app accordingly.

o Implement adaptive UI techniques that adjust the app’s visuals and


performance based on the capabilities of the device.

 Battery Usage:

o Avoid excessive background operations that consume battery power.

o Optimize app components to prevent unnecessary usage of location services,


GPS, or sensors, as these can drain the battery.

2. Scalability in Mobile Applications

Scalability refers to the ability of an app to handle increasing numbers of users, data, and
requests without sacrificing performance. A scalable app can handle a growing user base or
workload seamlessly by expanding its resources as needed.

How to Address Scalability:

 Backend Scalability:

o Ensure that the server-side infrastructure (e.g., APIs, databases) is scalable to


handle increasing traffic. This can be achieved by using cloud services (e.g.,
AWS, Google Cloud, Microsoft Azure) that offer scalable solutions such as auto-
scaling, load balancing, and flexible resource allocation.

o Use microservices architecture to split the backend into smaller, independent


services that can scale independently based on demand.

o Implement load balancing to distribute incoming traffic across multiple servers


and prevent any single server from becoming overloaded.

 Database Scalability:

o Use distributed databases (e.g., NoSQL databases like MongoDB) that can
scale horizontally by adding more servers or clusters as the app's data grows.

o Implement database indexing and optimize queries to ensure that data


retrieval remains fast even as the volume of data increases.

o Use caching mechanisms like Redis or Memcached to store frequently accessed


data temporarily, reducing database load.

 Handling Increased Traffic:

o Use Content Delivery Networks (CDNs) to deliver static content (like images
and videos) quickly to users by caching data on servers located closer to the
user, thus reducing latency and server load.

o Optimize API rate limiting and implement backoff strategies to handle high
traffic and ensure fair access to resources.

 Asynchronous Processing:

o Offload heavy tasks (such as video processing or large data uploads) to


background workers or queues to avoid overwhelming the app during peak usage
times.

 Optimizing App Downloads and Updates:


o Use techniques like incremental updates or differential updates so that
users don’t need to download the entire app every time there’s a new version,
improving the app's scalability in terms of frequent updates.

3. Security in Mobile Applications

Security is one of the most important aspects of any mobile application, as it directly impacts
the privacy and protection of users' data. Poor security practices can lead to data breaches,
unauthorized access, or malicious attacks.

How to Address Security:

 Data Encryption:

o Encrypt sensitive data both in transit and at rest. Use HTTPS (SSL/TLS) for all
communication between the app and the server to prevent data interception.

o Use strong encryption algorithms like AES (Advanced Encryption Standard)


to store sensitive data like passwords, tokens, or financial details on the device.

 Authentication and Authorization:

o Implement strong authentication mechanisms such as multi-factor


authentication (MFA) to prevent unauthorized access.

o Use OAuth for secure, token-based authentication, especially for social logins or
integrations with third-party services.

o Ensure proper role-based access control (RBAC) to restrict access to different


parts of the app based on user roles.

 Secure Storage:

o Use secure storage mechanisms provided by the mobile OS (e.g., Keychain on


iOS or Keystore on Android) to store sensitive data like tokens, keys, and
passwords.

o Avoid storing sensitive information in plain text or insecure locations like


SharedPreferences or local storage without encryption.

 Code Obfuscation:

o Obfuscate the app's code to make it difficult for attackers to reverse-engineer


or tamper with the app. Tools like ProGuard (for Android) or LLVM Obfuscator
(for iOS) can be used for this purpose.

 Secure APIs:

o Ensure that backend APIs are secure by implementing proper input validation,
rate limiting, and authentication to prevent misuse.

o Avoid exposing sensitive endpoints or data to unauthorized users.

 Regular Security Audits:

o Conduct penetration testing and security audits on both the mobile app and
the backend services to identify and address vulnerabilities.

o Keep the app updated with the latest security patches to prevent known
vulnerabilities from being exploited.
 User Privacy and Permissions:

o Request only the necessary permissions needed by the app and avoid requesting
sensitive data unless absolutely required. Clearly explain why permissions are
required.

o Implement proper privacy policies and inform users of how their data is being
used and stored.

 Secure Communication:

o Use certificate pinning to prevent Man-in-the-Middle (MITM) attacks where


attackers intercept the app’s communication with the server.

What are testing methodologies and deployment process in


Mobile Software Engineering?
Mobile Application Testing
Approaches to Test the mobile application

We will follow two different approaches for the testing of mobile applications. Here we will
follow two approaches to test the mobile application, and those are manual testing and
automated testing.

Manual Testing

Manual testing is a human process. The primary focus of manual testing is on the experience
of the user. The Analysis and evaluation of the application's functionality can be done through
the medium of the user in an explorative process. Manual Testing ensures that the application
work on the standard of user-friendliness. Manual testing is generally the time-consuming
process because the process is to find out the bugs will take time. Therefore, according to the
thumb rule, 20% of applications at the time of releases should be tested with the alpha and
beta testing. In the rest part of the application, automated testing should be performed.

Automation Testing

Automated testing is the second approach to test the mobile application. In this process, an
array of test cases is set up. Automated Testing covers 80% of the testing process. The
percentage is not set up, but this is the general guideline followed by the software industry.
We will perform automation testing in the below scenarios-

o When manual test cases are slow, then we will use Automate test cases.

o The test cases which can be easily automated then we will use Automation Testing.

o Automation testing is used for test cases, which is written for the frequently used
functionality.

o Automation testing is used for the automated test cases, which we cannot perform
manually.

o Automation testing is used to automate the test cases, which gives us predictable
results.

Types of Mobile Testing

Mobile testing has two types that we can perform on mobile devices.
1. Hardware Testing: Hardware testing is done on the internal processors, resolution,
internal hardware, size of the screen, radio, space, camera, Bluetooth or WIFI, etc. This
testing is known as simple "mobile testing."
2. Software Testing or the Application Testing: The functionality of those
applications should be tested, which works on mobile devices. We call this testing as
the "Mobile Application Testing".

Types of the Mobile Application

There are three types of applications. These are as shown below:

1. Native Apps: Native application is used on different platforms like mobile and tablets.

2. Mobile Web Apps: Mobile apps are the server-side apps. We can access the mobile
web apps on mobile by using the different browsers like Chrome, Firefox, after
connecting the mobile to the mobile network or wireless network like WIFI.

3. Hybrid Apps: Hybrid applications are a combination of both types of applications like
native and web applications. Hybrid apps run offline on the devices. Hybrid apps are
written by using the web technologies like HTML5 and CSS.

Types of the Mobile Application Testing

The following are the types of testing that can be performed on mobile:

o Usability Testing: Usability testing ensures the user that the mobile app is easy to
use and gives a satisfactory experience to the user.

o Compatibility Testing: Compatibility testing is done on different mobile devices, on


different browsers, screen sizes, and the versions of the Operating system according to
the requirement.

o Interface Testing: Interface testing is done on the menu options, bookmarks, buttons,
history, settings, and the navigation flow of the application.

o Service Testing: Service Testing is done to test the services of the application online
or offline.

o Low-Level resource Testing: This type of testing is done on the memory usage,
auto-detection of the temporary file, growing issue of the local database. The testing of
all the resources is known as Low-Level Resource Testing.

o Performance Testing: Performance testing is done on the application after changing


the connection from 2G,3G to WiFi. We will test the performance of the application by
sharing the documents, battery consumption, etc.

o Operational Testing: Operational Testing will perform to test the backup and recovery
plan when the battery goes down or the loss of the data when we upgrade the
application from the store.

o Installation Testing: Installation Testing will be performed to validate the application


by installing and uninstalling the app on the device.

o Security Testing: Security testing is done to test the application to validate the
information to protect it.

Mobile Application Testing Strategies

While deciding the testing strategy, we should have to ensure that the quality and the
performance guidelines met. Points are as shown below:

1. Selection of the device: During the selection of the device in the first analyses the
market and choose those devices which are widely used these days. The selection of
the device depends on the client.

2. Emulators: The use of the emulator is useful in the initial stage of the development;
the emulator allows us to test the application quickly. An emulator is a system used to
run the software from one environment to another environment without any change in
the software system. The emulator works on the real system.

Type of the Mobile Emulator

 Device Emulator: The manufacturer of the device provides this emulator.

 Browser Emulator: This emulator simulates the environment of the mobile browser.

 Operating Systems Emulator: The operating system Apple provides us the emulator
for the iPhones, Google provides the emulator for the Android Phone, and the Microsoft
provides the emulator for Windows Phone.

Understanding Mobile App Deployment


Mobile app deployment is not a singular event, but rather a series of steps that take place
after the development of the app. It involves preparing the app for distribution, which
can include packaging the app, setting up servers, and configuring settings. The goal is
to ensure that the app is ready for use on the intended platform, whether that's iOS, Android,
or another mobile operating system.

Deployment can also involve the process of updating an existing app. This can
include releasing new features, fixing bugs, or improving performance. In this case,
deployment involves not only making the new version available, but also ensuring that
existing users can smoothly transition to the updated app.

Stages of Mobile App Deployment

The first stage of mobile app deployment is preparation. This involves finalizing the app's
code, testing it thoroughly, and packaging it for distribution. The app may also need to be
configured for the intended platform, which can involve setting up servers, databases, and
other backend systems.

The next stage is distribution. This involves making the app available for download, either
through a public app store like Google Play or the Apple App Store, or through a private
distribution method. The app may also need to be registered with the appropriate app store,
which can involve submitting the app for review and approval.

Methods of Mobile App Deployment

There are several methods of mobile app deployment, each with its own advantages and
disadvantages. The most common method is through a public app store. This is a
straightforward and widely accepted method of distribution, but it can also be time-
consuming and costly, as app stores often charge fees for listing and selling apps.

Another method is private distribution, which involves making the app available for download
directly from the developer's website or through a private app store. This method offers more
control over the distribution process, but it can also be more complex to set up and manage.

Mobile App Deployment Platforms

There are several platforms available for mobile app deployment, each with its own features
and capabilities. These platforms provide tools and services to help developers prepare,
distribute, and manage their apps.

Some of the most popular mobile app deployment platforms include Google Play for Android
apps, the Apple App Store for iOS apps, and Microsoft Store for Windows apps. These
platforms offer a wide range of tools and services, including app testing, distribution,
analytics, and monetization options.

 Google Play

Google Play is the official app store for Android devices. It offers a comprehensive set of
tools for app deployment, including a developer console for managing apps, a
distribution service for making apps available to users, and a review process for
ensuring app quality.

Google Play also offers a variety of monetization options, including in-app purchases,
subscriptions, and ads. It also provides analytics tools for tracking app performance and
user engagement.

 Apple App Store

The Apple App Store is the official app store for iOS devices. Like Google Play, it offers a
comprehensive set of tools for app deployment, including a developer portal for
managing apps, a distribution service for making apps available to users, and a review
process for ensuring app quality.

The Apple App Store also offers a variety of monetization options, including in-app
purchases, subscriptions, and ads. It also provides analytics tools for tracking app
performance and user engagement.

 Challenges in Mobile App Deployment

Mobile app deployment can be a complex process, with several challenges to


overcome. One of the main challenges is ensuring app compatibility with a wide range
of devices and operating systems. This can be particularly difficult for Android apps, as
there are many different versions of Android in use, each with its own features and
capabilities.

Another challenge is managing app updates. This involves not only developing and
testing new features, but also ensuring that users can smoothly transition to the new
version of the app. This can be particularly challenging for apps with a large user base,
as any issues can affect a large number of users.

 Ensuring App Compatibility

Ensuring app compatibility involves testing the app on a variety of devices and
operating systems. This can be a time-consuming process, as there are many different
combinations to consider. However, it's an essential step in the deployment process, as
it ensures that the app will work correctly for all users.

There are tools available to help with this process, including device emulators and
testing services. These tools can simulate a variety of devices and operating systems,
allowing developers to test their apps in a controlled environment.

 Managing App Updates

Managing app updates involves not only developing and testing new features, but also
ensuring that users can smoothly transition to the new version of the app. This can
involve notifying users of the update, providing instructions for installing it, and
handling any issues that arise during the update process.

There are tools available to help with this process, including update management
services and in-app messaging tools. These tools can automate the update process,
notify users of updates, and provide support for any issues that arise.

What are the various hurdles that are faced during the mobile
app development
There is a large range of different mobile application challenges that an app developer will
face throughout the development lifecycle. This ranges from choosing the best approach to
developing the app, to creating an app that is good enough to stand out in the competitive
market.

So what are the main challenges of mobile app development? Let’s look at the key mobile
problem list.

Choosing the Best Development Approach

When starting app development projects, the first matter to consider is choosing the best app
development technology approach.

The real challenges in mobile app development are making sure you decide on the right
decisions in the early stages so that you create the best possible app for your customers. So
let's take a look at some of the development approaches you can take to overcome your
mobile app challenges.

Native app development


The first approach is known as native app development. This type is where you develop an
app using right tools specific to a certain mobile operating system (OS). The android app
development process involves challenges and complexities such as integrating third-party
APIs, ensuring compatibility across different Android versions and devices, and maintaining
user engagement while implementing futuristic features under tight deadlines. The native
approach comes with a range of advantages.

One of these is the fact that native apps often perform much better than other types of
app development and are often extremely reliable and safe, helping meet any mobile
development trend.

However, If you use the native approach, and decide to put your app in an Android mobile
app market, you will have to develop it all over again if you would like your app to be shown
in another marketplace.

Cross-platform app development

The second approach is called cross-platform development. Just like the name suggests,
this development type is perfect for those who are looking to put their apps on a range of
different app marketplaces. Developing Android apps comes with its own set of challenges,
including security issues, app visibility, device fragmentation, and integration of third-party
APIs.

Although it sounds good on paper, there are numerous issues with cross-platform
development. Firstly, there is a huge dependency on the type of framework that is used to
develop the app. As you will have to do all the work on these development platforms that
have a distinct lack of features, you need to ensure it will have everything you will ever need
for the app you are developing.

There are simply many more features that can be worked on and at much faster speed in
native development than in cross-platform. Because of this, teams working on the app
development will often need to work on cross-platform, as well as iOS and Android native
development, making the whole process much more costly and time consuming.

Hybrid app development

You can also go for hybrid mobile development. This way, apps are developed using standard
forms of coding, like Javascript and CSS that have higher performance than cross-platform
apps.

Hybrid applications consist where elements from native apps and web applications are
combined. They are web apps that have been placed inside a native app shell. This means
that mobile app developers require only one source of code for the app and it will still be
usable on multiple platforms. However, the unfortunate drawback is that a lot of native UX is
sacrificed as a result, along with all the great features in native development that hybrid apps
just can't replicate.

Choosing the right development approach is one of the crucial decisions in creating mobile
products. Be mindful in researching these different types and decide which one is better for
you, based on your needs and goals.

Ensuring great User Experience

When developing an app, designing a user interface that provides a great user experience
without faults is one of the most important processes and one of the crucial application
development challenges faced by UX designers and programmers. This can often be difficult,
as it needs to meet the best usability practices or it simply won’t be used as much as
competing apps having better user experience.

Great user experience is one of the biggest mobile app design challenges when making
an app. Ease of use, and loading times are just some of the factors that are imperative in
users’ eyes for them to carry on using them otherwise they may go for another mobile
product.

Device compatibility and screen size

One of the key factors in mobile UX design is ensuring the app works well on a range of
different mobile devices. If it is not compatible with certain popular devices and the screen
size is not catered to this could make the user experience much worse.

This is often one of the toughest challenges faced while testing mobile applications as there
are many different devices and screen sizes, so ensuring the app is compatible with all of
them can be difficult.

Although it is important to develop apps with accessibility as a main focus, there are no
special requirements that need to be met. WCAG, which is the most reliable Web Content
Accessibility Guidelines, suggest that both mobile and desktop apps should all follow all their
requirements in the same way.

Developers will need to constantly monitor the WCAG guidelines to ensure that they are
meeting their requirements at every stage of the process.

Different mobile operating systems

There are many iOS, Android, and Windows app development challenges that developers
face when trying to provide the top-notch user experience. Specifically, the Android OS
presents unique challenges such as fragmentation, security vulnerabilities, and the need for
compatibility with various device configurations and versions. Developers have to ensure that
the app is working well on every operating system to ensure a high-quality user experience.

Finance management and funding

After you have decided on developing a mobile application, you next need to think about the
costs, and how you will be able to afford it. Having a great idea for an app means nothing
when you don't have the funds to make it a reality.

The costs will vary depending on how complicated the app is. For example, apps often
range from $3,000 to $150,000. You need to consider all of this before developing the app.

This is often one of the biggest problems in software development, as it can be difficult to
figure out the costs involved, as well as getting the funding. You can get funding through a
range of different ways. These ways include angel investors, loans, or joint ventures.

Standing out in the mobile apps market

Mobile apps are extremely popular, and as such, the mobile market is extremely competitive.
One of the main challenges is app visibility in a crowded market. So how do you develop an
app that stands out from the crowd?

One of the biggest mobile app development challenges is promoting the app. There are
several ways to do this.

One of them is making it discoverable. If people can easily find it on an app marketplace,
they are much more likely to download it. If you’ve created a high-performing app that has a
great user experience but no one can find it, you won’t reach your business goals.

Make sure to look for a mobile app feature list example to find the best ways to promote the
app.

What is framework? Write various hurdles in Mobile App


Development

You might also like