0% found this document useful (0 votes)
53 views88 pages

Mobile User Interface Development - ANSWERKEY

Uploaded by

sanjays66869
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)
53 views88 pages

Mobile User Interface Development - ANSWERKEY

Uploaded by

sanjays66869
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/ 88

19CS414-Mobile Application Development

Answer Key
(PART B – 13 Marks )

UNIT - I
Q. No Questions
Android service is a component that is used to perform operations on the background such as playing music, handle network trans-
actions, interacting content providers etc. It doesn't has any UI (user interface).
The service runs in the background indefinitely even if application is destroyed.
Moreover, service can be bounded by a component to perform interactivity and inter process communication (IPC).
The android.app.Service is subclass of ContextWrapper class.

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 themselves to service to carry out inter-process communication(IPC).
1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground Services. Users can interact with the service by
1 the notifications provided about the ongoing task. Such as in downloading a file, the user can keep track of the progress in down -
loading and can also pause and resume the process.
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.

2
onCreate()
The onCreate() callback is compulsory in all Android applications. It is the first method called when we launch an activity from the
home screen or intent. In other words, it is a default callback that is automatically created when you create a new activity.
It’s the only method that developers need to implement activity logic that should only happen once, such as initializing a ViewModel.
Android Studio automatically creates a class named the MainActivity.java file. This class contains an onCreate() callback. It is called
when a user first opens the application.
When an application is installed on a device, it is in a doesn't exist state. This means the activity is dead.
Once a user opens the application, the lifecycle begins. The
activity is brought to the foreground. In this case, onCreate() is immediately called to fire up the application. It may contain
components such as the activity UI.
onStart()
When an application is started, the system will invoke an onStart() method. This callback is invoked to make the activity visible to
the user.
onStart() can be called several times during an application’s lifecycle. For example, this method can be called when a user opens
another activity and then navigates back to the previous activity.
During the activity’s lifecycle, the onStop() function is called. This means that some resources are released. The onStart() method can
be invoked to initialize such resources.
onResume()
Once onStart() is called, onResume() is immediately invoked. Every component associated with this activity is brought to the
foreground state. The activity is now considered interactive.
At this point, the activity remains in the foreground state unless something happens to the application. This may include overly
(multi-window mode application) interaction from other applications such as a phone call or when a user navigates to another
activity.
onPause()
onPause() is called when the user switches to another activity or a multi-window mode application. At this point, the activity has lost
focus and is running in the background.
This callback will pause the activity and release some resources that this activity was consuming. All un-required operations are
paused.
When onPause() is called, you might release some resources from memory. However, make sure that you initialize them again during
the onResume() callback.
onPause() is a brief callback that allows transition to other activities. So, intensive computations should not be executed during this
stage. This may delay the application from transitioning to other activities thus leading to a poor user experience.
onStop()
At this point, most of the activity processes have been stopped. However, the activity is still running in the background.
This life-cycle usually occurs after the onPause() method is executed due to the user switching to other activities or pressing the
home button.
In such situations, it is used to release heavy resources and stop intensive operations that are not required while the activity is
invisible.
Since onPause() is brief, onStop() can be used to save data to other channels such as databases.
onRestart()
Since the activity’s states still exist, the onRestart() method can be called when the user restarts the activity. This means the activity
will go back to the main screen and the user can resume interacting with its components.
As discussed, the onCreate() function is only called once in an activity’s life-cycle. So, when the onRestart() method is executed, the
activity will resume by executing the onStart() then onResume().
onDestroy()
This is the final callback that the activity will receive when it is stopped.
The method is called when there is a change in the configuration states such as screen rotation or language settings. The Android
system will destroy the activity, then recreate it with the set configurations.
3 Intents, in general, are used for navigating among various activities within the same application, but note, is not limited to one single application,
i.e., they can be utilized from moving from one application to another as well.
Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc.
Types of Android Intents
There are two types of intents in android:
Implicit and
Explicit
Implicit Intent doesn’t specify the component. In such a case, intent provides information on available components provided by the system that is
to be invoked. For example, you may write the following code to view the webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(“http://www.javatpoint.com”));
startActivity(intent);

Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit
intent.
We can also pass the information from one activity to another using
explicit intent.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
There are two activities (FirstActivity, SecondActivity). When you click on ‘GO TO OTHER ACTIVITY’ button in the first activity, then you
move to second activity. When you click on ‘GO TO HOME ACTIVITY’ button in the second activity, then you move to the first activity. This
is getting done through Explicit Intent.
4) Develop an android application to create a button called “Font.” By clicking on this button it should change the Font size for the text
“ Hello World” stored in the text box
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="HELLO WORLD"
android:textSize="20sp"
android:textStyle="bold"
tools:layout_editor_absoluteX="56dp"
tools:layout_editor_absoluteY="391dp" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20sp"
android:gravity="center"
android:text="Change Font Size"
tools:layout_editor_absoluteX="58dp"
tools:layout_editor_absoluteY="601dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

MAIN.JAVA
package com.example.fontsize;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.graphics.Color;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


float font = 24;
int i = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView t1 = (TextView)findViewById(R.id.textView1);
Button b1 = (Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
t1.setTextSize(font);
font = font+4;
if(font==40)
font = 20;
}
});

}
}

5 Android Telephony framework provides us the functionalities of the mobile. It gives us information about functionalities like calls,
SMS, MMS, network, data services, IMEI number, and so on.

For better understanding, you can consider Dialer, Browser, Sim App toolkit, Broadcast receivers, and so on.

Android Telephony architecture works in 4 layers that are :

1. Communication Processor
2. Radio Interface Layer (RIL)
3. Framework Services
4. Applications

Let us try to understand them briefly one by one :

1. Communication Processor

It is an input/output processor to distribute and collect data from a number of remote terminals. It is a specialized processor designed
to communicate with the data communication network.

2. Radio Interface Layer

It is a bridge between the hardware and Android phone framework services. Rather we say, it is a protocol stack for Telephone. It has
two main components that are:

● RIL Daemon– It starts when the android system starts. It reads the system properties to find a library that is to be used
for Vendor RIL.
● Vendor RIL– It is also known as RIL Driver. It can be understood as a library that is specific to each modem.

3. Framework Services

The telephony Framework starts and initializes along with the system. All the queries by Application API are directed to RIL using
these services.
4. Application

These are the Application UI related to telephony such as Dialer, SMS, MMS, Call tracker, etc. These applications start with the
android system boot up. These are tied with framework services of telephony.

Android Telephony Framework consists of two types of packages that are:

1. Internal Telephony Packages: This is generally the used for default telephony app.apk.

2. Open Technology Packages: This is for third-party apps.


6 1. Planning stage (project manager, marketer, and business analyst are involved) – carrying out the business analysis and
crafting mobile strategy.
2. Technical documentation (covered by the technical writer) – describing all tech requirements and details.
3. Prototyping (usually made by a UX/UI designer) – creating the sketch, wireframes, prototype and final app skins upon ap-
proval.
4. Development (performed by the developers) – front-end and back-end segments of coding.
5. Quality Assurance (usually performed continuously after each agile sprint is completed; followed by bug fixing) – testing
tech requirements, device compatibility, interface, security aspects, etc.
6. Publishing & Maintenance (covered by DevOps) – publishing to the app store, updates releases, infrastructure, and entire
app maintenance.
Planning stage

When creating a mobile app, it is crucial to take time to go through the necessary research and planning steps.
Business analysis:

 Idea evaluation – a preliminary stage, when experts investigate the idea, correct it, give their advice and create a rough logics
for it.
 Competition analysis – study of activities of other players in the market.
 SWOT-analysis – evaluation of strengths and weaknesses of the product, insights into opportunities and other aspects.
 ROI calculation – assessment of the future app market performance help realize the real value and adjust budget accordingly.
 Requirements scope – summing up requirements for the future product at all levels.

Mobile strategy:

 Market research – this study shows the overall situation on the market to help adjust the concept of the product to current de-
mand.
 Defining user personas – understanding who is your target audience is crucial in crafting advertising approach.
 Technologies & tools assessment – study of specific tools required for the industry and select a set of technologies to meet the
objectives of the project.
 Complex promotion strategy – a step-by-step action plan for acquisition and retaining users.

Technical documentation:

Also known as a technical specification or a software documentation, this paper is a complex manual of your product, outlining re-
quirements, business logic and leading your specialists through all stages of the project:

 Makes your software universally understandable.


 Provides flexibility for future changes.
 Adds value to your app by providing a clear manual.
 Helps to keep control of your own product.
 Allows reusing existing parts of the developed application.

Prototyping:

Prototyping is a process of defining a concept in visual terms and evaluating how the app might develop to correct a misconception.

 Creating a sketch – the draft version of your app on paper that sets up the main logic, number of screens and the way they in-
teract with each other.
 Creating wireframes – provides the visualization of the draft structure.
 Creating a clickable prototype – helps to find out and analyze all possible use cases, discover logical breaks and technical in-
consistencies in the original idea.
 Designing app skins – collecting all wireframes and put them together to get the final design.

Code Development:

This segment usually consists of two main parts:

 Front-end development – client-side development, creating a presentation layer of the software for a direct user interaction
with it.
 Back-end development – a server/database part of development, connecting a front-end part of the mobile app with the data
access layer.
Quality Assurance:

In the agile development, it’s usually a continuous process following every sprint of development:

 Compatibility testing – running the app on different devices and screen sizes.
 Interface testing – checking the navigation, menu and buttons performance.
 Device compatibility testing – checking how the app looks and performs on various screen sizes.
 Low-level resources testing – examination of the app in conditions of low battery, slow internet connection, etc.
 Security testing – provides quality assurance of users data safety.
 Beta testing – giving users access to the app to get feedback.

Publishing & Maintenance:

 Publishing of the app and following updated versions to a chosen app store.
 Infrastructure support – either you have admin panel to post on or cloud service attached, you’ll need to make sure it func-
tions fully.

App store optimization – helping your app move onto the tops of search lists and this way gain more users..
7
A mobile emulator plays a crucial role in app development by simulating the behavior of a mobile device or operating
system on a computer. It provides a virtual environment that allows developers to design, test, and debug their mobile
applications without the need for physical devices. Here are the key roles and benefits of using a mobile emulator in app
development:

1. **Cross-Platform Development:** Emulators enable developers to write and test code for multiple mobile platforms
(e.g., Android, iOS) on a single development machine. This cross-platform capability streamlines the development pro-
cess and helps ensure app compatibility across different devices.

2. **Cost Savings:** Emulators are cost-effective because they eliminate the need to purchase and maintain a wide
range of physical devices for testing. This is particularly beneficial for independent developers and small teams with lim-
ited resources.
3. **Rapid Testing and Debugging:** Developers can quickly deploy and test their applications on emulators, allowing for
faster iterations and debugging. This expedites the development cycle and accelerates time-to-market for apps.

4. **Simulate Device Features:** Emulators replicate the hardware and software features of real devices, including
screen size, resolution, touch gestures, sensors (e.g., GPS, accelerometer), and networking capabilities. This enables
comprehensive testing and ensures that apps work as expected on various device configurations.

5. **Operating System Versions:** Developers can test their apps on different versions of the operating system, helping
to identify and address compatibility issues and ensuring backward compatibility with older devices.

6. **Integration with Development Tools:** Emulators seamlessly integrate with popular development environments (e.g.,
Android Studio, Xcode), allowing developers to write, debug, and profile code directly within the development environ-
ment.

7. **Automation Testing:** Emulators can be integrated with testing frameworks, enabling automated testing of app func-
tionality and performance. This is essential for continuous integration and regression testing.

8. **User Interface Testing:** Emulators facilitate user interface (UI) testing, allowing developers to assess the app's re-
sponsiveness, layout, and appearance on various screen sizes and orientations.
9. **Performance Profiling:** Developers can use emulators to profile the performance of their apps, identifying bottle-
necks, memory leaks, and resource usage issues. This helps optimize app performance.

10. **Accessibility Testing:** Emulators support accessibility testing, allowing developers to assess the app's compliance
with accessibility standards and make necessary improvements for users with disabilities.

11. **Localization and Internationalization Testing:** Emulators can simulate different languages, regions, and time
zones, making it easier to test the app's localization and internationalization features.

12. **Security Testing:** Developers can use emulators to assess the security of their apps, including data encryption,
authentication, and authorization mechanisms.

While mobile emulators are incredibly valuable tools in app development, it's important to note that they may not fully replicate the
behavior of physical devices in every aspect. Therefore, testing on real devices is still recommended, especially for ensuring a
seamless user experience and addressing device-specific issues. Emulators should be used in conjunction with physical testing to
achieve comprehensive app quality assurance.

Get started with the emulator


The Android Emulator lets you test your app on many different devices virtually. The emulator comes with
Android Studio, so you don't need to install it separately. To use the emulator, follow these basic steps,
which are described in more detail in the sections that follow:
1. Verify that you have the system requirements.
2. Create an Android Virtual Device (AVD).
3. Run your app on the emulator.
4. Navigate the emulator.

Navigate the emulator screen

Use your computer mouse pointer to mimic your finger on the touchscreen, select menu items and input
fields, and click buttons and controls. Use your computer keyboard to type characters and enter emulator
shortcuts.

Table 1. Gestures for navigating the emulator

Feature Description

Swipe the Point to the screen, press and hold the primary mouse button, swipe across the screen, and then release.
screen

Drag an item Point to an item on the screen, press and hold the primary mouse button, move the item, and then release.

Tap Point to the screen, press the primary mouse button, and then release.

Double tap Point to the screen, double-click the primary mouse button quickly, and then release.

Touch & Point to an item on the screen, press the primary mouse button, hold, and then release.
hold

Type You can type in the emulator by using your computer keyboard or using a keyboard that pops up on the emulator screen.

Pinch and Pressing Control (Command on macOS) brings up a pinch gesture multi-touch interface. The mouse acts as the first finger, and across
spread the anchor point is the second finger. Drag the cursor to move the first point.

Clicking the left mouse button mimics touching down both points and releasing mimics picking both up.
Vertical Open a vertical menu on the screen and use the scroll wheel (mouse wheel) to scroll through the menu items. Click a menu item to
swipe select it.

8 The concept of a mobile software stack refers to the layered architecture that forms the foundation for developing and running mobile
applications on a mobile device. It's a hierarchical structure of software components, libraries, and frameworks that enable the func-
tioning of mobile applications and the interaction between hardware and software. The mobile software stack serves as an abstraction
layer that shields developers from the complexities of hardware while providing a standardized environment for app development.

Typically, a mobile software stack consists of several layers, each with its specific responsibilities and functionalities. Here are the
typical layers in a mobile software stack:

1. **Application Layer:**

- **Purpose:** This is the topmost layer where user-facing mobile applications reside. It includes the actual apps that users interact
with.

- **Components:** Mobile applications, also known as "apps," are developed for specific tasks, such as social networking, mes-
saging, gaming, productivity, and more.

2. **Application Framework Layer:**


- **Purpose:** Below the application layer is the application framework, which provides a set of libraries and APIs for app devel-
opment. It offers tools and services that simplify common tasks like UI rendering, data storage, and network communication.

- **Components:** Frameworks for UI rendering (e.g., Android's View and Layout classes), data storage (e.g., SQLite), and com-
munication (e.g., HTTP libraries).

3. **Libraries and APIs Layer:**

- **Purpose:** This layer includes various libraries and APIs that enable developers to access device-specific functionality and ser-
vices. It bridges the gap between the app's code and the underlying hardware and operating system.

- **Components:** Libraries for accessing hardware features like sensors, cameras, and GPS, as well as APIs for services like loc-
ation, contacts, and push notifications.

4. **Runtime Layer (Virtual Machine):**

- **Purpose:** The runtime layer hosts the runtime environment where app code is executed. It abstracts the underlying hardware,
allowing apps to run on different devices and platforms.

- **Components:** Mobile operating systems use virtual machines or runtime environments like the Android Runtime (ART) or
the Java Virtual Machine (JVM) to execute app code.

5. **Operating System Layer:**

- **Purpose:** The operating system (OS) layer manages hardware resources, provides core services, and enforces security and ac-
cess control. It acts as an intermediary between the hardware and higher-level software.

- **Components:** Kernel, drivers, system services (e.g., memory management, process management), and security mechanisms.
6. **Kernel and Hardware Abstraction Layer:**

- **Purpose:** At the lowest level, the kernel and hardware abstraction layer interact directly with the device's hardware compon-
ents, such as the CPU, memory, display, and input devices.

- **Components:** Kernel (Linux kernel in Android), device drivers, hardware abstraction layers (HALs), and hardware-specific
libraries.

Each layer in the mobile software stack serves a specific role in the execution and functioning of mobile applications. App developers
interact primarily with the top three layers (Application, Application Framework, Libraries and APIs), while the lower layers are
managed by the mobile operating system. This layered architecture allows for portability, security, and ease of development in the
world of mobile app development.
UNIT - II
Q. No Questions
Resources in Android:
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.

Organize resource in Android Studio


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

Sr.No. Directory & Resource Type


anim/
1
XML files that define property animations. They are saved in res/anim/ folder and accessed from the R.anim class.

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

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

layout/
4
XML files that define a user interface layout. They are saved in res/layout/ and accessed from the R.layout class.
menu/
5
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.
raw/
6
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.
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.
7  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.
xml/
8
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.
(Or)
2 The AndroidManifest.xml file contains information of your package, including components of the application such as activities,
services, broadcast receivers, content providers etc.
It performs some other tasks also:
It is responsible to protect the application to access any protected parts by providing the permissions.
It also declares the android api that the application is going to use.
It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are
removed just before the application is published etc.
This is the required xml file for all the android application and located inside the root directory.

Elements of the AndroidManifest.xml file


The elements used in the above xml file are described below.
<manifest>
manifest is the root element of the AndroidManifest.xml file. It has package attribute that describes the package name of the activity
class.
<application>
application is the subelement of the manifest. It includes the namespace declaration. This element contains several subelements that
declares the application component such as activity etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.
<activity>
activity is the subelement of application and represents an activity that must be defined in the AndroidManifest.xml file. It has many
attributes such as label, name, theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity, service or broadcast receiver can
respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.
<category>
It adds a category name to an intent-filter.
3 Android Directory Structure:

Within an Android project structure, the most frequently edited folders are:

 src - Java source files associated with your project. This includes the Activity "controller" files as well as your
models and helpers.
 res - Resource files associated with your project. All graphics, strings, layouts, and other resource files are stored
in the resource file hierarchy under the res directory.
 res/layout - XML layout files that describe the views and layouts for each activity and for partial views such as list
items.
 res/values - XML files which store various attribute values. These include strings.xml, dimens.xml, styles.xml, col-
ors.xml, themes.xml, and so on.
 res/drawable - Here we store the various density-independent graphic assets used in our application.
 res/drawable-hdpi - Series of folders for density specific images to use for various resolutions.

res/mipmap - most commonly used for application icons.


The most frequently edited files are:

 res/layout/activity_foo.xml - This file describes the layout of the activity's UI. This means the placement of
every view object on one app screen.
 src/.../FooActivity.java - The Activity "controller" that constructs the activity using the view, and handles all
event handling and view logic for one app screen.
 AndroidManifest.xml - This is the Android application definition file. It contains information about the Android ap-
plication such as minimum Android version, permission to access Android device capabilities such as internet ac-
cess permission, ability to use phone permission, etc.

Other less edited folders include:

 gen - Generated Java code files, this library is for Android internal use only.
 assets - Uncompiled source files associated with your project; Rarely used.
 bin - Resulting application package files associated with your project once it’s been built.
 libs - Before the introduction of Gradle build system, this directory was used for any secondary libraries (jars) you
might want to link to your app.

4 To create an Android app that opens a webpage using an implicit intent, you'll need to follow these steps:

1. **Create a New Android Project**:

Open Android Studio and create a new project with an appropriate name (e.g., "WebpageOpener").

2. **Design the User Interface**:

Open the `activity_main.xml` layout file and add a Button. This button will be used to trigger the action of opening a webpage.

```xml
<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/openWebpageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Webpage" />
</LinearLayout>
```

3. **Implement the Button Click Event**:

Open `MainActivity.java` and implement the code to open a webpage when the button is clicked.

```java
// MainActivity.java
package com.example.webpageopener;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

// Find the Button by its ID


findViewById(R.id.openWebpageButton).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Define the URL of the webpage to open
String webpageUrl = "https://www.example.com";

// Create an Intent with the ACTION_VIEW action and set the webpage URL
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpageUrl));

// Start the activity to open the webpage


startActivity(intent);
}
});
}
}
```

4. **Add Internet Permission**:

Open `AndroidManifest.xml` and add the `<uses-permission>` element to request internet access permission.
```xml
<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.INTERNET" />
```

5. **Test the App**:

Connect an Android device or start an emulator, then run the app. When you click the "Open Webpage" button, it should open the specified
webpage in the default browser.

That's it! You've created an Android app that opens a webpage using an implicit intent..
5 In Android, Content Providers are a very important component that serves the purpose of a relational database to store the data of applicatio
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 oth
applications to securely access and modifies that data based on the user requirements. Android system allows the content provider to store th
application data in several ways. Users can manage to store the application data like images, audio, videos, and personal contact information
storing them in SQLite Database, in files, or even on a network. In order to share the data, content providers have certain permissions tha
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 u
a query string.

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

Details of different parts of Content URI:

content:// – Mandatory part of the URI as it represents that the given URI is a Content URI.
authority – Signifies the name of the content provider like contacts, browser, etc. This part must be unique for every content provider.

optionalPath – Specifies the type of data provided by the content provider. It is essential as this part helps content providers to support diffe
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.

Abstract Method Description

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

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


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

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


update()
It returns the number of rows updated.

This method is used to delete the existing rows.


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail


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

As the content provider is created, the android system calls


onCreate()
this method immediately to initialise the provider.

6 Describe in detail about Raw Folder and the steps involved to create a Raw folder in Android Studio

Raw Resources:
❖ The raw (res/raw) folder is one of the most important folders and it plays a very important role during the development of
android projects in android studio.

❖ The raw folder in Android is used to keep mp3, mp4, sfb files, etc. The raw folder is created inside the res folder:
main/res/raw. So we will simply create it inside the res folder.

❖ But before creating a raw folder let’s have a look at the asset folder in android which acts the same role as the raw folder in
android studio.

Create Resource Raw Folder in Android Studio


1. Step 1: To create the Resource Raw folder in Android studio open your project in Android mode first as shown in the below image.

2. Step 2: Open your android studio go to the app > res > right-click > New > Android Resource Directory
3. Step 3: Then a pop-up screen will arise like below. Here in Resource type choose raw.
4. Step 4: After choosing the raw from the dropdown menu click on the OK button and keep all the things as it is.

5. Step 5: Now you can see the raw folder has been created and you can find the folded in the app > res > raw
Resource raw folder is different from the Assets folder
In Android one can store the raw asset file like JSON, Text, mp3, HTML, pdf, etc in two possible locations:
1. assets

2. res/raw folder

Both of them appear to be the same, as they can read the file and generate InputStream as below.
// From assets
assets.open(assetPathFilename)
// From res/raw
resources.openRawResource(resourceRawFilename)

7 Describe the key components of a Content Provider, and how do they interact to manage data access in Android.

A Content Provider in Android is a key component of the Android architecture that allows apps to share structured sets of data with
other apps. It provides a consistent and secure way to manage and access data, such as databases, files, or content, and allows for data
isolation between apps. The key components of a Content Provider and how they interact to manage data access in Android are as
follows:

1. Content URI (Uniform Resource Identifier):


o A Content URI uniquely identifies the data that a Content Provider manages. It consists of a scheme, authority, and
path and is used to specify the data to be accessed.
o Example: content://com.example.myapp/books
2. URI Matcher:
o A URI Matcher is used to match incoming Content URIs to specific data tables or resources handled by the Content
Provider. It helps route incoming requests to the appropriate data source.
o Example: Mapping content://com.example.myapp/books to the "books" table.
3. Data Storage:
o The Content Provider interacts with a data storage mechanism, which can be a database, file system, or any other data
source. It manages the actual data storage and retrieval.
o Example: Storing and retrieving book information in a database.
4. Content Resolver:
o The Content Resolver is a client-side component that Android apps use to interact with Content Providers. It sends re-
quests to the Content Provider using Content URIs.
o Example: An app requests a list of books using a Content URI, and the Content Resolver forwards the request to the
appropriate Content Provider.
5. Provider Methods:
o Content Providers implement various methods to handle CRUD (Create, Read, Update, Delete) operations on data.
These methods include query(), insert(), update(), and delete().
o Example: The query() method retrieves a list of books matching certain criteria from the Content Provider's data
source.
6. Permissions and Security:
o Content Providers enforce permissions and security measures to control access to data. Developers specify permis-
sions in the AndroidManifest.xml file to restrict which apps can access the data.
o Example: Specifying that only the app itself and specific trusted apps can access the "books" data.
7. Content Type (MIME Type):
o Content Providers define the type of data they can handle using MIME types. This helps clients understand the type of
data they will receive.
o Example: vnd.android.cursor.dir/vnd.com.example.myapp.books for a list of books and vnd.android.curs-
or.item/vnd.com.example.myapp.books for a single book.

These components work together to allow apps to access and manipulate data provided by the Content Provider. When an app needs data, it
constructs a Content URI, sends a request through the Content Resolver, and the Content Provider processes the request, returning the
requested data or performing the specified operation on the data source. This architecture ensures data isolation and controlled access,
enhancing the security and consistency of data management in the Android ecosystem.
8 Explain the significance of intents in Android app communication
Intents play a significant role in Android app communication, and their importance cannot be overstated. They serve as a fundamental
mechanism for inter-component and inter-app communication, enabling seamless interactions within the Android ecosystem. Here's why
intents are so significant in Android:

1. **Component Communication:** Intents facilitate communication between different components of an Android app, such as Activities,
Services, and Broadcast Receivers. For example, an Activity can use an intent to start another Activity within the same app.

2. **App Integration:** Intents enable apps to work together and integrate functionality. Apps can send and receive intents, allowing them to
request services or data from other apps. For instance, a camera app can request access to the device's photo gallery to select a photo for
editing.

3. **Loose Coupling:** Intents promote loose coupling between app components. Components don't need to be aware of each other's
implementation details, which enhances modularity and code maintainability.

4. **Implicit and Explicit Intents:** Android supports both implicit and explicit intents. Implicit intents allow apps to request services without
specifying the exact component that will handle the request. Explicit intents, on the other hand, specify a target component by name,
promoting precise communication.

5. **Broadcasting:** Intents can be broadcasted system-wide or within an app. This broadcasting mechanism is useful for system events, such
as low battery alerts, and for apps to communicate with their own components.

6. **User-Friendly:** Intents are user-friendly. Users can interact with different apps intuitively, such as sharing content from one app to
another. This enhances the overall user experience.

7. **Security and Permission Control:** Intents are used to enforce security and permissions. Apps can declare which intents they can handle
and specify required permissions. This ensures that sensitive data is not exposed without proper authorization.

8. **Third-Party Integration:** Intents allow third-party developers to extend the functionality of existing apps. Apps can define and register
custom intent filters to specify the types of intents they can handle.

9. **Flexibility:** Intents are versatile and can carry various types of data, including text, binary data, and custom data types. This flexibility
enables a wide range of use cases, from sharing text to launching complex tasks.

10. **Multi-App Workflows:** Intents make it possible to create multi-app workflows. For example, users can click on a map location in one
app, and the device will offer a selection of mapping apps to handle the request.

In summary, intents are a cornerstone of Android app communication. They empower developers to build modular, interconnected, and user-
friendly apps that can seamlessly collaborate with other apps in the Android ecosystem. This flexibility and interactivity contribute to Android's
rich and dynamic user experience.
UNIT - III
Q. No Questions

ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

ListView listView = (ListView) findViewById(R.id.lvItems);


listView.setAdapter(itemsAdapter);
2 The "Gallery" control, also known as the "Gallery View" in Android, is a user interface (UI) component used in mobile application development
for displaying a scrollable grid or list of images or other items, such as text, icons, or videos. Its purpose is to provide users with a visually
appealing and interactive way to browse and select items from a collection. Here are some key purposes and features of the Gallery control:

1. **Image Browsing:** The Gallery control is commonly used to create image galleries or image viewers within mobile apps. Users can swipe
or scroll through a collection of images, making it ideal for applications like photo viewers, image galleries, or product catalogs.

2. **Selection Interface:** It provides an intuitive way for users to select items from a list or grid. Users can tap on an item to interact with it or
select it, which is useful for creating interfaces like image pickers or item selection dialogs.

3. **Customizable Appearance:** Developers can customize the appearance of the Gallery control, allowing for various visual styles, including
thumbnail views, carousel-style scrolling, or custom item layouts.

4. **Scrollable Content:** The Gallery control allows users to scroll horizontally or vertically through a set of items. This can be useful for
displaying content when screen real estate is limited.
5. **Item Interaction:** Developers can define interactions for each item within the Gallery, such as responding to item clicks, long presses, or
gestures like swiping.

6. **Adapter-Based:** Like many Android UI components, the Gallery is typically populated using an adapter, which allows developers to
dynamically load and display content from various data sources, such as local storage, remote servers, or databases.

7. **Support for Multimedia:** In addition to images, the Gallery control can be used to display and interact with multimedia content like
videos or audio clips.

8. **Responsive Design:** The Gallery control can adapt to different screen sizes and orientations, making it suitable for both phones and
tablets.

9. **User Engagement:** Its interactive nature can enhance user engagement, as users can explore and select items with ease.

10. **Integration:** It can be integrated with other UI elements and functionalities, such as image zooming, sharing options, or item details.

11. **Applicability:** While the Gallery control is commonly used for displaying images, it can also be adapted to showcase other types of
content, like product listings, news articles, or user profiles.

In summary, the Gallery control is a versatile UI component that enhances user experience by providing an interactive and visually appealing
way to browse, select, and interact with items, particularly images, within a mobile application. Its customizable nature allows developers to
tailor its appearance and behavior to suit the specific needs of their apps.
3 <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter First Number:-"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Second Number"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_toRightOf="@+id/editText"
android:layout_toEndOf="@+id/editText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sum of Two No"
android:id="@+id/button"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_result"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
public void sum(View v)
{
//get the edit text
EditText t1=(EditText)findViewById(R.id.editText);
EditText t2=(EditText)findViewById(R.id.editText2);
//convert value into int
int x=Integer.parseInt(t1.getText().toString());
int y=Integer.parseInt(t2.getText().toString());

int z=x/y;
//display this text to TextView
TextView tv_data=(TextView)findViewById(R.id.tv_result);
tv_data.setText("The division :"+z);
}
4 The GridView layout is a ViewGroup that groups view in a two-dimensional scrolling grid of rows and
columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable
and we don’t need to use ScrollView. An example of GridView is your default Gallery.
Attributes of a GridView

Attributes Description

id Like all other views, android uses the id element to uniquely identify an element.

The number of columns to display. It can be an integer or auto_fit which will display as many
numColumns possible columns to fill the screen of the device. If they don’t specify this attribute then the grid
view will behave like a listview.

horizontalSpacing property is used to define the default horizontal spacing between columns.
horizontalSpacing
This could be in pixel(px), density pixel(dp), or scale-independent pixel(sp).

The vertical spacing property is used to define the default vertical spacing between rows. This
verticalSpacing
should be in px, dp or sp.

An Adapter is a connection between the UI components(TextView, ImageView) and the data source.
An adapter helps fill the UI element with the appropriate data. In android commonly used adapters
that fill data in GridView are:
1. ArrayAdapter
2. BaseAdapter
3. Custom ArrayAdapte
public class MyAdapter extends BaseAdapter {
@Override public int getCount() {
return 0;
}

@Override public Object getItem(int i) {


return null;
}

@Override public long getItemId(int i) {


return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
}
Method Description:
 getCount(): this method returns the count of the total elements to be displayed.
 getItem(int i): this method takes in an index and returns an object.
 getItemId(int i): this method takes in an index and returns the id of the item being displayed in the
GridView.
 getView(int I, View view, ViewGroup group): this is the most important method which returns a
view that is displayed in the grid view. The int i is the index, the view can be (ImageView or Tex -
tView), and the view group is the container that hosts the View e.g LinearLayout, RelativeLayout,
etc.
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<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:orientation="vertical">

<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="center"
tools:srcCompat="@tools:sample/avatars" />

</LinearLayout>
public View getView(int i, View view, ViewGroup viewGroup)
{
if (view == null)
{
LayoutInflater inflater =
(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.grid_layout, viewGroup);
}

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


imageView.setImageResource(items[i]);
return view;
}

import android.os.Bundle;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

int[] itemsarray = new int[]{


R.drawable.android_1, R.drawable.android_2,
R.drawable.android_3, R.drawable.android_4,
R.drawable.android_5, R.drawable.android_1,
R.drawable.android_2, R.drawable.android_3,
R.drawable.android_4, R.drawable.android_5
};

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

GridView gridView = findViewById(R.id.grid_view);

// create a object of myBaseAdapter


MyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray);
gridView.setAdapter(baseAdapter);
}
}

5 Gallery app is one of the most used apps which comes pre-installed on many android devices and there are
several different apps that are present in Google Play to view the media files present in your device.
Simple Gallery brings you a photo manager that allows you to view images, edit photos and create photo galleries, all in one easy to use app
Step-by-Step Implementation
Step 1: Create a New Project
Step 2: Add the dependency in build.gradle file
Navigate to the app > Gradle Scripts > build.gradle(:app) and add the below dependency to it. We are using
casso for loading images from paths in our ImageView.
Step 3: Adding permissions in our AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml file and add the below permissions to it.
<!-- permissions for reading external storage -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Step 4: Working with the activity_main.xml file

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

Step 6: Creating a new activity for displaying a single image

Navigate to the app > java > your app’s package name > Right-click on it > New > Empty Activity and name yo
activity as ImageDetailActivity and create a new activity. We will be using this activity to display our single image f
the list of different images.
Step 7: Creating an adapter class for setting data to each item in our RecyclerView

Navigate to the app > java > your app’s package name > Right-click on it > New Java class and name your cla
as RecyclerViewAdapter and add the below code to it
Step 8: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Co
ments are added inside the code to understand the code in more detail.
Step 9: Working with the activity_image_detail.xml file.

Navigate to the app > res > layout > activity_image_detail.xml and add the below code to that file. Below is the c
for the activity_image_detail.xml file.

Step 10: Working with ImageDetailActivity.java file

Go to the ImageDetailActivity.java file and refer to the following code. Below is the code for the ImageDetailActiv
java file.

6 It 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 onConnection-
Failed(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.

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {


Location currentLocation;
FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fetchLocation();
}
private void fetchLocation() {
if (ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(),
Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.myMap);
assert supportMapFragment != null;
supportMapFragment.getMapAsync(MainActivity.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here!");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));
googleMap.addMarker(markerOptions);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
fetchLocation();
}
break;
}
}
}
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

7 A `MapView` control in mobile application development is used to display maps and allow users to interact with them. It's particularly useful for
applications that require location-based services, such as navigation, geolocation-based services, and even gaming.

Here's an example of how a `MapView` control can be used in Android:

1. **Setting Up the Project**:

Start by creating a new Android project in Android Studio. Ensure you have the necessary permissions set for accessing the internet and
location services in the AndroidManifest.xml file.

2. **Adding the MapView in Layout**:

Open the activity's layout file (e.g., `activity_main.xml`) and add a `MapView` element.

```xml
<!-- activity_main.xml -->
<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">

<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

</RelativeLayout>
```

3. **Initializing MapView in Activity**:


Open the corresponding Activity (e.g., `MainActivity.java`) and initialize the `MapView` in `onCreate()`.

```java
// MainActivity.java
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

private MapView mapView;

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

// Find the MapView by its ID


mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);

// Get notified when the map is ready to be used


mapView.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
// Customize and interact with the map here
// Example: Add a marker
LatLng location = new LatLng(37.7749, -122.4194); // Coordinates for San Francisco
googleMap.addMarker(new MarkerOptions().position(location).title("Marker in San Francisco"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 12.0f));
}

// Handle the lifecycle events of the MapView


@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}

@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}

@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}

@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
```

4. **Provide Google Maps API Key**:

In the `AndroidManifest.xml` file, add your Google Maps API key as a meta-data element inside the `application` tag.

```xml
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY" />
```

Replace `YOUR_API_KEY` with your actual API key.

5. **Testing**:

Run the application on an emulator or physical device. You should see a map centered on San Francisco with a marker.

Remember to replace `YOUR_API_KEY` with your actual Google Maps API key. This example demonstrates the basic setup of a `MapView`
control in Android. You can further customize it with various functionalities provided by the Google Maps SDK.
8 In Android UI development, adapters act as a bridge between data sources and UI elements like ListView, GridView, Spinner, etc. They play a
crucial role in efficiently displaying large sets of data in a user-friendly manner.

Here's how adapters facilitate the connection between data sources and UI elements:
1. **Data Retrieval**:
- Adapters retrieve data from a data source, which can be an array, list, database, or any other collection of data.

2. **Data Transformation**:
- Adapters transform the raw data into a format that can be displayed in UI elements. For example, in a ListView, each item needs to be
formatted appropriately.

3. **View Creation**:
- Adapters create individual views for each item in the data source. These views are generated based on the layout specified in the adapter.

4. **View Recycling**:
- Adapters efficiently reuse views to conserve system resources. Instead of creating a new view for each item, adapters recycle existing views
that are no longer visible on the screen.

5. **Binding Data to Views**:


- Adapters associate the data from the data source with the appropriate views. For instance, in a ListView, the adapter assigns the data to the
respective TextViews or ImageViews.

6. **Managing Data Changes**:


- Adapters listen for changes in the underlying data source and automatically update the UI elements. This dynamic binding ensures that the
UI reflects any changes in the data.

7. **Handling User Interaction**:


- Adapters manage interactions with UI elements. For instance, they handle click events on list items and trigger appropriate actions based on
user input.

8. **Optimizing Performance**:
- Adapters help in optimizing performance by using techniques like view recycling. This ensures smooth scrolling and reduces memory
consumption, especially when dealing with large datasets.

9. **Customization and Flexibility**:


- Adapters can be customized to handle specific data formats or layouts. Developers can create custom adapters to suit their specific
application requirements.

In summary, adapters serve as intermediaries that handle the data flow between the underlying data source and the UI elements. They
abstract away much of the complexity involved in managing and displaying data, making it easier for developers to create dynamic and
interactive user interfaces.
UNIT - IV
Q. No Questions
1 An interpolator is a function (in the mathematical sense) that outputs values “interpolated” between a range of values that are given
to it as input. Interpolation is simply a method to generate new data points between two fixed data points. The exact values of these
generated data points are determined by the kind of interpolation is performed. For example, in linear interpolation, all the
generated values are evenly distributed between the fixed points. While an understanding of interpolation is helpful, it isn’t necessary
to get started animating your views in your apps
The Interpolator Interface
In the Android development framework, Interpolator is defined as an interface. This allows methods to accept an interpolator that can
bring its own configuration and not tie developers to a specific implementation. As of this writing, there are 11 indirect subclasses of
the Interpolator interface. They are:
Linear Interpolator: The generated values between the two fixed points are evenly distributed. For example, consider a = 1 and b = 5
to be the fixed points. Linear interpolation between a and b would look like: 1 -> 2 -> 3 -> 4 -> 5, where the numbers between 1 and
5 have been generated.
Accelerate Interpolator: This interpolator generates values that initially have a small difference between them and then ramps up the
difference gradually until it reaches the endpoint. For example, the generated values between 1 -> 5 with accelerated interpolation
could be 1 -> 1.2 -> 1.5 -> 1.9 -> 2.4 -> 3.0 -> 3.6 -> 4.3 -> 5. Notice how the difference between consecutive values grows
consistently.
Decelerate Interpolator: In the sense that the accelerate interpolator generates values in an accelerating fashion, a decelerate
interpolator generates values that are “slowing down” as you move forward in the list of generated values. So, the values generated
initially have a greater difference between them and the difference gradually reduces until the endpoint is reached. Therefore, the
generated values between 1 -> 5 could look like 1 -> 1.8 -> 2.5 -> 3.1 -> 3.6 -> 4.0 -> 4.
Accelerate Decelerate Interpolator: This interpolator starts out with a slow rate of change and accelerates towards the middle. As it
approaches the end, it starts decelerating, i.e. reducing the rate of change.
Anticipate Interpolator: This interpolation starts by first moving backward, then “flings” forward, and then proceeds gradually to the
end. This gives it an effect similar to cartoons where the characters pull back before shooting off running. For example, generated
values between 1 -> 3 could look like: 1 -> 0.5 -> 2 -> 2.5 -> 3. Notice how the first generated value is “behind” the starting value
and how it jumps forward to a value ahead of the starting value. It then proceeds uniformly to the endpoint.
Bounce Interpolator: To understand this interpolator, consider a meter scale that’s standing vertically on a solid surface. The starting
value is at the top and the end value is at the bottom, touching the surface. Consider now, a ball that is dropped next to the meter
scale. The ball on hitting the surface bounces up and down a few times until finally coming to rest on the surface. With the bounce
interpolator, the generated values are similar to the list of values the ball passes by alongside the meter scale. For example, the
generated values between 1 -> 5 could be 1 -> 2 -> 3 -> 4 -> 5 -> 4.2 -> 5 -> 4.5 -> 5. Notice how the generated values bounce.
Overshoot Interpolator: This interpolator generates values uniformly from the start to end. However, after hitting the end, it
overshoots or goes beyond the last value by a small amount and then comes back to the endpoint. For example, the generated values
between 1 -> 5 could look like: 1 -> 2 -> 3 -> 4 -> 5 -> 5.5 -> 5.
Anticipate Overshoot Interpolator: This interpolator is a combination of the anticipate and overshoot interpolators. That is, it first
goes backward from the starting value, flings forward and uniformly moves to the endpoint, overshoots it, and then returns to the
endpoint.
Step 1: Working with the activity_main.xml file
Step 2: Working with the MainActivity.java file
Setup ObjectAnimator Object: For this example, we’ll use a single ObjectAnimator to animate the different
buttons. We’ll also use a fixed duration of 2 seconds for the animations to play out, this gives us ample time to
observe the animation behaviors. You can have this set up with 2 lines of code as below.
/ 2-second animation duration
final private static int ANIMATION_DURATION = 2000;
private ObjectAnimator animator;
Setup Animations on Button Click: Now that we have the pre-requisites setup, we can finally get to config-
uring the buttons to trigger their respective animations. For each button, you can configure the specific prop -
erty to animate, its duration, and the interpolation, among other things. The basic three-step configuration is
performed as shown in the code snippet below:
 Java

// Linear
binding.linear.setOnClickListener(clickedView -> {
animator = ObjectAnimator.ofFloat(binding.linear,"translationX", 200f);
animator.setInterpolator(new LinearInterpolator());
animator.setDuration(ANIMATION_DURATION);
animator.start();
});

2 In android, Slide Up and Slide Down animations are used to change the appearance and behavior of the objects over a particular
interval of time. The Slide Up and Slide Down animations will provide a better look and feel for our applications.
For Slide Up animation, we need to set android:fromYScale="1.0" and android:toYScale="0.0" like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
For Slide Down animation, we need to set android:fromYScale="0.0" and android:toYScale="1.0" like as shown below.

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


<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
3 In android, Context Menu is like a floating menu and that appears when the user performs a long press or click on an
element and it is useful to implement actions that affect the selected content or context frame.

The android Context Menu is more like the menu which displayed on right-click in Windows or Linux.

Following is the pictorial representation of using Context Menu in our android applications.
In android, the Context Menu offers actions that affect a specific item or context frame in the UI and we can provide a
context menu for any view. The context menu won’t support any item shortcuts and item icons.

Create Android Context Menu in Activity


The views which we used to show the context menu on long-press, we need to register that views using registerFor-
ContextMenu(View) in our activity and we need to override onCreateContextMenu() in our activity or fragment.

When the registered view receives a long-click event, the system calls our onCreateContextMenu() method. By using
the onCreateContextMenu() method, we can create our menu items as shown below.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btnShow);
registerForContextMenu(btn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menu-
Info) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Upload");
menu.add(0, v.getId(), 0, "Search");
}
If you observe above code, we registered our Button control using registerForContextMenu() to show the context
menu on button long-click and binding the Context Menu items using onCreateContextMenu() method.

Handle Android Context Menu Click Events


In android, we can handle a context menu item click events using the onContextItemSelected() method.

Following is the example of handling a context menu item click event using onContextItemSelected() method.

@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Save") {
// do your coding
}
else {
return false;
}
return true;
}

OUTPUT:

4 <?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press The Back Button of Your Phone."
android:textStyle="bold"
android:textSize="30dp"
android:gravity="center_horizontal"
android:layout_marginTop="180dp"
/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Declare the onBackPressed method
// when the back button is pressed
// this method will call
@Override
public void onBackPressed()
{
// Create the object of
// AlertDialog Builder class
AlertDialog.Builder builder
= new AlertDialog
.Builder(MainActivity.this);
// Set the message show for the Alert time
builder.setMessage("Do you want to exit ?");
// Set Alert Title
builder.setTitle("Alert !");
// Set Cancelable false
// for when the user clicks on the outside
// the Dialog Box then it will remain show
builder.setCancelable(false);

// Set the positive button with yes name


// OnClickListener method is use of
// DialogInterface interface.

builder
.setPositiveButton(
"Yes",
new DialogInterface
.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which)
{

// When the user click yes button


// then app will close
finish();
}
});

// Set the Negative button with No name


// OnClickListener method is use
// of DialogInterface interface.
builder
.setNegativeButton(
"No",
new DialogInterface
.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which)
{
// If user click no
// then dialog box is canceled.
dialog.cancel();
}
});
// Create the Alert dialog
AlertDialog alertDialog = builder.create();
// Show the Alert Dialog box
alertDialog.show();
}
}
5 In Android Frame Animation, you will be swapping frames repeatedly, so that it appears continuous to the human
eye and we feel that it is animated. Frame is referred to an image. So to implement frame by frame animation in
android, one needs to have set of images, which describes a motion.
Step 1- Create a drawable folder

Within it create an animation_list.xml file.


It includes :
A list of items that has the addresses of the frame images.

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


<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/blank" android:duration="210" />
<item android:drawable="@drawable/logo" android:duration="210" />
<item android:drawable="@drawable/logo1" android:duration="210" />
<item android:drawable="@drawable/logo2" android:duration="210" />
<item android:drawable="@drawable/logo3" android:duration="210" />
<item android:drawable="@drawable/logo4" android:duration="210" />
<item android:drawable="@drawable/logo5" android:duration="210" />
<item android:drawable="@drawable/logo6" android:duration="210" />
<item android:drawable="@drawable/logofinal" android:duration="210" />
</animation-list>
Step 2: Create an activity_main.xml file
It Includes : An Image View

1
2
3
{/code]
4
<span style="font-size: 13px; text-align: center;">Here we are done with the xml part, see the image below for r
5
<p style="text-align: center;"><a href="https://www.edureka.co/blog/frame-animation-in-android/"
6
ter size-full wp-image-2382" title="XML part in Frame animation" alt="XML part in Frame animation" src="https:/
7
content/uploads/2013/02/Project.jpg" width="845" height="603" /></a></p>
8
<strong>&nbsp;</strong>
9
<h2><span style="font-size: large;"><strong>Step 3- Outside the onCreate method :</strong></span></h2>
1
<strong></strong>Declare the Image View and Animation Drawable
0
1
1
// Declaring an Image View and an Animation Drawable
1
ImageView view;
2
AnimationDrawable frameAnimation;
Step 3- Inside the OnCreate method:
 Typecast the Image view
 Typecast the Animation Drawable
 Set the drawable background on the image view

// Typecasting the Image View


1
view = (ImageView) findViewById(R.id.imageAnimation);
2

3
// Setting animation_list.xml as the background of the image view
4
view.setBackgroundResource(R.drawable.animation_list);
5

// Typecasting the Animation Drawable


7

frameAnimation = (AnimationDrawable) view.getBackground();


8
Step 4- After the onCreate method :
The animation should only run when it is in focus that is when it is visible to the user. Hence define this
method after the onCreate method.

// Called when Activity becomes visible or invisible to the user


@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// Starting the animation when in Focus
frameAnimation.start();
} else {
// Stoping the animation when not in Focus
frameAnimation.stop();
}
}
Screen Shots:

6 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:
Property Animation
View Animation
Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animating almost everything. This is one of
the powerful and flexible animations which was introduced in Android 3.0. Property animation can be used to
add any animation in the CheckBox, RadioButtons, and widgets other than any view.
2. View Animation
View Animation can be used to add animation to a specific view to perform tweened animation on views.
Tweened animation calculates animation information such as size, rotation, start point, and endpoint. These
animations are slower and less flexible. An example of View animation can be used if we want to expand a
specific layout in that place we can use View Animation. The example of View Animation can be seen in Ex -
pandable 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 ex -
ample of drawable animation can be seen in many apps Splash screen on apps logo animation.

Important Methods of Animation

startAnimation()-This method will start the animation.


clearAnimation()-This method will clear the animation running on a specific view.

Example:

<?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>
<?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>
7 The `AnimationDrawable` class in Android is used to create frame-by-frame animations. It's particularly useful for creating simple animations
where a series of images are displayed in sequence to give the illusion of motion.

**Role of AnimationDrawable:**

1. **Sequential Frames:** You define a series of Drawable resources (images) in your app, where each drawable represents an individual frame
of the animation.

2. **Defining the Animation:** In an XML resource file, you create an `<animation-list>` containing a list of items. Each item specifies a
drawable and the duration it should be displayed.

Example XML resource (`res/drawable/animation_spinner.xml`):

```xml
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/selected"
android:oneshot="false">
<item android:drawable="@drawable/frame1" android:duration="50" />
<item android:drawable="@drawable/frame2" android:duration="50" />
<!-- Add more frames as needed -->
</animation-list>
```

3. **Using the Animation:** In your code, you create an `AnimationDrawable` object and set it as the background of a `View`.

```java
ImageView loadingSpinner = findViewById(R.id.loading_spinner);
AnimationDrawable spinnerAnimation = (AnimationDrawable) loadingSpinner.getBackground();
spinnerAnimation.start();
```

Here, `loadingSpinner` is an `ImageView` in your layout.

4. **Starting the Animation:** You start the animation by calling the `start()` method on the `AnimationDrawable` object. This begins the frame
sequence.

```java
spinnerAnimation.start();
```

If you want the animation to loop indefinitely, set `android:oneshot="false"` in the XML resource. If you want it to play only once, set it to
`true`.

5. **Optional Interaction:** You can interact with the animation, such as pausing or stopping it, by using methods like `stop()` and
`selectDrawable()`.

**Example Scenario:**

A common scenario for using `AnimationDrawable` is in creating loading spinners or progress indicators. For instance, imagine a weather app
that needs to fetch data from a remote server. While the data is being fetched, you want to show a loading spinner to indicate that the app is
working. You can use `AnimationDrawable` to create a spinner animation, where the frames represent different states of the spinner's rotation.
This gives users visual feedback that the app is actively processing their request.

In summary, `AnimationDrawable` is a powerful tool for creating simple, frame-based animations, and it's often used for loading indicators,
progress bars, and other visual effects in Android applications.
8 The "Gallery" control, also known as the "Gallery View" in Android, is a user interface (UI) component used in mobile application development
for displaying a scrollable grid or list of images or other items, such as text, icons, or videos. Its purpose is to provide users with a visually
appealing and interactive way to browse and select items from a collection. Here are some key purposes and features of the Gallery control:

1. **Image Browsing:** The Gallery control is commonly used to create image galleries or image viewers within mobile apps. Users can swipe
or scroll through a collection of images, making it ideal for applications like photo viewers, image galleries, or product catalogs.

2. **Selection Interface:** It provides an intuitive way for users to select items from a list or grid. Users can tap on an item to interact with it or
select it, which is useful for creating interfaces like image pickers or item selection dialogs.

3. **Customizable Appearance:** Developers can customize the appearance of the Gallery control, allowing for various visual styles, including
thumbnail views, carousel-style scrolling, or custom item layouts.

4. **Scrollable Content:** The Gallery control allows users to scroll horizontally or vertically through a set of items. This can be useful for
displaying content when screen real estate is limited.

5. **Item Interaction:** Developers can define interactions for each item within the Gallery, such as responding to item clicks, long presses, or
gestures like swiping.

6. **Adapter-Based:** Like many Android UI components, the Gallery is typically populated using an adapter, which allows developers to
dynamically load and display content from various data sources, such as local storage, remote servers, or databases.
7. **Support for Multimedia:** In addition to images, the Gallery control can be used to display and interact with multimedia content like
videos or audio clips.

8. **Responsive Design:** The Gallery control can adapt to different screen sizes and orientations, making it suitable for both phones and
tablets.

9. **User Engagement:** Its interactive nature can enhance user engagement, as users can explore and select items with ease.

10. **Integration:** It can be integrated with other UI elements and functionalities, such as image zooming, sharing options, or item details.

11. **Applicability:** While the Gallery control is commonly used for displaying images, it can also be adapted to showcase other types of
content, like product listings, news articles, or user profiles.

In summary, the Gallery control is a versatile UI component that enhances user experience by providing an interactive and visually appealing
way to browse, select, and interact with items, particularly images, within a mobile application. Its customizable nature allows developers to
tailor its appearance and behavior to suit the specific needs of their apps.

UNIT - V
Q. No Questions
1 There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread . This subclass should
override the run method of class Thread . An instance of the subclass can then be allocated and started.
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
...
}
}
PrimeThread p = new PrimeThread(143);
p.start();
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
...
}
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
2 A Job Scheduler in Android allows you to defer background work until certain conditions are met. It's a flexible API that helps you
optimize battery life and system resources.

Here's how it works, along with an example:

**How Job Scheduler Works:**

1. **JobInfo**: You create a `JobInfo` object specifying the conditions under which the job should run (e.g., network connection,
charging status, etc.).

2. **JobScheduler**: You use the `JobScheduler` class to schedule the job with the system. The system will run the job when the
specified conditions are met.

3. **Service**: The work to be performed by the job is typically handled by a `JobService`. This service extends `JobService` and
overrides the `onStartJob()` method to execute the background work.

4. **JobFinished**: When the job is complete, you call `jobFinished()` within `onStartJob()` to notify the system. If the job fails, you
can reschedule it or report an error.

**Example: Scheduling a Job to Download Data:**

Suppose you want to schedule a job to download data from a server when the device is connected to Wi-Fi and charging.

1. **Define the JobService**:

```java
public class DataDownloadJobService extends JobService {

@Override
public boolean onStartJob(JobParameters params) {
// Perform background work (e.g., download data)
// Call jobFinished when the job is complete
jobFinished(params, false);
return true;
}

@Override
public boolean onStopJob(JobParameters params) {
// Called if the job is cancelled before completion
return false; // Reschedule the job if necessary
}
}
```

2. **Schedule the Job**:

```java
public class MainActivity extends AppCompatActivity {

private static final int JOB_ID = 123;

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

JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);

JobInfo jobInfo = new JobInfo.Builder(JOB_ID, new ComponentName(this, DataDownloadJobService.class))


.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // Require Wi-Fi
.setRequiresCharging(true) // Require charging
.build();

jobScheduler.schedule(jobInfo);
}
}
```

In this example, the `DataDownloadJobService` is a `JobService` that downloads data. We schedule the job with specific constraints:
it should run on an unmetered network (Wi-Fi) and when the device is charging.
Remember, you'll need to add the appropriate permissions in the manifest file for this to work (e.g.,
`android.permission.RECEIVE_BOOT_COMPLETED` for certain conditions).
3 public class Triangle {
private FloatBuffer vertexBuffer; // Buffer for vertex-array
private ByteBuffer indexBuffer; // Buffer for index-array
private float[] vertices = { // Vertices of the triangle
0.0f, 1.0f, 0.0f, // 0. top
-1.0f, -1.0f, 0.0f, // 1. left-bottom
1.0f, -1.0f, 0.0f // 2. right-bottom
};
private byte[] indices = { 0, 1, 2 }; // Indices to above vertices (in CCW)
// Constructor - Setup the data-array buffers
public Triangle() {
// Setup vertex-array buffer. Vertices in float. A float has 4 bytes.
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder()); // Use native byte order
vertexBuffer = vbb.asFloatBuffer(); // Convert byte buffer to float
vertexBuffer.put(vertices); // Copy data into buffer
vertexBuffer.position(0); // Rewind

// Setup index-array buffer. Indices in byte.


indexBuffer = ByteBuffer.allocateDirect(indices.length);
indexBuffer.put(indices);
indexBuffer.position(0);
}
// Render this shape
public void draw(GL10 gl) {
// Enable vertex-array and define the buffers
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
// Draw the primitives via index-array
gl.glDrawElements(GL10.GL_TRIANGLES, indices.length, GL10.GL_UNSIGNED_BYTE, indexBuffer);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
}
A thread entering a synchronized instance method acquires the lock associated with the object on which the method is called.
A thread entering a synchronized class method acquires the lock associated with the class's Class object.

synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
5 Create a notification channel

To create a notification channel, follow these steps:

1. Construct a NotificationChannel object with a unique channel ID, a user-visible name, and an importance level.
2. Optionally, specify the description that the user sees in the system settings with setDescription().
3. Register the notification channel by passing it to createNotificationChannel().
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
Manage:
// The id of the group.
String groupId = "my_group_01";
// The user-visible name of the group.
CharSequence groupName = getString(R.string.group_name);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(groupId, groupName));

Read notification channel settings

4. Get the NotificationChannel object by calling either getNotificationChannel() or getNotificationChannels().


5. Query specific channel settings such as getVibrationPattern(), getSound(), and getImportance().

Open the notification channel settings

Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);


intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
intent.putExtra(Settings.EXTRA_CHANNEL_ID, myNotificationChannel.getId());
startActivity(intent);

Delete a notification channel

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// The id of the channel.
String id = "my_channel_01";
notificationManager.deleteNotificationChannel(id);
6 In Android, manual thread creation involves creating and managing threads explicitly. This can be done by extending the `Thread`
class or implementing the `Runnable` interface. Manual thread creation provides more control over thread behavior compared to
using high-level concurrency utilities like `AsyncTask` or `Executor`.

Here's a detailed explanation of manual thread creation:

**1. Extending the Thread class:**

```java
public class MyThread extends Thread {
@Override
public void run() {
// Code to be executed in the new thread
}
}
```

**2. Implementing the Runnable interface:**

```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// Code to be executed in the new thread
}
}
```

**Creating and Starting Threads:**

```java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating threads
MyThread thread1 = new MyThread();
Thread thread2 = new Thread(new MyRunnable());

// Starting threads
thread1.start();
thread2.start();
}
}
```

**Key Points:**

1. **Thread vs. Runnable:**


- Extending `Thread` ties the code to a specific thread, while implementing `Runnable` allows the same code to be executed by
different threads.

2. **Advantages of Implementing Runnable:**


- Flexibility: Allows you to extend other classes or implement multiple interfaces.
- Separation of Concerns: Encourages clean separation between thread logic and business logic.

3. **Thread Lifecycle:**
- New: The thread is created but not yet started.
- Runnable: The thread is executing.
- Blocked: The thread is waiting for a resource or lock.
- Dead: The thread has finished execution.

4. **Thread Priority:**
- You can set the priority of a thread using `setPriority(int)` method. Priority values range from 1 to 10, where 1 is the lowest and
10 is the highest.

5. **Thread Synchronization:**
- Manual thread creation also requires explicit synchronization using techniques like `synchronized` blocks or locks to prevent race
conditions in shared data.

6. **Handling Exceptions:**
- You need to handle exceptions within the `run()` method as uncaught exceptions in threads can lead to app crashes.
7. **Thread Termination:**
- Threads can be stopped using `interrupt()` method, but it's generally better to design threads to gracefully exit when a certain
condition is met.

8. **Thread Safety:**
- Ensure that shared data accessed by multiple threads is properly synchronized to prevent data corruption.

**Note:**
Always remember that manual thread creation comes with additional responsibility. You need to be cautious about thread
synchronization, resource management, and thread safety. Additionally, excessive thread creation can lead to performance issues, so
it's important to balance the need for parallelism with system resources.
7 Describe the purpose and benefits of using AsyncTask in Android.

**Purpose of AsyncTask in Android:**

AsyncTask in Android provides an easy and efficient way to perform background operations and update the UI thread with the results. It's
particularly useful when you need to execute tasks that might take a longer time, such as network requests, database operations, or file I/O,
without freezing the UI.

**Benefits of AsyncTask:**

1. **Convenience:** AsyncTask simplifies the process of managing threads and allows developers to perform background tasks without
manually handling thread creation, execution, and synchronization.

2. **UI Responsiveness:** It helps maintain a smooth and responsive user interface by offloading time-consuming tasks to a separate
background thread, preventing the UI from freezing.

3. **Progress Updates:** AsyncTask provides methods like `onProgressUpdate()` that allow you to update the UI with progress information
during the execution of a background task.

4. **Result Handling:** It provides a way to return results from the background task to the UI thread using the `onPostExecute()` method.

5. **Automatic Threading:** AsyncTask handles the creation of a new thread for you, executing the background task on a separate thread from
the UI.

6. **Simplified Thread Synchronization:** It simplifies the process of synchronizing the UI thread with the background thread, allowing you to
perform UI updates directly in methods like `onPostExecute()`.

7. **Avoiding Network on Main Thread Exception:** AsyncTask is commonly used to execute network requests, helping to avoid the
NetworkOnMainThreadException that occurs when network operations are performed on the main UI thread.
8. **Ease of Use:** AsyncTask is a built-in class in Android, making it readily available for developers without the need for additional setup or
libraries.

Overall, AsyncTask is a valuable tool for handling background tasks in Android applications, enhancing the user experience by ensuring a
responsive UI while performing necessary operations in the background.
Compare and contrast the difference between the main (UI) thread and background threads in Android
Aspect Main (UI) Thread Background Thread(s)
- Responsible for handling the user - Used for performing long-running
interface (UI) interactions, such as tasks that should not block the UI, like
button clicks, screen updates, and network operations, file I/O, or
Responsibilities user input processing. complex computations.
- Cannot directly update the UI;
- All UI updates and interactions attempting to do so will result in an
User Interface (UI) happen on this thread. exception.
- Performing network operations
directly on the main thread is - Suitable for network operations as
discouraged, as it can lead to they can be time-consuming and
application freezes and unresponsive should not be done on the main
Network Operations UI. thread.
- Reading/writing files on the device - Appropriate for file operations as
should be kept to a minimum on the they can be blocking and should not
File I/O main thread to avoid UI freezes. interfere with UI responsiveness.
8 - Intensive computations can block - Ideal for executing CPU-intensive
the main thread, causing the UI to tasks that could potentially slow down
Complex Computations become unresponsive. the UI if done on the main thread.
- Tasks that take a significant amount
of time to complete should be avoided - Suited for tasks that require
on the main thread to maintain UI extended processing time without
Long-Running Tasks responsiveness. impacting the UI's performance.
- Cannot directly update UI
components; must use handlers or
- Can directly update UI components other mechanisms to communicate
UI Updates like TextViews, Buttons, etc. with the main thread.
- Exceptions thrown on the main - Exceptions thrown on background
thread are critical and can lead to app threads can be caught and handled
Exception Handling crashes if not properly handled. without directly affecting the UI.
- AsyncTask is typically used to - AsyncTask is commonly used to
perform background tasks while perform network requests, database
providing a way to update the UI on operations, or any long-running tasks
AsyncTask Usage the main thread. that may block the UI.
(PART C – 15 Marks )

UNIT - I
Q. No Questions
1

android architecture or Android software stack is categorized into five parts:

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

Linux kernel

It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible for device drivers,
power management, memory management, device management and resource access.
Native Libraries

On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc)
etc.

The WebKit library is responsible for browser support, SQLite is for database, FreeType for font support, Media for playing and
recording audio and video formats.

3) Android Runtime

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

4) Android Framework

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

5) Applications

On the top of android framework, there are applications. All applications such as home, contact, settings, games, browsers are using
android framework that uses android runtime and libraries. Android runtime and native libraries are using linux kernal.
2 Implement a suitable code to display “The Main Activity File:
The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a
Dalvik executable and runs your application. Following is the default code generated by the application wizard for Hello World!

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

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

@Override
protected void onStart() {
super.onStart();
showToast("onStart");
}

@Override
protected void onResume() {
super.onResume();
showToast("onResume");
}

@Override
protected void onPause() {
super.onPause();
showToast("onPause");
}

@Override
protected void onStop() {
super.onStop();
showToast("onStop");
}

@Override
protected void onDestroy() {
super.onDestroy();
showToast("onDestroy");
}

private void showToast(String message) {


Toast.makeText(this, "Hi Everybody - " + message, Toast.LENGTH_SHORT).show();
}
}Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of
many methods that are figured when an activity is loaded.
Welcome to Android Studio” messages in android studio and also use all activity life cycle methods.

The Layout File:

The activity_main.xml is a layout file available in res/layout


directory, that is referenced by your application when building its interface. Y

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />

UNIT - II
Q. No Questions
1 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.

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.
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.
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
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
Step 4: Design the activity_main.xml layout
Step 5: Modify the MainActivity file
Step 6: Modify the AndroidManifest file

2 import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity2 extends AppCompatActivity {

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

public void homeScreen(View view) {


Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

public void newsScreen(View view) {


Intent i = new Intent(getApplicationContext(), MainActivity2.class);
startActivity(i);
}
}
<editText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to GFG Home Screen"
android:textAlignment="center"
android:textSize="28sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/btn1"
android:text="Go to News Screen"
android:onClick="newsScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />

UNIT - III
Q. No Questions
Android provides a wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle
buttons, and many more.
A View is an object that draws something on the screen that the user can interact with and a ViewGroup is an object that holds other View
(and ViewGroup) objects in order to define the layout of the user interface.
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user interface for your app.
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user interface for your app.
Sr.No. UI Control & Description
TextView
1
This control is used to display text to the user.
EditText
2
EditText is a predefined subclass of TextView that includes rich editing capabilities.
AutoCompleteTextView
3 The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion suggestions
1
automatically while the user is typing.
Button
4
A push-button that can be pressed, or clicked, by the user to perform an action.

ImageButton
5 An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This shows a button
with an image (instead of text) that can be pressed or clicked by the user.

CheckBox
6 An on/off switch that can be toggled by the user. You should use check box when presenting users with a group of
selectable options that are not mutually exclusive.
ToggleButton
7
An on/off button with a light indicator.
RadioButton
8
The RadioButton has two states: either checked or unchecked.
RadioGroup
9
A RadioGroup is used to group together one or more RadioButtons.
ProgressBar
10 The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing a task in the
background.
Spinner
11
A drop-down list that allows users to select one value from a set.

TimePicker
12
The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode.

DatePicker
13
The DatePicker view enables users to select a date of the day.

Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides a wide variety of controls you can use in
your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle buttons, and many more.

View object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside
an XML tag is −

android:id="@+id/text_id"

finally create an instance of the Control object and capture it from the layout, use the following statement in java file

TextView myText = (TextView) findViewById(R.id.text_id);

MainActivity.java
package com.example.demo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


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

//--- text view---


TextView txtView = (TextView) findViewById(R.id.text_id);
}
}
Activity_main.xml:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"/>

</RelativeLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
2 Android Date Picker allows you to select the date consisting of day, month and year in your custom user interface. For this
functionality android provides DatePicker and DatePickerDialog components. The android.widget.DatePicker is the subclass of
FrameLayout class.

DatePickerDialog is a simple dialog containing DatePicker.


In order to show DatePickerDialog , you have to pass the DatePickerDialog id to showDialog(id_of_dialog) method. Its syntax is
given below −
showDialog(999);
On calling this showDialog method, another method called onCreateDialog gets automatically called. So we have to override that
method too. Its syntax is given below −
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
In the last step, you have to register the DatePickerDialog listener and override its onDateSet method. This onDateSet method
contains the updated day, month and year. Its syntax is given below −
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
Apart form date attributes, DatePicker object is also passed into this function. You can use the following methods of the DatePicker
to perform further operation.
Sr.No Method & description
getDayOfMonth()
1
This method gets the selected day of month
getMonth()
2
This method gets the selected month
getYear()
3
This method gets the selected year
setMaxDate(long maxDate)
4 This method sets the maximal date supported by this DatePicker in milliseconds since
January 1, 1970 00:00:00 in getDefault() time zone
setMinDate(long minDate)
5 This method sets the minimal date supported by this NumberPicker in milliseconds since
January 1, 1970 00:00:00 in getDefault() time zone
setSpinnersShown(boolean shown)
6
This method sets whether the spinners are shown
updateDate(int year, int month, int dayOfMonth)
7
This method updates the current date
getCalendarView()
8
This method returns calendar view
getFirstDayOfWeek()
9
This Method returns first day of the week

Android DatePicker Example


Activity_main.xml
<?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="example.javatpoint.com.datepicker.MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="102dp"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:text="" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:text="Change Date" />
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="36dp" />

</RelativeLayout>

Activity class
File: MainActivity.java
package example.javatpoint.com.datepicker;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


DatePicker picker;
Button displayDate;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textview1=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker);
displayDate=(Button)findViewById(R.id.button1);

textview1.setText("Current Date: "+getCurrentDate());

displayDate.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {

textview1.setText("Change Date: "+getCurrentDate());


}
});

public String getCurrentDate(){

StringBuilder builder=new StringBuilder();;

builder.append((picker.getMonth() + 1)+"/");//month is 0 based

builder.append(picker.getDayOfMonth()+"/");

builder.append(picker.getYear());
return builder.toString();

UNIT - IV
Q. No Questions
1 Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then
according to your response the next step is processed.

Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button.

Alert Dialog code has three methods:

● setTitle() method for displaying the Alert Dialog box Title


● setMessage() method for displaying the message
● setIcon() method is use to set the icon on Alert dialog box.

Then we add the two Button, setPositiveButton and setNegativeButton to our Alert Dialog Box as shown below.

Example:
Step By Step Implementation
Step 1: Create a New Project in Android Studio
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.

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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:gravity="center_horizontal"
android:text="Press The Back Button of Your Phone."
android:textSize="30dp"
android:textStyle="bold" />
</RelativeLayout>
Step 3: Working with the MainActivity File
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

// Declare the onBackPressed method when the back button is pressed this method will call
@Override
public void onBackPressed() {
// Create the object of AlertDialog Builder class
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

// Set the message show for the Alert time


builder.setMessage("Do you want to exit ?");

// Set Alert Title


builder.setTitle("Alert !");

// Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show
builder.setCancelable(false);

// Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface.
builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> {
// When the user click yes button then app will close
finish();
});

// Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface.
builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> {
// If user click no then dialog box is canceled.
dialog.cancel();
});

// Create the Alert dialog


AlertDialog alertDialog = builder.create();
// Show the Alert Dialog box
alertDialog.show();
}
}
Output:
2 Menus are the common user interface component in almost all the application. This interface provides a few options from which the
user can select an option.

Way to create menu directory and menu resource file:

To create the menu directory just right-click on res folder and navigate to res->New->Android Resource Directory. Give resource
directory name as menu and resource type also menu. one directory will be created under res folder.

To create xml resource file simply right-click on menu folder and navigate to New->Menu Resource File. Give name of file as
menu_example. One menu_example.xml file will be created under menu folder.

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


<menu xmlns:android="http:// schemas.android.com/apk/res/android">
<item android:id="@+id/mail"
android:icon="@drawable/ic_mail"
android:title="@string/mail" />
<item android:id="@+id/upload"
android:icon="@drawable/ic_upload"
android:title="@string/upload"
android:showAsAction="ifRoom" />
<item android:id="@+id/share"
android:icon="@drawable/ic_share"
android:title="@string/share" />
</menu>
There are 3 types of menu types available in Android:
1. Options menu and app bar
2. Context menu and contextual action mode
3. Popup menu

Android Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the
searching application. Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is
useful for elements that affect the selected content or context frame. Android Popup Menu displays a list of items in a vertical list which
presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content.

UNIT - V
Q. No Questions
1 An example of an Android application that demonstrates creating a thread, EditText, and TextView. When the user enters text in the
EditText, it waits for 5000 milliseconds (5 seconds) and then updates the TextView with the entered text.

**Step 1:** Create a new Android project with an Empty Activity.

**Step 2:** In your activity's layout XML file (e.g., `activity_main.xml`), add an EditText and a TextView:

```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will appear here"/>

</LinearLayout>
```

**Step 3:** In your activity's Java file (e.g., `MainActivity.java`), implement the logic:

```java
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

private EditText editText;


private TextView textView;
private Button button;

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

editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inputText = editText.getText().toString();
if (!inputText.isEmpty()) {
updateTextViewAfterDelay(inputText);
}
}
});
}

private void updateTextViewAfterDelay(final String text) {


// Create a new thread
new Thread(new Runnable() {
@Override
public void run() {
try {
// Wait for 5000 milliseconds (5 seconds)
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the TextView on the main thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
textView.setText(text);
}
});
}
}).start();
}
}
```

**Explanation:**
1. We have an EditText to input text, a Button to trigger the process, and a TextView to display the result.
2. When the button is clicked, the `updateTextViewAfterDelay()` method is called.
3. This method creates a new thread that sleeps for 5 seconds and then updates the TextView with the entered text.
4. We use a Handler to ensure that the update happens on the main (UI) thread.

**Note:**
In a real application, you should handle exceptions, potential memory leaks, and consider using more advanced concurrency
mechanisms (like `AsyncTask` or `Executor`) depending on the complexity of the task.
2 Notification Channels were introduced in Android 8.0 (API level 26) to provide users with more control over the types of
notifications they receive from an app. They allow you to group notifications by category and define user-specific preferences for
each category. Here's how you can create and manage Notification Channels in Android:

**Step 1: Define Notification Channels**

In your Android code, define the notification channels. This is typically done in a place like your `Application` class, or wherever
you handle notifications.

```java
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;

public class MyApplication extends Application {

@Override
public void onCreate() {
super.onCreate();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {


NotificationChannel channel1 = new NotificationChannel(
"channel_1_id",
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");

NotificationChannel channel2 = new NotificationChannel(


"channel_2_id",
"Channel 2",
NotificationManager.IMPORTANCE_DEFAULT
);
channel2.setDescription("This is Channel 2");

NotificationManager notificationManager = getSystemService(NotificationManager.class);


notificationManager.createNotificationChannels(Arrays.asList(channel1, channel2));
}
}
}
```
In this example, we define two notification channels: "Channel 1" and "Channel 2". Channel 1 is set to high importance, while
Channel 2 is set to default importance.

**Step 2: Use Notification Channels when Sending Notifications**

When sending notifications in your app, make sure to specify the channel ID. This ensures that the notification gets associated with
the correct channel.

```java
public void sendNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_1_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Notification Title")
.setContentText("Notification Content")
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, builder.build());
}
```

In this example, the notification is associated with "channel_1_id", which corresponds to "Channel 1" that we defined earlier.

**Step 3: Allow Users to Customize Channels (Optional)**

You can also allow users to customize channel settings from within your app. This can be done through an activity where users can
modify notification preferences.

**Note:**
- Channels should be defined once, typically at app startup.
- You can update channel properties, but users must be informed of the changes.

Remember to handle cases where the device is running an Android version prior to Oreo (API level 26), where notification channels
are not supported. You can use pre-Oreo notification mechanisms in such cases.

By using notification channels, you provide users with more control over which types of notifications they want to receive, leading to
a better user experience.

You might also like