Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

PARUL INSTITUTE OF ENGINEERING & TECHNOLOGY

(DIPLOMA STUDIES)
PARUL UNIVERSITY, POST LIMDA, WAGHODIA,
GUJARAT 391760

DEPARTMENT OF COMPUTER ENGINEERING


(1ST SHIFT)

QUESTION BANK
ENROLLMENT NO.
NAME
Semester 6th
Division
SUBJECT NAME ANDROID PROGRAMMING
SUBJECT CODE 03606352
ACADEMIC YEAR 2023-24
Android Programming (03606352) PIET-DS

Chapter - 1 Introduction To Android And Architecture Framework


1. Give full form of 1. OHA 2. AVD.(2 marks)

Ans: OHA : Open Handset Aliance.


AVD : Android Virtual Devices.

2. What is an OHA ? (2 marks)


Ans: The Open Handset Alliance (abbreviated as OHA) is an organization of total 84
companies that works to develop open standards for mobile devices. It is led by
Google. To promote a unified Android platform, members of the OHA are prohibited
from producing devices based off of incompatible forks of Android.

3. List out all android versions.(2 marks)

Ans:
Version Name of Version
Android 1.0 Alpha,
Android 1.1 Beta,
Android 1.5 Cupcake,
Android 1.6 Donut,
Android 2.0 Eclair,
Android 2.2 Froyo,
Android 2.3 Gingerbread,
Android 3.0 Honeycomb,
Android 4.0 Ice Cream Sandwhich,
Android 4.1 Jellybean,
Android 4.4 Kitkat,
Android 5.0 Lolipop,
Android 6.0 Marshmallow,
Android 7.0 Nougat,
Android 8.0 Oreo,
Android 9.0 Pie,
Android 10.0 Q,
Android 11.0 R,
Android 12.0 Snow Corn,
Android 13.0 Tiramishu

Prepared By: Devansh Parikh Page No. 2


Android Programming (03606352) PIET-DS

4. Draw hierarchy architecture.(2 marks)

Ans:

The hierarchy pattern is a standard site structure with an index page and a series of sub-
pages. If you are designing a responsive site you may be restricted to this, however
introducing additional patterns could allow you to tailor the experience for mobile. Luke
Wroblewski’s Mobile First approach helps us focus on the important stuff first: features
and user journeys that will help us create great user experiences.

5. Draw a figure of hub and spoke.(2 marks)

Ans:

A hub and spoke pattern gives you a central index from which users will navigate out.
It’s the default pattern on Apple’s iPhone. Users can’t navigate between spokes but must
return to the hub, instead. This has historically been used on desktop where a workflow is
restricted (generally due to technical restrictions such as a form or purchasing process)
however this is becoming more prevalent within the mobile landscape due to users being
focused on one task, as well as the form factor of the device, making a global navigation
more difficult to use.

Prepared By: Devansh Parikh Page No. 3


Android Programming (03606352) PIET-DS

6. Explain types of mobile phone generation.(3 marks)

Ans:

First Generation (1G)

First generation mobile networks were reliant upon analogue radio systems which
meant that users could only make phone calls, they couldn’t send or receive text
messages. The 1G network was first introduced in Japan in 1979 before it was
rolled out in other countries such as the USA in 1980. In order to make it work,
cell towers were built around the country which meant that signal coverage could
be obtained from greater distances. However, the network was unreliable and had
some security issues. For instance, cell coverage would often drop, it would
experience interference by other radio signals and due to a lack of encryption, it
could easily be hacked. This means that with a few tools, conversations could be
heard and recorded.

Second Generation (2G)

The 1G network was not perfect, but it remained until remained until 1991 when
it was replaced with 2G. This new mobile network ran on digital signal, not
analogue, which vastly improved its security but also its capacity. On 2G, users
could send SMS and MMS messages (although slowly and often without success)
and when GPRS was introduced in 1997, users could receive and send emails on
the move.

Third Generation (3G)


Third generation mobile networks are still in use today, but normally when the
superior 4G signal fails. 3G revolutionised mobile connectivity and the
capabilities of cell-phones. In comparison to 2G, 3G was much faster and could
transmit greater amounts of data. This means that users could video call, share
files, surf the internet, watch TV online and play online games on their mobiles
for the first time. Under 3G, cell-phones where no longer just about calling and
texting, they were the hub of social connectivity.

Prepared By: Devansh Parikh Page No. 4


Android Programming (03606352) PIET-DS

Fourth Generation (4G)


The introduction of 4G went one step further than the revolutionary 3G. It’s five
times faster than the 3G network – and can in theory provide speeds of up to
100Mbps. All mobile models released from 2013 onwards should support this
network, which can offer connectivity for tablets and laptops as well as
Smartphone’s. Under 4G, users can experience better latency (less buffering),
higher voice quality, easy access to instant messaging services and social media,
quality streaming and make faster downloads.

Fifth Generation (5G)


The network has arrived and has been largely welcomed by the mobile industry.
The network has changed more than just our mobile use, and affects how we
connect our devices to the internet. The improved speed and the massive network
capacity has developed new IOT trends, such as smart cities, e-healthcare, IOT in
the home or office and connected cars. 5G can theoretically have download speed
20x faster than 4G, as well as boasting a very low latency in comparison to its
predecessor. This means that time-delay for online gaming, video calls, and
critical mission applications will be significantly lower. With almost a decade of
5G development left, the technology’s full potential is yet to come. The 5G
network will revolutionize the way people live and work across the world, so
expect to see exciting changes in the coming years.

Prepared By: Devansh Parikh Page No. 5


Android Programming (03606352) PIET-DS

7. Types of mobile applications.(3 marks)

Ans: Types of mobile application can be divided into three categories as follows:

1. Native App: native app.


2. Web App: web application.
3. Hybrid App: hybrid application.

1. Native Apps
Anything natural to our environment is known as native. Similar is the case of a
mobile application. If an app is natural to the mobile then it is considered as a
Native app, which means, apps that are built targeting a particular mobile which
means a particular Operating System (like Android, Windows, macOS, etc.) of
the mobile.
These apps work only on those devices for which they are built.
If an app is developed for Apple mobiles i.e. macOS, then that app will not work
on any other device which is having an operating system other than macOS.
If an app is developed for Android OS then it will work only on devices having
Android OS, and not on any other device.
The benefits of native apps are that it easily communicates with the device on
which it is running, It easily communicates with device hardware like Camera,
Speakers, Graphics Engine, Buttons, Touch, Location Sensors and
Accelerometers, etc.
The page rendering i.e. User Interface rendering goes on without any hanging
issues or stucking up.
The flow of layout is flawless and easy to use.
These apps are more user-friendly, easier to operate, and can easily tolerate a load
of fast user activity on them.
These apps can react at the same speed with what the user operates them.
These apps in terms of interactivity supersede all other types of apps.

Advantages of Native Application:


The performances of these apps are very high these apps very fast compared to
any other apps. We have easy access to all the features and APIs.
The community is widespread so all your doubts and errors can be discussed and
solved easily. Updates are available on the same day.

Disadvantages of Native Application:


The development speed is too slow as we have to code it again for different OS.
And this category doesn’t support open source.

Prepared By: Devansh Parikh Page No. 6


Android Programming (03606352) PIET-DS

2. Web Apps
These are apps built using web technologies and they serve web pages using the
existing web browsers on devices.
These are built using HTML, Javascript, jQuery, CSS, etc.
These are not exactly mobile apps but a website in its responsive form in the form
of a mobile application, which means, a web-based application which works on
any mobile device or operating system because it is delivered using web browsers
inside a mobile device.
They are a responsive form of websites so they automatically change their
appearance according to the device and space available for the rendering of
content.
A category of Web apps is Progressive Web Apps (PWA) which are native apps
running inside a browser. Plugins, third-party plugins or APIs cannot be used in
these kinds of apps

Advantages web Application:


The main advantage of this process is that its development speed is fast the same
code base is used for IOS, Android, web applications.
The web development team can be repurposed to develop the mobile application.
No installation required.

Disadvantages web Application:


The major disadvantage is that PWA don’t have access to all the feature and so
the user experience is not that good IOS does not support all the features of PWA
The UI for development is bespoke i.e. the buttons, edit texts need to be
programmed which was not necessary for the 1st party native Apps.
The community is not that wide spread.
No extra room for business model i.e. it is still a challenge to develop a revenue
model or advertising opportunities for PWAs. At the moment, there are fewer
options than among native apps to subscribe to.

3. Hybrid Apps
The term hybrid means “mixture”. Thus, a hybrid app refers to applications that
are native as well as web-based. Hybrid apps are an integration of Native and
Web apps. These apps use web technologies and native APIs, both.
These apps can use most of the device features like native apps. Similar to web
apps, hybrid apps are made of web technologies like HTML, CSS, Javascript,
jquery, AJAX, JSON, etc.
These also use web browsers to display content and user interfaces but they use
the native elements as well as web-based elements for development.

Prepared By: Devansh Parikh Page No. 7


Android Programming (03606352) PIET-DS

The code of these apps is just needed to be tweaked to make it compatible across
multiple platforms.

Advantages of Hybrid Apps:


The apps’ development speed is very high as they use the same code base for both
Android and iOS. The apps’ maintenance cost is low as the errors and updates as
to be countered only once.

Disadvantages of Hybrid Apps:


Slow Code Performance With Limited Tool Availability.
Limited User Experience i.e. these apps does not have access to Native only
features.

8. Explain the various types of android application.(3 marks)


Ans: There are following Types of android applications are available in app market.

1. Lifestyle Mobile Apps


Fitness, Dating, Food, Music, Travel, Spotify, Trip advisor, Uber

2. Social Media Mobile Apps:


Facebook, Instagram, Pinterest, Snapchat, Whatsapp, Messenger.

3. Utility Mobile Apps


Reminders, Calculator, Flashlight, Weather.

4. Games/Entertainment Mobile Apps


Angry Birds, Clash of Clans, Subway Surfer, PUBG, BGMI, Free Fire.

5. Productivity Mobile Apps


Docs, Sheets, Wallet/Pay

6. News/Information Outlets Mobile Apps


Buzzfeed, Smart news, Google News & Weather, Feedly, Flipboard,
Yahoo News Digest, Reddit, LinkedIn Pulse

9. Explain use of android debug bridge.(3 marks)

Ans: Android Debug Bridge (adb) is a versatile command-line tool that lets you communicate
with a device. The ADB is typical, used to communicate with a smartphone, tablet,
smartwatch, set-top box, or any other device that can run the Android operating system.
We can do things on an Android device that may not be suitable for everyday use, like,

Prepared By: Devansh Parikh Page No. 8


Android Programming (03606352) PIET-DS

install apps outside of the Play Store, debug apps, access hidden features, and bring up a
UNIX shell, etc. For security reasons, Developer Options need to be unlocked and you
need to have USB Debugging Mode enabled as well. Not only that, but you also need to
authorize USB Debugging access to the specific PC that you’re connected to with a USB
cable. It is a client-server program that includes three components.

A client, which sends commands. The client runs on your development machine. You can
invoke a client from a command-line terminal by issuing an adb command.

A daemon, which runs commands on a device. The daemon runs as a background process
on each device.

A server, which manages communication between the client and the daemon. The server
runs as a background process on your development machine.

10. Explain Android Permission model.(3 marks)

Ans: App permissions help support user privacy by protecting access to the following:
Restricted data, such as system state and users' contact information Restricted actions,
such as connecting to a paired device and recording audio

Types of Permissions

Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is
requested at the installation time at the Google Play Store.
If the user Accepts the permissions, the app is installed. Else the app installation is
canceled.

Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is requested
at the run time during the running of the app.
If the user Accepts the permissions, then that feature of the app can be used. Else to use
the feature, the app requests permission again.
So, now the permissions are requested at runtime. In this article, we will discuss how to
request permissions in an Android Application at run time.

11. Explain Android Manifest file.(4 marks)

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

Prepared By: Devansh Parikh Page No. 9


Android Programming (03606352) PIET-DS

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.

<manifest xmlns:android=http://schemas.android.com/apk/res/android
package="com.javatpoint.hello"
android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity" android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

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.

Prepared By: Devansh Parikh Page No. 10


Android Programming (03606352) PIET-DS

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

12. Draw and explain android Application Framework.(3 marks)

Ans:

Prepared By: Devansh Parikh Page No. 11


Android Programming (03606352) PIET-DS

Android software stack (also known as android architecture) includes


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

Linux kernel
At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This
provides a level of abstraction between the device hardware and it contains all the
essential hardware drivers like camera, keypad, display etc. Also, the kernel handles all
the things that Linux is really good at such as networking and a vast array of device
drivers, which take the pain out of interfacing to peripheral hardware.

Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser
engine WebKit, well known library libc, SQLite database which is a useful repository for
storage and sharing of application data, libraries to play and record audio and video, SSL
libraries responsible for Internet security etc.

Android Libraries
This category encompasses those Java-based libraries that are specific to Android
development. Examples of libraries in this category include the application framework
libraries in addition to those that facilitate user interface building, graphics drawing and
database access. A summary of some key core Android libraries available to the Android
developer is as follows –

android.app − Provides access to the application model and is the cornerstone of all
Android applications.

android.content − Facilitates content access, publishing and messaging between


applications and application components.

android.database − Used to access data published by content providers and includes


SQLite database management classes.

android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.

android.os − Provides applications with access to standard operating system services


including messages, system services and inter-process communication.

android.text − Used to render and manipulate text on a device display.

android.view − The fundamental building blocks of application user interfaces.

Prepared By: Devansh Parikh Page No. 12


Android Programming (03606352) PIET-DS

android.widget − A rich collection of pre-built user interface components such as


buttons, labels, list views, layout managers, radio buttons etc.

android.webkit − A set of classes intended to allow web-browsing capabilities to be


built into applications.

Having covered the Java-based core libraries in the Android runtime, it is now time to
turn our attention to the C/C++ based libraries contained in this layer of the Android
software stack.

Android Runtime
This is the third section of the architecture and available on the second layer from the
bottom. This section provides a key component called Dalvik Virtual Machine which is a
kind of Java Virtual Machine specially designed and optimized for Android.

The Dalvik VM makes use of Linux core features like memory management and multi-
threading, which is intrinsic in the Java language. The Dalvik VM

enables every Android application to run in its own process, with its own instance of the
Dalvik virtual machine.

The Android runtime also provides a set of core libraries which enable Android
application developers to write Android applications using standard Java programming
language.

Application Framework
The Application Framework layer provides many higher-level services to applications in
the form of Java classes. Application developers are allowed to make use of these
services in their applications.

The Android framework includes the following key services −

Activity Manager − Controls all aspects of the application lifecycle and activity stack.

Content Providers − Allows applications to publish and share data with other
applications.

Resource Manager − Provides access to non-code embedded resources such as strings,


color settings and user interface layouts.

Notifications Manager − Allows applications to display alerts and notifications to the


user.

Prepared By: Devansh Parikh Page No. 13


Android Programming (03606352) PIET-DS

View System − An extensible set of views used to create application user interfaces.

Applications
You will find all the Android application at the top layer. You will write your application
to be installed on this layer only. Examples of such applications are Contacts Books,
Browser, Games etc.

Prepared By: Devansh Parikh Page No. 14


Android Programming (03606352) PIET-DS

Chapter – 2 Android Activities

1. Write down steps for creating first android applications.(2 marks)

Ans: Step 1 : Open Android Studio


Step 2 : Click on “ + “ Icon for New Project.
Step 3 : Assign Project Name.
Step 4 : Then Click on Finish Button.
Step 5 : Now your Android Application Project is created after the Gradle Build
Successfully.
Step 6 : Click on Run button for “Launch Activity”.

2. Explain anatomy of android application. (2 marks)

Ans: The anatomy for the android app development.

The various folders and their files are as follows:

1. src — Contains the .java source files for your project. In this example, there is one
file, HelloworldActivity.java. The HelloworldActivity.java file is the source file
for your activity. You will write the code for your application in this file.

Prepared By: Devansh Parikh Page No. 15


Android Programming (03606352) PIET-DS

2. Android 2.3 library — This item contains one file, android.jar, which contains all
the class libraries needed for an Android application.

3. gen — Contains the R.java file, a compiler-generated file that references all the
resources found in your project. You should not modify this file.

4. assets — This folder contains all the assets used by your application, such as
HTML, text files, databases, etc.

5. res — This folder contains all the resources used in your application. It also
contains a few other subfolders: drawable-<resolution>, layout, and values.

6. AndroidManifest.xml — This is the manifest file for your Android application.


Here you specify the permissions needed by your application, as well as other
features (such as intent-filters, receivers, etc.).

3. List out all the android components. (2 marks)

Ans: There are Seven Android Components.


1. Activities
2. Services
3. Content Providers
4. Broadcast Receivers
5. Intents
6. Widgets
7. Notifications.

1) Activity
Activity is the most used of the four components. It is always used in an app.
Activity is basically a screen in an application. There may be multiple activities in
an app as an app may contain multiple screens. Each activity consists of various
UI components like Views, buttons, layouts, etc. The Activity consists of an
Activity class where all the work is done.

2) Service
Services are the processes that execute in the background but not displayed on the
screen. These are used when you want programs to run but not necessarily display
it on the UI screen. For example, playing music in an app, and changing the music
automatically, doesn’t need to be displayed on the screen and just needs to keep
running in the background. Services can be started and managed from activities,
intent receivers, etc and are given higher priority by android runtime than many
other processes.

Prepared By: Devansh Parikh Page No. 16


Android Programming (03606352) PIET-DS

3) Intents
Intent basically provides a developer with the option to move from one screen to
another screen. It gives the option to connect one screen to another. It consists of
the operation to be performed and the activity class name has to be declared to
which the current activity has to be connected.

4) Intent Receiver
Intent Receiver is used when a function has to be executed in response to an
event. This doesn’t display UI but may alert the user with a notification.

5) Content Provider
Content providers deal with the sharing of data within or between apps. Apps can
store data in shared preferences, SQLite databases, files, etc. An application can
allow other apps to access their data by defining a Content Provider. The data’s
access is provided by a Universe Resource Identifier (URI) defined by the
Content Provider.

6) Widgets and Notifications


A component of design and customization are widgets. Widget for Information:
The only information that will be displayed to the user by these Android widgets
is dynamic and important information. This kind of widget, for instance, is the
time and weather information on your home screen.

Widgets for Collections:


These Android widgets move from top to bottom.a collection of
information of the same kind that allows the user to open any of them to
view all of the details. Your email app, for instance, will show you all of
the messages in your inbox and let you open any one of them.

Control Panel Widgets:


It displays the features that are used the most frequently and that the user
might want to control from the home screen. A control widget, for
instance, allows you to pause, play, stop, go to the previous track, and
move on to the next track in a video app.

Hybrid Widgets: These Android widgets combine all three of the previous
features.

Prepared By: Devansh Parikh Page No. 17


Android Programming (03606352) PIET-DS

4. Explain any two methods of activity lifecycle.(2 marks)


Ans:

Lifecycle Description
Method
onCreate() This method called when the activity is first
created
onStart() This method is called when the activity
become visible to the user
onResume() This is called when the user start interacting
with the application
onPause() The paused activity does not received user input and
cannot execute any code and called when the current
activity is being paused and
the previous activity is being resumed
onStop() This callback Is called when the activity is no
longer visible
onDestroy() This callback is called before the activity is
destroy by the system.

5. Write down steps for deploying android app in physical mobile devices.(3 marks)

Ans: How to Connect Your Device


• Before starting, Enable debugging mode on Android device. Open the
'Applications' folder and select 'Development.' On the subsequent screen, ensure
the 'USB Debugging' checkbox is ticked.
• If windows develop application then it is need to install the USB driver for your
device. If Google device is used (such as the Nexus line) then download the
necessary drivers through the Android SDK Manager. Open the 'Windows' menu
and select 'Android SDK Manager' to get started. The Android SDK Manager will
open, listing all of the installed packages, along with available updates and
additional packages that can be installed. Locate the 'Google USB Driver' package
under the 'Extras' folder.
• If it isn't installed, tick the checkbox and click the 'Install Package' button. This can
take some time to download, so be prepared to wait a few minutes
• Connect the device to computer using the appropriate USB cable.
• Inside Eclipse installation, open the 'Run' menu and select 'Run Configurations’.
• Select the Android project to run/debug and open the 'Target' tab.
• Ensure 'Always prompt to pick device' is selected, click 'Apply' and 'Run.'

Prepared By: Devansh Parikh Page No. 18


Android Programming (03606352) PIET-DS

• The 'Android Device Chooser' will open. If device connected successfully, it will
be listed under 'Choose a running Android device.' Select device and click 'OK.'

Steps For Emulator:

• Connect android phone with the pc on which running project. eclipse/ map
• Let it install smartphone, go all the necessary drivers. When done, open your
seetings then goto : Settings > Applications > Development > USB debugging and
enable it on by clicking on the check button at the right side.
• Also, enable Settings > Unknown resources
• Come back to eclipse on pc. Right click on the project/application, Run As > Run
configurations... >Choose Device>Target Select device Run.
• Click on the Target tab from top. By default it is on the first tab Android
• Choose the second radio button which says Launch on all compatible
Devices/AVDs. Then click Apply at the bottom and afterwards, click Run.
• It will automatically install application's .apk file into Smartphone and make it run
over it., just like on emulator.

6. Draw a diagram of Activity lifecycle and explain it.(3 marks)


Ans:

Fig. Activity Life cycle of Android

Prepared By: Devansh Parikh Page No. 19


Android Programming (03606352) PIET-DS

Life Cycle Methods and Callbacks:


1. onCreate()
2. onStart()
3. onResume()
4. onPause()
5. onStop()
6. onRestart()
7. onDestroy()

onCreate()
The activity is created in this state.The OS calls the onCreate() method whenever
an activity gains memory.

onStart()
This callback is called by the system whenever the activity enters the Started
state.As the app prepares for the activity to enter the foreground and become
interactive, the onStart() call makes the activity visible to the user. This method,
for instance, is where the app initializes the UI- maintaining code.

onResume()
The system calls the onResume() callback when the activity enters the Resumed
state and enters the foreground. In this state, the app communicates with the user.
Until something draws attention away from the app, the app stays in this state.
Receiving a phone call, navigating to another activity, or turning off the device
screen are all examples of such events.

onPause()
Although it does not always imply that the activity is being destroyed, the system
refers to this method as the initial sign that the user is leaving your activity; It tells
the user that the activity is no longer in the foreground, though it might still be
visible if the user is in multi-window mode.

onStop()
When an activity is hidden from the user, it is referred to as stopped. Any activity
is halted in the event that it is replaced by another activity. For instance, suppose a
user was on screen1, clicked a button, and then moved on to screen2. Activity that
is displaying content for screen 1 will be stopped in this case. When the user
presses the back navigation button, all activities are halted before they can
continue. As a result, the Activity will be in the stopped state when it is replaced
by other activities that the user has initiated or switched. As a result, the
application will cease to provide the user with any useful information.

onRestart()
After the stop state, the activity is called in the restart state.Therefore, the
onRestart() function of the activity is called when the user returns to the screen or
resumes the activity that was stopped.To put it another way, onRestart() is never

Prepared By: Devansh Parikh Page No. 20


Android Programming (03606352) PIET-DS

called when the operating system starts the activity for the first time.It is only
called when activity resumes after being stopped.

onDestroy()
When it is not in the background, any activity is referred to as being
destroyed.Activity can be destroyed in a variety of circumstances. First, if the user
presses the back navigation button, the activity will end after it completes the
pause and stop lifecycle.

7. Create demo of activity life cycle.(4 marks)

Ans: Code: activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Code :MainActivity.java

package com.example.myapplication; import android.app.Activity;


import android.os.Bundle; import android.util.Log;
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate INvoked");
}
protected void onStart()
{
super.onStart();

Prepared By: Devansh Parikh Page No. 21


Android Programming (03606352) PIET-DS

Log.d("lifecycle","onStart invoked");
}
protected void onResume()
{
super.onResume();
Log.d("lifecycle","onResume invoked");
}
protected void onPause()
{
super.onPause();
Log.d("lifecycle","onPause invoked");
}
protected void onStop()
{
super.onStop();
Log.d("lifecycle","onStop invoked");
}
protected void onRestart()
{
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
protected void onDestroy()
{
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

8. What is Intent? Explain types of Intent in android with example.(4 marks)

Ans: An intent is to perform an action on the screen. It is mostly used to start activity, send
broadcast receiver, start services and send message between two activities. There are two
intents available in android as Implicit Intents and Explicit Intents. Here is a sample
example to start new activity with old activity.

Intent is to perform an action. It is mostly used to start activity, send broadcast receiver,
start services and send message between two activities. There are two intents available in
android as Implicit Intents and Explicit Intents.

Prepared By: Devansh Parikh Page No. 22


Android Programming (03606352) PIET-DS

Explicit Intent − It going to connect the internal world of an application such as start
activity or send data between two activities. To start new activity we have to create Intent
object and pass source activity and destination activity as shown below −

For Example: Explicit Intent


Intent send = new Intent(MainActivity.this, SecondActivity.class);
startActivity(send);

Note: And we should declare about second activity in Manifest.xml file or else it going to
show run time exception. sample declaration is as shown below.
<activity android:name = ".SecondActivity"></activity>

Implicit Intents − It going to connect with out side application such as call, mail,
phone,see any website ..etc. In implicit intent we have to pass an action using setAction()
as shown below example.

For Example: Implicit Intent


Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("www.paruluniversity.ac.in"));
startActivity(i);

Prepared By: Devansh Parikh Page No. 23


Android Programming (03606352) PIET-DS

Chapter – 3 Android GUI Design Concepts And UI Programming


1. Explain Broadcast receiver. (2 marks)

Ans: Broadcast Receivers simply respond to broadcast messages from other applications or
from the system. For example, applications can also initiate broadcasts to let other
applications know that some data has been downloaded to the device and is available for
them to use, so this is broadcast receiver who will intercept this communication and will
initiate appropriate action.

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each


message is broadcaster as an Intent object.

For Example :

public class MyReceiver extends BroadcastReceiver {


public void onReceive (context,intent){}
}

2. Explain the use of Broadcast receiver in android.(3 marks)


Ans: Broadcast in android is the system-wide events that can occur when the device starts,
when a message is received on the device or when incoming calls are received, or when a
device goes to airplane mode, etc. Broadcast Receivers are used to respond to these
system-wide events. Broadcast Receivers allow us to register for the system and
application events, and

when that event happens, then the register receivers get notified. There are mainly two
types of Broadcast Receivers:

Static Broadcast Receivers: These types of Receivers are declared in the manifest file and
works even if the app is closed.
Dynamic Broadcast Receivers: These types of receivers work only if the app is active or
minimized.

Intent Description Of Event


Indicates low battery condition on
android.intent.action.BATTERY_LOW :
the device.
This is broadcast once after the
android.intent.action.BOOT_COMPLETED
system has finished booting
To perform a call to someone
android.intent.action.CALL
specified by the data
android.intent.action.DATE_CHANGED Indicates that the date has changed
Indicates that the device has been a
android.intent.action.REBOOT
reboot

Prepared By: Devansh Parikh Page No. 24


Android Programming (03606352) PIET-DS

android.net.conn.CONNECTIVITY_CHANGE The mobile network or


wifi connection is changed(or reset)
android.intent.ACTION_AIRPLANE_MODE_ This indicates that airplane mode
CHANGED has been switched on or off.

The two main things that we have to do in order to use the broadcast receiver in our
application are:

Creating the Broadcast Receiver:


class AirplaneModeChangeReceiver:BroadcastReceiver() { override fun
onReceive(context: Context?, intent: Intent?) {
// logic of the code needs to be written here
}
}
Registering a BroadcastReceiver:

IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also
{
// receiver is the broadcast receiver that we have registered
// and it is the intent filter that we have created registerReceiver(receiver,it)
}

3. Explain Drawable resources. (2 marks)


Ans: A Drawable resource is a general concept for a graphic which can be drawn.The simplest case is
a graphical file (bitmap), which would be represented in Android via a BitmapDrawable class.
Every Drawable is stored as individual files in one of the res/drawable folders.

4. Write down all dimensions name.(2 marks)


Ans: Dimensions are most commonly referenced within style and layout resources. They’re
useful for creating layout constants, such as borders and font heights. To specify a
dimension resource, use the <dimen> tag, specifying the dimension value, followed by
an identifier describing the scale of your dimension:

1. px(screen pixels)
2. in(physical inches)
3. pt(physical points)
4. mm(physical millimeters)
5. dp(density-independent pixels)
6. sp(scale-independent pixels)

5. Explain Edittext with example.(2 marks)


Ans: EditText is a user interface element for entering and modifying text. When you define an
edit text widget, you must specify the R.styleable.TextView_inputType attribute. For
example, for plain text input set inputType to "text":

Prepared By: Devansh Parikh Page No. 25


Android Programming (03606352) PIET-DS

For Example:

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle=”bold”
android:textSize=”20dp”
android:hint=“Enter Your Name" />

6. List out different layout in android and explain any 2 out of them.(3 marks)
Ans: Types of Android Layout

1. Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide


child View elements one by one either in a particular direction either horizontally
or vertically based on the orientation property.
2. Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify
the position of child View elements relative to each other like (A to the right of B)
or relative to the parent (fix to the top of the parent).
3. Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to
specify the position of layout constraints for every child View relative to other
views present. A ConstraintLayout is similar to a RelativeLayout, but having more
power.
4. Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the
position of View elements it contains on the top of each other to display only a
single View inside the FrameLayout.
5. Android Table Layout: TableLayout is a ViewGroup subclass, used to display the
child View elements in rows and columns.
6. Android Web View: WebView is a browser that is used to display the web pages
in our activity layout.
7. Android ListView: ListView is a ViewGroup, used to display scrollable lists of
items in a single column.
8. Android Grid View: GridView is a ViewGroup that is used to display a scrollable
list of items in a grid view of rows and columns.

7. Explain toggle button in android.(3 marks)

Ans: Android Toggle Button can be used to display checked/unchecked (On/Off) state on the
button. It is beneficial if user have to change the setting between two states. It can be
used to On/Off Sound, Wifi, Bluetooth etc.

Since Android 4.0, there is another type of toggle button called switch that provides slider
control.

Prepared By: Devansh Parikh Page No. 26


Android Programming (03606352) PIET-DS

Android ToggleButton and Switch both are the subclasses of


CompoundButton class.

XML Attribute Description


android:disabledAlpha The alpha to apply to the indicator when
disabled.
android:textOff The text for the button when it is not
checked.
android:textOn The text for the button when it is
checked.

Methods of ToggleButton class

Method Description
CharSequence getTextOff() Returns the text when button is not in the
checked state.
CharSequence getTextOn() Returns the text for when button is in the
checked state.
void setChecked(boolean Changes the checked state of this button.
checked)

For Example:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ToggleButton
android:id="@+id/toggleButton" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="8dp"
android:layout_marginTop="80dp" android:text="ToggleButton" android:textOff="Off"
android:textOn="On"
app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ToggleButton

Prepared By: Devansh Parikh Page No. 27


Android Programming (03606352) PIET-DS

android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:layout_marginTop="80dp"
android:text="ToggleButton"
android:textOff="Off"
android:textOn="On"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="144dp"
android:layout_marginLeft="148dp"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

File: MainActivity.java
package example.javatpoint.com.togglebutton;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;


import android.view.View; import android.widget.Button; import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity { private ToggleButton toggleButton1,


toggleButton2; private Button buttonSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button);
//Performing action on button click buttonSubmit.setOnClickListener(new
View.OnClickListener(){

Prepared By: Devansh Parikh Page No. 28


Android Programming (03606352) PIET-DS

@Override
public void onClick(View view) { StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggleButton1.getText());
result.append("\nToggleButton2:
").append(toggleButton2.getText());
//Displaying the message in toast Toast.makeText(getApplicationContext(),
result.toString(),Toast.LENGTH_LONG).show();
}
});
}
}

8. What is spinner? Explain with example.(4 marks)

Ans: Android Spinner is like the combox box of AWT or Swing. It can be used to display the
multiple options to the user in which only one item can be selected by the user.

Android spinner is like the drop down menu with multiple values from which the end
user can select only one value.

Android spinner is associated with AdapterView. So you need to use one of the adapter
classes with spinner.

Android Spinner class is the subclass of As a Spinner class.

File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

Prepared By: Devansh Parikh Page No. 29


Android Programming (03606352) PIET-DS

android:layout_height="match_parent"
tools:context="example.javatpoint.com.spinner.MainActivity">

<Spinner android:id="@+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.498"
/>

</android.support.constraint.ConstraintLayout>

File: MainActivity.java
package example.javatpoint.com.spinner;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;


import android.view.View;
import android.widget.AdapterView; import android.widget.ArrayAdapter; import
android.widget.Spinner; import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener {
String[] country = { "India", "USA", "China", "Japan", "Other"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying
OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the country list ArrayAdapter aa = new
ArrayAdapter(this,android.R.layout.simple_spinner_item,country);

aa.setDropDownViewResource(android.R.layout.simple_spinner_dro pdown_item);
//Setting the ArrayAdapter data on the Spinner spin.setAdapter(aa);

Prepared By: Devansh Parikh Page No. 30


Android Programming (03606352) PIET-DS

//Performing action onItemSelected and onNothing selected @Override


public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long id) {
Toast.makeText(getApplicationContext(),country[position] ,
Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Output:

9. Explain Checkbox in android with example.(3 marks)

Ans: In android, CheckBox is a two-states button that can be either checked (ON) or
unchecked (OFF) and it will allow users to toggle between the two states (ON / OFF)
based on the requirements. Generally, we can use multiple CheckBox controls in android
application to allow users to select one or more options from the set of values.

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change
the default state of CheckBox by using android:checked attribute. In case, if we want to
change the state of CheckBox to ON (Checked), then we need to set android:checked =
“true” in our XML layout file.

Prepared By: Devansh Parikh Page No. 31


Android Programming (03606352) PIET-DS

In android, we can create CheckBox control in two ways either in the XML layout file or
create it in the Activity file programmatically.

Attribute Description
android:id It is used to uniquely identify the control
android:checked It is used to specify the current state of checkbox
It is used to specify how to align the text like left, right,
android:gravity
center, top, etc.
android:text It is used to set the text for a checkbox.
android:textColor It is used to change the color of text.
android:textSize It is used to specify the size of text.
It is used to change the style (bold, italic, bold italic) of
android:textStyle
text.
android:background It is used to set the background color for checkbox
control.
android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the


checkbox clicked.
android:visibility It is used to control the visibility of control.

For Example:
<CheckBox
android:id="@+id/chkJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onCheckboxClicked"/>

Prepared By: Devansh Parikh Page No. 32


Android Programming (03606352) PIET-DS

10. Explain Webview with example.(3 marks)

Ans: Android WebView is used to display web page in android. The web page can be loaded
from same application or URL. It is used to display online content in android activity.
Android WebView uses webkit engine to display web page.
The android.webkit.WebView is the subclass of AbsoluteLayout class.
The loadUrl() and loadData() methods of Android WebView class are used to load and
display web page.
activity_main.xml
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

MainActivity.java ( Inside OnCreate() )

WebView mywebview = (WebView) findViewById(R.id.webView);


mywebview.loadUrl("https://www.paruluniversity.ac.in/");

11. Explain Listview with example.(3 marks)


Ans: Android ListView is a view which contains the group of items and displays in a
scrollable list. ListView is implemented by importing android.widget.ListView class.
ListView is a default scrollable which does not use other scroll view.
ListView uses Adapter classes which add the content from data source (such as string
array, array, database etc) to ListView. Adapter bridges data between an AdapterViews
and other Views (ListView, ScrollView etc).

File: activity_main.xml
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="fill_parent"/>

Create an additional mylist.xml file in layout folder which contains view components
displayed in listview.

Prepared By: Devansh Parikh Page No. 33


Android Programming (03606352) PIET-DS

mylist.xml

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

<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d"/>

Now place the list of data in strings.xml file by creating string-array. File:strings.xml

<resources>
<string name="app_name">ListView</string>
<string-array name="array_technology">
<item>Android</item>
<item>Java</item>
<item>Php</item>
</string-array>
</resources>

File: MainActivity.java

listView=(ListView)findViewById(R.id.listView);
textView=(TextView)findViewById(R.id.textView);
listItem = getResources().getStringArray(R.array.array_technology); final
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override

Prepared By: Devansh Parikh Page No. 34


Android Programming (03606352) PIET-DS

public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)


{
// TODO Auto-generated method stub String value=adapter.getItem(position);

Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}}

12. Write down steps to create progress Dialogbox.(4 marks)


Ans: We can display the android progress bar dialog box to display the status of work being
done e.g. downloading file, analyzing status of work etc.
In this example, we are displaying the progress dialog for dummy file download
operation.
Here we are using android.app.ProgressDialog class to show the progress bar. Android
ProgressDialog is the subclass of AlertDialog class.
The ProgressDialog class provides methods to work on progress bar like setProgress(),
setMessage(), setProgressStyle(), setMax(), show() etc. The progress range of Progress
Dialog is 0 to 10000.

Step 1:- Create & Object of progress dialog box. –


ProgressDialog pd = new ProgressDialog(this);
Step 2:- Set Message to the progress dialog box
-Pd.setMessage (“P_dialogbox”);
Step 3:- Set Cancelable Method to the progress dialogbox
-Pd.setCancel ble(true);
Step 4:- Set progress style to the progress dialog box
-Pd.setprogressstyle (progress Dialog.STYLE_SPINEER); Step 5:- Set initial
value to the progress dialog box.
-Pd.setprogress (0);
Step 6:- Set Maximum value to the progress dialog box
-Pd.setprogress(100);
Step 7:- Show progress Dialogbox
-Pd.show();

13. Explain android Analog clock and Digital clock with example.(4 marks)
Ans: The android.widget.AnalogClock and android.widget.DigitalClock classes provides the
functionality to display analog and digital clocks.

Android analog and digital clocks are used to show time in android application.

Android AnalogClock is the subclass of View class.

Android DigitalClock is the subclass of TextView class. Since Android API level 17, it is
deprecated. You are recommended to use TextClock Instead.

Prepared By: Devansh Parikh Page No. 35


Android Programming (03606352) PIET-DS

The AnalogClock was deprecated in API level 23. This widget is no longer supported.
Instead if you want to use AnalogClock in your application you need to hard code. It does
not appear in API level 27 to drag from palette.

In android, you need to drag analog and digital clocks from the pallet to display analog
and digital clocks.

File: activity_main.xml

For Analog Clock


<AnalogClock
android:id="@+id/analogClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="136dp"
android:layout_marginTop="296dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

For Digital Clock

<DigitalClock
android:id="@+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/analogClock1"
android:layout_centerHorizontal="true"
android:layout_marginLeft="176dp"
android:layout_marginTop="84dp"
android:text="DigitalClock"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Prepared By: Devansh Parikh Page No. 36

You might also like