Lecture Android
Lecture Android
Android
Wireless Communication and Mobile Computing
Lab
06/08/2024 2
Introduction
• Every day the new devices are incoming to the market with innovative
options thanks to growing technology.
06/08/2024 3
Cont..
• Mobile development is not about building phone apps, it’s doing any
reasonably development for any kind of mobile devices such as
developing apps for phones, tablets, smartwatches, and every form of
wearable devices that run any kind of mobile operating system.
06/08/2024 4
Major Mobile Development Platforms
• are similar to an all-in-one environment of the tools that allow you to
create, test, optimize, debug, deploy, and maintain mobile applications.
• iOS
• iOS is of course developed by Apple, and it runs exclusively on Apple
products.
• Apple provides iOS developers with many native tools and libraries to
develop iOS applications, and, though you do not have to be enforced to use
Apple’s development tools to create your apps, you just need to have a mac
running OS X to build your application.
06/08/2024 5
Cont…
• Android
• It is first being released in Sept 2008, virtually a
year later than iOS but it has managed to achieve a
reasonably massive share of the mobile market.
• iOS is designed to run only • Anyone can build an Android device, and it is
designed to run on a variety of different hardware
on a specific set of Apple platforms and devices with very different form factors
devices and capabilities.
• Consumer behavior: Customers are more used to mobile devices and is easy for them to access
information on the move.
• Personalized content delivery: Enterprise can leverage the location and sensors to offer more
contextualized, relevant and personalized content, offers and advertisements.
• Mobile ecosystem: An explosive growth in Mobile Applications stores such as Apple store, Google
Play store, Windows marketplace store was coupled with availability of games, utilities and other apps.
• Social Networking: With the popularity of web 2.0 and social media technologies such as Facebook,
Twitter users are increasingly using the location-based features in the social media platforms.
06/08/2024 9
Introduction to Mobile Computing
• Mobile computing can be defined as a computing environment over
physical mobility.
• The user of the mobile computing environment will be able to access
data, information or logical objects from any device in any network
while on move.
• Wireless telecommunications networks are generally implemented
and administered using radio communication. This implementation
takes place at the physical level (layer) of the OSI model network
structure.
06/08/2024 10
• Mobility/Nomadic is that someone / something can move or be moved easily and
quickly from place to place.
• Computing - is the operations of the computer. Types of computing are.
• Mobile Computing is a computing that connects a mobile device to network or another
computing device, anytime, anywhere.
• Nomadic Computing: It refers to limited migration is within a building at a pedestrian speed,
interleaved pattern of user relocation and indoor connections and users carrying laptop with
wireless access are engaged in nomadic computing
• Pervasive Computing: A computing environment, which is pervasive in nature and can be
made available in any environment.
• It refers to access to computer network all the time at any location by any person. It cannot be realized
unless mobile computing matures
• Ubiquitous Computing: A disappearing (nobody will notice its presence) every place
computing environment. User will be able to use both local and remote services.
06/08/2024 11
Cont….
• Global System for Mobile Communications (GSM):
• The GSM network is divided into three major systems:
• the switching system,
• the base station system, and
• the operation and support system.
06/08/2024 12
computing environment is defined as mobile if
it supports one or more of these characteristics:
1. User mobility: User should be able to move from one physical location to
another location and use same service
2. Network mobility: User should be able to move from one network to
another network and use same service
3. Device mobility: User should be able to move from one device to another
and use same service
4. Session mobility: A user session should be able to move from one user-
agent environment to another.
5. Service mobility: User should be able to move from one service to another.
6. Host mobility: The user should be either a client or server.
06/08/2024 13
Introduction to Android Development
Environment
• Before any work can begin on the development of an Android
application, the first step is to configure a computer system to act as
the development platform.
06/08/2024 14
Android Studio
• It is an OPEN SOURCE and Linux-Based OS built for mobile devices.
• It is developed by Open Handset Alliance, led by Google.
• It is not a hardware platform, while components of the underlying OS are
written in C or C++, user applications are built for Android in Java.
• It is software only.
• Leveraging its Linux kernel to interface with the hardware, you can expect
Android to run on many different devices from multiple cell phone
manufacturers.
06/08/2024 15
Features of Android:
• Beautiful UI – its screen provides beautiful and intuitive user interface.
• Connectivity - GSM/EDGE (Enhanced Data for GSM Evolution), CDMA, UMTS,
Bluetooth, Wi-Fi, LTE, NFC and WiMAX.
• Storage – lightweight relational database like SQLite.
• Media Support - MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, etc.
• Messaging – SMS, MMS
• Web-browser – supporting HTML5 and CSS3.
• Multi-touch – which initially made in handsets.
• Multi-tasking – users can jump from one task to another and run various applications
simultaneously at the same time.
• Resizable Widgets – users can expand or shrink the contents to save space.
• Multi-Language – support single direction and bi-directional text.
• etc.
06/08/2024 16
Application Fundamentals
• Apps are written in Java
• Apps can share the same user ID to see each other’s files.
06/08/2024 17
Android Version Name
• The versions
06/08/2024 19
Android Architecture
• Android OS has a stack software components and has FIVE sections.
06/08/2024 20
Android Architecture, Cont. …
1. Applications:
• It is a place where the applications are to be installed.
• All applications are written using Java programming language.
• Example: Games, Browser, Contacts, etc.
2. Application Framework:
• It provides many higher-level services to applications in the form Java Classes.
• Application developers are allowed to use these services in their applications.
• Developers are free to take advantage of the device hardware, access location
information, run background services, set alarms, add notifications to the status bar,
and much, much more.
• Developers have full access to the same framework APIs used by the core
applications.
• The application architecture is designed to simplify the reuse of components.
06/08/2024 21
Android Architecture, Cont. …
2. Application Framework:
• Underlying all applications is a set of services and systems, including:
• A rich and extensible set of Views that can be used to build an application, including lists,
grids, text boxes, buttons, and even an embeddable web browser
• Content Providers that enable applications to access data from other applications (such
as Contacts), or to share their own data.
• A Resource Manager, providing access to non-code resources such as localized strings,
graphics, and layout files.
• A Notification Manager that enables all applications to display custom alerts in the status
bar.
• An Activity Manager that manages the lifecycle of applications and provides a common
navigation back-stack.
3. Libraries:
• Example: WebKit, Libc, SQLite, Media Framework, SSL, etc.
06/08/2024 22
Android Architecture, Cont. …
4. Android Runtime:
• It provides a key component called Dalvik Virtual Machine (DVM) (which is a kind
of JVM specially designed and optimized for Android).
• The DVM:
o It makes the use of Linux core features like memory management and multi-threading.
o It enables every android application to run in its own process, with its own instance of
DVM.
o It executes files in the Dalvik Executable (.dex) format which is optimized for minimal
memory footprint.
o The VM is register-based, and runs classes compiled by a Java language compiler that
have been transformed into the .dex format by the included "dx tool”.
06/08/2024 23
Android Architecture, Cont. …
• DVM, Cont. …
• It provides a set of core libraries which enable android application developers to write
android application using standard Java Programming language.
06/08/2024 24
Android Architecture, Cont. …
5. Linux Kernel:
• It provides basic system functionalities.
• It also acts as an abstraction layer between the hardware and the rest of the software
stack.
• Example: Process management, memory management, device management like
camera, keypad, etc.
• It handles all things that kernel is good at, such as networking and device drivers.
06/08/2024 25
DVM vs. JVM
• DVM
o Google
o Dalvik executable (.dex)
o Dalvik Virtual Machine (DVM)
o Only supports a subset of standard Java Library
• JVM
o Sun
o Java bytecode (.class)
o Java Virtual Machine (JVM)
06/08/2024 26
FACTORS IN
DEVELOPING MOBILE
APPLICATION
06/08/2024 27
• Mobile application development is the set of processes and
procedures involved in writing software for small, wireless computing
devices, such as smartphones and other hand-held devices.
• Learn about the factors that influence your mobile app development
process by taking note of the items on this list.
06/08/2024 28
factors
• Distribution Channel
• As a developer, you must first identify which platform best supports your grand idea.
• Though Google Play Store and Apple App Store serve the same function, they have different guidelines.
• Audience Research For your idea to become successful,
• you must first conduct audience research.
• Knowing your audience involves understanding the industry and getting in-depth knowledge about the
people that might take an interest in your apps.
• App Idea
• Apps don’t come out of thin air. They start as brilliant ideas. Unfortunately, not all ideas become great and
successful once you turn them into an app.
• App Development Strategy
• To properly execute your app idea, you must come with a plan.
• In this case, you must have a solid app development strategy.
• UI/UX User interface (UI) and user experience (UX) are part of what keeps users hooked on an
app.
06/08/2024 29
Cont..
• Testing
• You must also run a few tests to ensure your design runs smoothly.
• It’s a way to secure that your mobile app has no exceptions and bugs.
• Security
• must be part of your app development process.
• You can also keep the user’s information safe through encryption. You should also restrict your app’s permissions to a
minimum.
• Always prioritize security to ensure your app isn’t vulnerable to external threats.
• Monitoring
• You still have work to do after you publish your mobile app. You must be hands-on with fixes, performance
improvements, changes, and integrating new features.
• Lifecycle management – Once an app is deployed, developers must test, host, deploy, maintain and analyze its usage
throughout its lifecycle.
• Delivery –
• Apps aren’t done when they go into production.
• They must be dependable. They must scale.
• They will need updating based on evolving requirements and end user feedback.
• Developers need to make sure the tool they select will allow for easy upgrades, updates, availability, scalability and performance
06/08/2024 30
• Ionic Ionic Framework is a very popular open-source mobile framework that was released in 2013.
• Xamarin Xamarin is an extremely popular Mobile framework (With over 1.4 million developers using it!)
that was acquired by Microsoft in 2016 and is currently a Microsoft subsidiary.
Android Development
• Adobe PhoneGap Adobe PhoneGap is an open-source mobile application development framework that
Frameworks
was purchased by Adobe Systems in 2011.
• React Native React Native is an open-source mobile framework that was created by Facebook and
released in 2015.
• Flutter Flutter is a comparatively recent open-source development framework that was released by
Google in 2017.
• Titanium SDK Titanium SDK is an open-source framework that was created by Appcelerator, Inc. and
released in 2018.
• JQuery Mobile jQuery Mobile is a Touch-Optimized Web Framework that was developed by the jQuery
team and released in 2010.
• Corona SDK Corona Software Development Kit was developed by Corona Labs Inc. and released in 2009.
It is a great platform for creating apps for mobile as well as desktop systems.
• Native Script Native Script is an open-source framework for creating native (duh!) mobile apps that were
developed by Progress and initially released in 2014.
• Mobile06/08/2024
Angular UI Mobile Angular UI is a mobile UI framework (As is clear from the name!) that allows 31
the creation of HTML5 hybrid mobile apps using a combination of Angular JS and Bootstrap
User interfaces
• User interfaces are the access points where users interact with
designs.
• They come in three formats:
• Graphical user interfaces (GUIs)—Users interact with visual representations
on digital control panels. A computer’s desktop is a GUI.
• Voice-controlled interfaces (VUIs)—Users interact with these through their
voices. Most smart assistants—e.g., Siri on iPhone and Alexa on Amazon
devices—are VUIs.
• Gesture-based interfaces—Users engage with 3D design spaces through
bodily motions: e.g., in virtual reality (VR) games.
06/08/2024 32
Designing the Right UI
• Consistency of the design layout
• Unambiguous Interactive Elements:
• The design elements that are interactive in nature must be clearly depicted. Ambiguity
should be avoided to make sure that the users are going to access such elements
when required by them
• Single Trial Learning Experience
• Anticipate and Answer Users’ Queries:
• When a user’s tap a button, they want to know whether the process has started and
how long will it take.
• Layered User Experience:
• The UX should be layered. Layered here refers that all the features of an app must not
be exposed at once.
06/08/2024 33
API
• API stands for application programming interface.
• An API is a platform-agnostic interface that allows software applications to communicate with each other.
• It's like the doorway into another application - if you know how to open the door, you can access all of the applications inside.
• it's a set of rules and guidelines that allow app developers to access certain features of an application.
• For example, an app developer might use an API to connect with a third-party service provider such as Amazon or Google.
• APIs can be used by app developers to gain access to data, functionality, or other systems outside of the application itself.
• In short, an API is a powerful tool that app developers can use to make their applications more powerful and efficient.
• APIs can be used for a wide variety of purposes, from sending a simple email to retrieving data from a web service.
• APIs are beneficial because they allow developers to add specific functionality to an application, without having to write all
of the code themselves.
06/08/2024 34
Types of APIs
• Nowadays, most application programming interfaces are web APIs that expose an application's data and
functionality over the internet. Here are the four main types of web API:
• Open APIs are open source application programming interfaces you can access with the HTTP protocol. Also
known as public APIs, they have defined API endpoints and request and response formats.
• Partner APIs are application programming interfaces exposed to or by strategic business partners.
• Typically, developers can access these APIs in self-service mode through a public API developer portal. Still, they will need to
complete an onboarding process and get login credentials to access partner APIs.
• Internal APIs are application programming interfaces that remain hidden from external users.
• These private APIs aren't available for users outside of the company and are instead intended to improve productivity and
communication across different internal development teams.
06/08/2024 35
Android Applications Components
• They are the essential building blocks of an Android applications.
• They are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
• Four main components are used in android application.
06/08/2024 36
Activities
• It represents a single screen with UI.
• Example:
• An email application might have one activity that shows a list of new emails, another
activity to compose an email, and one for reading emails.
• If an application has more than one activity, then one of them should be marked as the
activity that is presented when the application is launched.
• An activity is implemented as a subclass of Activity class as follows:
06/08/2024 37
Services
• It is a component that runs in the background to perform long-running operations.
• Example:
• A service might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking user
interaction with an activity.
• A media player playing songs from a play list.
• A service is implemented as a subclass of Service class as follows:
06/08/2024 38
Broadcast Receivers
• It responds to broadcast messages from other applications or from the system.
• It is a component that does nothing but receive and react to broadcast announcements.
• Many broadcasts originate in system code.
• Example:
• Some data has been downloaded to the device and is available for them to use.
• An announcements that the time-zone has changed, that the battery is low, that a picture
has been taken, or that the user changed a language preference.
• A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
each message is broadcasted as an Intent object.
06/08/2024 39
Content Providers
• It makes a specific set of the application's data available to other applications.
• Android ships with a number of content providers for common data types (audio,
video, images, personal contact information, etc.)
• It supplies data from one application to others on request.
• Such requests are handled by the methods of the ContentResolver class.
• The data may be stored in the file system, the database or somewhere else entirely.
• It is implemented as a subclass of ContentProvider class and must implement a
standard set of APIs that enable other applications to perform transactions.
06/08/2024 40
Intents
• Activities, services, and broadcast receivers - are activated by asynchronous messages
called intents.
• It is an Intent object that holds the content of the message.
• For activities and services, it names the action being requested and specifies the URI
of the data to act on, among other things.
• Example:
o It might convey a request for an activity to present an image to the user or let the user
edit some text.
• For broadcast receivers, the Intent object names the action being announced.
• Example:
It might announce to interested parties that the camera button has been pressed.
06/08/2024 41
Additional Components
• These are the additional components we use while developing any Apps.
No. Component Description
1. Fragments Represent a behavior or portion of UI in an Activity.
2. Views UI element that are drawn onscreen including buttons, list forms etc.
3. View hierarchies that control screen format and appearance of the
Layouts
views.
4. Intents Messages wiring components together.
5. Resources External elements, such strings, constants, and drawable pictures.
6. Manifest Configuration file for the application.
06/08/2024 42
Installation of Android Studio
• Android Studio is bundled with Android Software Development Kit
(SDK). Please navigate to the official download site located at:
https://developer.android.com/studio/index.html.
06/08/2024 43
Installing Android SDK
• SDK – stands for Software Development Kit.
• Its contains the main components like:
o Tools – it primary includes stock android emulator, hierarchy view, SDK manager, and
ProGuard.
o Build Tools – it primary contains aapt (Android packaging tools to create .apk), dx
(Android tool that converts .java files to .dex files).
o Platform Tools – it primary includes the Android debug shell, sqlite3 and Systrace.
06/08/2024 44
Installation of SDK updates:
• After the installation of Android Studio, it is better to check SDK
updates. For this, run Android Studio and open the SDK manager from
Tools Android SDK Manager as shown below
06/08/2024 45
06/08/2024 46
Activity Lifecycle
• It is summarized here.
06/08/2024 47
Activity Lifecycle, Cont. …
• onResume() – is called when the activity starts interacting with the user.
o At this stage we can start any services or code that needs to run while your activity is in
the foreground.
06/08/2024 48
Activity Lifecycle, Cont. …
• onPause() – is called when the current activity is being paused and the previous
o If there are any unsaved changes, you should save them here.
o At this stage we can stop any services or code that does not need to run when your
06/08/2024 49
Activity Lifecycle, Cont. …
• onRestart() – is called when the activity has been stopped and is restarting again.
o For example, you turn off your phone screen (lock it) and then unlock it again.
06/08/2024 50
Android Application Development
• The Apps can be developed in the following steps.
06/08/2024 51
Android Development
• It is developed in the following steps.
06/08/2024 52
Create Android Application
• Steps used to create:
o File ----> New ----> New Project ----> Write Application Name, then click Next ---->
select Target Android Devices (Phone and Tablet, Wear, TV, Android Auto), then
click Next ----> Add an Activity to Mobile (Basic Activity, Bottom Navigation
Activity, Empty Activity, Fullscreen Activity, Google AdMob Ads Activity, Google
Map Activity, Login Activity, Master/ Detail Flow, Navigation Drawer Activity), then
click Next ----> Customize the Activity ----> finally, click FINISH.
06/08/2024 53
Example-1: Hello World
• The project contains:
06/08/2024 54
Example-1: Hello World, Cont. …
• It contains two parts:
• The JAVA code
• The .xml code
06/08/2024 55
Deployment the APP
• Two choices for deployment:
06/08/2024 56
AVD (Android Virtual Device)
• Installation of Emulators are software that mimics the behavior of real devices
• When we develop an app, we obviously won’t have all the possible devices (Android
phones, tablets, etc.) available at hand. Because of this, we run the apps on emulators
for testing on various devices.
• Emulators are also called as “Android Virtual Devices (AVDs)” in Android Studio.
• The AVD Manager is an interface you can launch from Android Studio that helps you
create and manage AVDs.
• An AVD contains a, hardware profile, system image, storage area, and skin
06/08/2024 57
How to Create or Delete AVD?
• Go to “Tools Android AVD Manager click on, Create Virtual Device
Select Hardware click Next Click Next Write AVD Name, then click
FINISH”.
06/08/2024 58
Within the Android SDK Tools screen, make sure that the
following packages are listed as Installed in the Status column
06/08/2024 59
Thanks!!
06/08/2024 60
Intents and Services
06/08/2024 61
Service
• You can think Service as an Android component that is used to perform
some long-running operations in the background like that in the Music
app, where we run the app in the background and use other applications
of the mobile parallelly.
• The best part is that you don’t need to provide some UI for the
operations to be performed in the background.
• By using Service, you can perform some InterProcess Communication
(IPC) also.
• So, with the help of Service, you can perform a number of operations
together because any application component can start a Service and can
run in background.
06/08/2024 62
There are three ways of using Service:
1. Foreground:
• A foreground service is a Service that will let the user know about what
is happening in the background.
• here displaying notification is a must.
2. Background:
• Here, the user will never know about what is happening in the
background of the application.
• But for the API level 21 or higher, the Android System imposes some restrictions while
using the Background Service. So, take care of those restrictions before using the
Background Service.
3. Bound:
• The Bound Service is used when one or more than one application component
binds the Service by using the bindService() method.
• If the applications unbind the Service, then the Service will be destroyed.
06/08/2024 63
Intent
• An Intent is a messaging object you can use to request an action from another app
component.
• Although intents facilitate communication between components in several ways, there
are three fundamental use cases:
• There are two types of intents:
• Explicit intents
• You'll typically use an explicit intent to start a component in your own app, because you know the class name
of the activity or service you want to start.
• For example, you might start a new activity within your app in response to a user action, or start a service to
download a file in the background.
• Implicit intents
• do not name a specific component, but instead declare a general action to perform, which allows a component
from another app to handle it.
• For example, if you want to show the user a location on a map, you can use an implicit intent to request that
another capable app show a specified location on a map.
06/08/2024 64
• How an implicit intent is delivered
through the system to start
another activity:
• [1] Activity A creates an Intent with
an action description and passes it
to startActivity().
• [2]The Android System searches all
apps for an intent filter that
matches the intent. When a match
is found,
• [3] the system starts the matching
activity (Activity B) by invoking its
onCreate() method and passing it
the06/08/2024
Intent. 65
Starting an activity
• An Activity represents a single screen in an app.
• You can start a new instance of an Activity by passing an Intent to
startActivity().
• The Intent describes the activity to start and carries any necessary
data.
• If you want to receive a result from the activity when it finishes, call
startActivityForResult().
• Your activity receives the result as a separate Intent object in your
activity's onActivityResult() callback.
06/08/2024 66
Starting a service
• A Service is a component that performs operations in the background
without a user interface.
• With Android 5.0 (API level 21) and later, you can start a service with
JobScheduler.
• For versions earlier than Android 5.0 (API level 21), you can start a
service by using methods of the Service class.
06/08/2024 67
Delivering a broadcast
• A broadcast is a message that any app can receive.
• The system delivers various broadcasts for system events, such as
when the system boots up or the device starts charging.
• You can deliver a broadcast to other apps by passing an Intent to
sendBroadcast() or sendOrderedBroadcast().
06/08/2024 68
Android Widgets
• There are given a lot of android widgets with simplified examples
such as Button, EditText, AutoCompleteTextView, ToggleButton,
DatePicker, TimePicker, ProgressBar etc.
06/08/2024 69
Android Toast
06/08/2024 70
Toast class
• Toast class is used to show notification for a particular interval of
time. After sometime it disappears. It doesn't block the user
interaction.
• Constants of Toast class
• There are only 2 constants of Toast class which are given below.
public static final int LENGTH_LONG displays view for the long duration of
time.
public static final int LENGTH_SHORT displays view for the short duration of
time.
06/08/2024 71
Methods of Toast class
• The widely used methods of Toast class are given below.
Method Description
public static Toast makeText(Context context, makes the toast containing text and duration.
CharSequence text, int duration)
public void setMargin (float horizontalMargin, float changes the horizontal and vertical margin difference.
verticalMargin)
06/08/2024 72
• Android Toast Example
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
• Another code:
Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
06/08/2024 73
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
06/08/2024 75
Methods of CheckBox class
There are many inherited methods of View, TextView, and Button classes in the CheckBox
class. Some of them are as follows:
Method Description
public boolean isChecked() Returns true if it is checked
otherwise false.
public void setChecked(boolean Changes the state of the CheckBox.
status)
06/08/2024 76
1.<?xml version="1.0" encoding="utf-8"?> 34. android:layout_marginTop="28dp"
2.<android.support.constraint.ConstraintLayout 35. android:text="Burger"
3.xmlns:android="http://schemas.android.com/apk/res/android" 36. app:layout_constraintStart_toStartOf="parent"
4. xmlns:app="http://schemas.android.com/apk/res-auto" 37. app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
5. xmlns:tools="http://schemas.android.com/tools" 38.
6. android:layout_width="match_parent" 39. <Button
7. android:layout_height="match_parent" 40. android:id="@+id/button"
8. tools:context="example.javatpoint.com.checkbox.MainActivity"> 41. android:layout_width="wrap_content"
9. <CheckBox 42. android:layout_height="wrap_content"
10. android:id="@+id/checkBox" 43. android:layout_marginLeft="144dp"
11. android:layout_width="wrap_content" 44. android:layout_marginTop="184dp"
12. android:layout_height="wrap_content" 45. android:text="Order"
13. android:layout_marginLeft="144dp" 46. app:layout_constraintStart_toStartOf="parent"
14. android:layout_marginTop="68dp" 47. app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
15. android:text="Pizza" 48.
16. app:layout_constraintStart_toStartOf="parent" 49.</android.support.constraint.ConstraintLayout>
17. app:layout_constraintTop_toTopOf="parent" />
18.
19. <CheckBox
20. android:id="@+id/checkBox2"
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:layout_marginLeft="144dp"
24. android:layout_marginTop="28dp"
25. android:text="Coffee"
26. app:layout_constraintStart_toStartOf="parent"
27. app:layout_constraintTop_toBottomOf="@+id/checkBox" />
28.
29. <CheckBox
30. android:id="@+id/checkBox3"
31. android:layout_width="wrap_content"
32. 06/08/2024
android:layout_height="wrap_content" 77
33. android:layout_marginLeft="144dp"
1. package example.javatpoint.com.checkbox; 28.
2. 29. @Override
3. import android.support.v7.app.AppCompatActivity; 30. public void onClick(View view) {
4. import android.os.Bundle; 31. int totalamount=0;
5. import android.view.View; 32. StringBuilder result=new StringBuilder();
6. import android.widget.Button; 33. result.append("Selected Items:");
7. import android.widget.CheckBox; 34. if(pizza.isChecked()){
8. import android.widget.Toast; 35. result.append("\nPizza 100Rs");
9. 36. totalamount+=100;
10. public class MainActivity extends AppCompatActivity { 37. }
11. CheckBox pizza,coffe,burger; 38. if(coffe.isChecked()){
12. Button buttonOrder; 39. result.append("\nCoffe 50Rs");
13. @Override 40. totalamount+=50;
14. protected void onCreate(Bundle savedInstanceState) { 41. }
15. super.onCreate(savedInstanceState); 42. if(burger.isChecked()){
16. setContentView(R.layout.activity_main); 43. result.append("\nBurger 120Rs");
17. addListenerOnButtonClick(); 44. totalamount+=120;
18. } 45. }
19. public void addListenerOnButtonClick(){ 46. result.append("\nTotal: "+totalamount+"Rs");
20. // 47. //Displaying the message on the toast
Getting instance of CheckBoxes and Button from the activty_main.xml file 48. Toast.makeText(getApplicationContext(), result.toString(), Toast.LE
21. pizza=(CheckBox)findViewById(R.id.checkBox); NGTH_LONG).show();
22. coffe=(CheckBox)findViewById(R.id.checkBox2); 49. }
23. burger=(CheckBox)findViewById(R.id.checkBox3); 50.
24. buttonOrder=(Button)findViewById(R.id.button); 51. });
25. 06/08/2024 52. } 78
Android RadioButton
06/08/2024 79
1. package example.javatpoint.com.radiobutton; 19. public void onclickbuttonMethod(View v){
1.<?xml version="1.0" encoding="utf-8"?> 39. <RadioButton
2.<LinearLayout 40. android:id="@+id/radioFemale"
2. import android.support.v7.app.AppCompatActivity; 20. int selectedId = radioGroup.getCheckedRadioButtonId();
3. xmlns:android="http://schemas.android.com/apk/res/android" 41. android:layout_width="fill_parent"
4. xmlns:tools="http://schemas.android.com/tools" 42. android:layout_height="wrap_content"
3. import android.os.Bundle; 5. android:layout_width="match_parent" 43. android:text=" Female"
6. android:layout_height="match_parent" 44. android:layout_marginTop="20dp"
21. genderradioButton = (RadioButton) findViewById(selecte
4. import android.view.View; 7. android:paddingBottom="@dimen/activity_vertical_margin"
dId);
45. android:checked="false"
8. android:paddingLeft="@dimen/activity_horizontal_margin" 46. android:button="@drawable/custom_radio_button"
9. android:paddingRight="@dimen/activity_horizontal_margin" 47. android:textSize="20dp" />
5. import android.widget.Button; 22. if(selectedId==-1){
10. android:paddingTop="@dimen/activity_vertical_margin" 48. </RadioGroup>
11. android:orientation="vertical" 49.
6. import android.widget.RadioButton; 23. Toast.makeText(MainActivity.this,"Nothing
12. tools:context="com.example.test.customradiobutton.MainActivity"> 50. <Button
selected",
13. 51. android:layout_width="wrap_content"
7. import android.widget.RadioGroup; 14. <TextView Toast.LENGTH_SHORT).show(); 52. android:layout_height="wrap_content"
15. android:id="@+id/tv" 53. android:text="Show Selected"
8. import android.widget.Toast; 16. 24. }
android:layout_width="fill_parent" 54. android:id="@+id/button"
17. android:layout_height="wrap_content" 55. android:onClick="onclickbuttonMethod"
18.
9. public class MainActivity extends AppCompatActivity
19. { 25. else{
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
56.
57.
android:layout_gravity="center_horizontal" />
18. }06/08/2024 80
Android AlertDialog
• Android AlertDialog can be used to display the dialog message with
OK and Cancel buttons. It can be used to interrupt and ask the user
about his/her choice to continue or discontinue.
• Android AlertDialog is composed of three regions: title, content area
and action buttons.
• Android AlertDialog is the subclass of Dialog class.
Method Description
public AlertDialog.Builder setTitle(CharSequence) This method is used to set the title of AlertDialog.
public AlertDialog.Builder setMessage(CharSequence) This method is used to set the message for AlertDialog.
public AlertDialog.Builder setIcon(int) This method is used to set the icon over AlertDialog.
06/08/2024 81
1. package example.javatpoint.com.alertdialog; 26. //Uncomment the below code to Set the message and title from the strings.xml file
2. 27. builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
28.
3. import android.content.DialogInterface; 29. //Setting message manually and performing action on button click
4. import android.support.v7.app.AppCompatActivity; 30. builder.setMessage("Do you want to close this application ?")
5. import android.os.Bundle; 31. .setCancelable(false)
32. .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
6. import android.view.View; 33. public void onClick(DialogInterface dialog, int id) {
7. import android.widget.Button; 34. finish();
35. Toast.makeText(getApplicationContext(),"you choose yes action for alertbox",
8. import android.app.AlertDialog;
36. Toast.LENGTH_SHORT).show();
9. import android.widget.Toast; 37. }
10. 38. })
39. .setNegativeButton("No", new DialogInterface.OnClickListener() {
11. public class MainActivity extends AppCompatActivity {
40. public void onClick(DialogInterface dialog, int id) {
12. Button closeButton; 41. // Action for 'NO' Button
13. AlertDialog.Builder builder; 42. dialog.cancel();
43. Toast.makeText(getApplicationContext(),"you choose no action for alertbox",
14. @Override 44. Toast.LENGTH_SHORT).show();
15. protected void onCreate(Bundle savedInstanceState) { 45. }
16. super.onCreate(savedInstanceState); 46. });
47. //Creating dialog box
17. setContentView(R.layout.activity_main); 48. AlertDialog alert = builder.create();
18. 49. //Setting the title manually
19. closeButton = (Button) findViewById(R.id.button); 50. alert.setTitle("AlertDialogExample");
51. alert.show();
20. builder = new AlertDialog.Builder(this); 52. }
21. closeButton.setOnClickListener(new View.OnClickLi 53. });
stener() { 54. }
22. @Override 55.}
06/08/2024 83
1. <android.support.constraint.ConstraintLayout
2. xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="example.javatpoint.com.spinner.MainActivity">
8.
9. <Spinner
10. android:id="@+id/spinner"
11. android:layout_width="149dp"
12. android:layout_height="40dp"
13. android:layout_marginBottom="8dp"
14. android:layout_marginEnd="8dp"
15. android:layout_marginStart="8dp"
16. android:layout_marginTop="8dp"
17. app:layout_constraintBottom_toBottomOf="parent"
18. app:layout_constraintEnd_toEndOf="parent"
19. app:layout_constraintHorizontal_bias="0.502"
20. app:layout_constraintStart_toStartOf="parent"
21. app:layout_constraintTop_toTopOf="parent"
22. app:layout_constraintVertical_bias="0.498" />
23. 06/08/2024 84
1. public class MainActivity extends AppCompatActivity implements
2. AdapterView.OnItemSelectedListener {
06/08/2024 86
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="listview.example.com.listview.MainActivity">
8.
9. <ListView
10. android:id="@+id/listView"
11. android:layout_width="match_parent"
12. android:layout_height="fill_parent"
13. />
14.</android.support.constraint.ConstraintLayout>
06/08/2024 87
mylist.xml
1. <?xml version="1.0" encoding="utf-8"?> strings.xml
2. 1.<resources>
3. <TextView xmlns:android="http://schemas.android.com/apk/res/ 2. <string name="app_name">ListView</string>
android" 3. <string-array name="array_technology">
4. android:id="@+id/textView" 4. <item>Android</item>
5. android:layout_width="wrap_content" 5. <item>Java</item>
6. android:layout_height="wrap_content" 6. <item>Php</item>
7. android:text="Medium Text" 7. <item>Hadoop</item>
8. android:textStyle="bold" 8. <item>Sap</item>
9. android:textAppearance="?android:attr/textAppearanceMedium" 9. <item>Python</item>
10. <item>Ajax</item>
10. android:layout_marginLeft="10dp"
11. <item>C++</item>
11. android:layout_marginTop="5dp"
12. <item>Ruby</item>
12. android:padding="2dp" 13. <item>Rails</item>
13. android:textColor="#4d4d4d" 14. <item>.Net</item>
14. /> 15. <item>Perl</item>
16. </string-array>
17.</resources>
06/08/2024 88
1. package listview.example.com.listview;
2.
3. import android.support.v7.app.AppCompatActivity; 28. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
29. @Override
4. import android.os.Bundle;
30. public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
5. import android.view.View; 31. // TODO Auto-generated method stub
6. import android.widget.AdapterView; 32. String value=adapter.getItem(position);
33. Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
7. import android.widget.ArrayAdapter; 34.
8. import android.widget.ListView; 35. }
36. });
9. import android.widget.TextView; 37. }
10. import android.widget.Toast; 38.}
11.
12. public class MainActivity extends AppCompatActivity {
13. ListView listView;
14. TextView textView;
15. String[] listItem;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. listView=(ListView)findViewById(R.id.listView);
22. textView=(TextView)findViewById(R.id.textView);
23. listItem = getResources().getStringArray(R.array.array_technology);
24. final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
25. android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
26. 06/08/2024
listView.setAdapter(adapter); 89
Android DatePicker
• Android DatePicker is a widget to select date. It allows you to select
date by day, month and year. Like DatePicker, android also provides
TimePicker to select time.
• The android.widget.DatePicker is the subclass of FrameLayout class.
06/08/2024 90
1. <?xml version="1.0" encoding="utf-8"?> 20.
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/ 21. <Button
android" 22. android:id="@+id/button1"
3. xmlns:app="http://schemas.android.com/apk/res-auto" 23. android:layout_width="wrap_content"
4. xmlns:tools="http://schemas.android.com/tools" 24. android:layout_height="wrap_content"
5. android:layout_width="match_parent" 25. android:layout_alignParentBottom="true"
6. android:layout_height="match_parent" 26. android:layout_centerHorizontal="true"
7. tools:context="example.javatpoint.com.datepicker.MainActivity"> 27. android:layout_marginBottom="20dp"
8. 28. android:text="Change Date" />
9. <TextView 29.
10. android:id="@+id/textView1" 30. <DatePicker
11. android:layout_width="wrap_content" 31. android:id="@+id/datePicker"
12. android:layout_height="wrap_content" 32. android:layout_width="wrap_content"
13. android:layout_above="@+id/button1" 33. android:layout_height="wrap_content"
14. android:layout_alignParentLeft="true" 34. android:layout_above="@+id/textView1"
15. android:layout_alignParentStart="true" 35. android:layout_centerHorizontal="true"
16. android:layout_marginBottom="102dp" 36. android:layout_marginBottom="36dp" />
17. android:layout_marginLeft="30dp" 37.
18. android:layout_marginStart="30dp" 38.</RelativeLayout>
06/08/2024 91
19. android:text="" />
1. package example.javatpoint.com.datepicker; 24.
2. 25. displayDate.setOnClickListener(new View.OnClickListen
3. import android.support.v7.app.AppCompatActivity; er(){
4. import android.os.Bundle; 26. @Override
5. import android.view.View; 27. public void onClick(View view) {
6. import android.widget.Button; 28.
7. import android.widget.DatePicker; 29. textview1.setText("Change Date: "+getCurrentDate())
;
8. import android.widget.TextView;
30. }
9.
31.
10.public class MainActivity extends AppCompatActivity {
32. });
11. DatePicker picker;
33.
12. Button displayDate;
34. }
13. TextView textview1;
35. public String getCurrentDate(){
14. @Override
36. StringBuilder builder=new StringBuilder();;
15. protected void onCreate(Bundle savedInstanceState) {
37. builder.append((picker.getMonth() + 1)+"/");//
16. super.onCreate(savedInstanceState); month is 0 based
17. setContentView(R.layout.activity_main); 38. builder.append(picker.getDayOfMonth()+"/");
18. 39. builder.append(picker.getYear());
19. textview1=(TextView)findViewById(R.id.textView1); 40. return builder.toString();
20. picker=(DatePicker)findViewById(R.id.datePicker); 41. }
21. displayDate=(Button)findViewById(R.id.button1); 42.}
22. 06/08/2024 92
06/08/2024 93
Android TimePicker
• Android TimePicker widget is used to select date. It allows you to
select time by hour and minute. You cannot select time by seconds.
• The android.widget.TimePicker is the subclass of FrameLayout class.
06/08/2024 94
1. <?xml version="1.0" encoding="utf-8"?> 20.
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/ 21. <Button
android" 22. android:id="@+id/button1"
3. xmlns:app="http://schemas.android.com/apk/res-auto" 23. android:layout_width="wrap_content"
4. xmlns:tools="http://schemas.android.com/tools" 24. android:layout_height="wrap_content"
5. android:layout_width="match_parent" 25. android:layout_alignParentBottom="true"
6. android:layout_height="match_parent" 26. android:layout_centerHorizontal="true"
7. tools:context="example.javatpoint.com.timepicker.MainActivity"> 27. android:layout_marginBottom="20dp"
8. 28. android:text="Change Time" />
9. <TextView 29.
10. android:id="@+id/textView1" 30. <TimePicker
11. android:layout_width="wrap_content" 31. android:id="@+id/timePicker"
12. android:layout_height="wrap_content" 32. android:layout_width="wrap_content"
13. android:layout_above="@+id/button1" 33. android:layout_height="wrap_content"
14. android:layout_alignParentLeft="true" 34. android:layout_above="@+id/textView1"
15. android:layout_alignParentStart="true" 35. android:layout_centerHorizontal="true"
16. android:layout_marginBottom="102dp" 36. android:layout_marginBottom="36dp" />
17. android:layout_marginLeft="30dp" 37.</RelativeLayout>
18. android:layout_marginStart="30dp"
19. 06/08/2024
android:text="" /> 95
1. package example.javatpoint.com.timepicker; 23. changetime=(Button)findViewById(R.id.button1);
2. 24.
3. import android.support.v7.app.AppCompatActivity; 25. textview1.setText(getCurrentTime());
4. import android.os.Bundle; 26.
5. import android.view.View; 27. changetime.setOnClickListener(new View.OnClickListener
6. import android.widget.Button; (){
7. import android.widget.TextView; 28. @Override
8. import android.widget.TimePicker; 29. public void onClick(View view) {
9. 30. textview1.setText(getCurrentTime());
10.public class MainActivity extends AppCompatActivity { 31. }
11. TextView textview1; 32. });
12. TimePicker timepicker; 33.
13. Button changetime; 34. }
14. @Override 35.
15. protected void onCreate(Bundle savedInstanceState) { 36. public String getCurrentTime(){
16. super.onCreate(savedInstanceState); 37. String currentTime="Current Time: "+timepicker.getCurren
tHour()+":"+timepicker.getCurrentMinute();
17. setContentView(R.layout.activity_main);
38. return currentTime;
18.
39. }
19. textview1=(TextView)findViewById(R.id.textView1);
40.
20. timepicker=(TimePicker)findViewById(R.id.timePicker);
41.}
21. //Uncomment the below line of code for 24 hour view
06/08/2024 96
22. timepicker.setIs24HourView(true);
06/08/2024 97
Android ScrollView (Vertical)
06/08/2024 98
1. <?xml version="1.0" encoding="utf-8"?> 31. <Button android:layout_width="fill_parent" 61. <Button android:layout_width="fill_parent"
12. android:layout_width="fill_parent" 42. android:text="Button 8" /> 72. android:text="Button 18" />
15. <LinearLayout 45. android:text="Button 9" /> 75. android:text="Button 19" />
18. android:orientation="vertical" > 48. android:text="Button 10" /> 78. android:text="Button 20" />
21. android:text="Button 1" /> 51. android:text="Button 11" /> 81. </RelativeLayout>
30. 06/08/2024
android:text="Button 4" /> 60. android:text="Button 14" /> 99
Activity class
In activity class, we have not changed any code.
File: MainActivity.java
1.package com.example.test.scrollviews;
2.
3.import android.support.v7.app.AppCompatActivity;
4.import android.os.Bundle;
5.
6.public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13.}
06/08/2024 100
Android HorizontalScrollView
• A HorizontalScrollView is a FrameLayout.
The android.widget.HorizontalScrollView class provides the
functionality of horizontal scroll view.
• HorizontalScrollView is used to scroll the child elements or views in a
horizontal direction. HorizontalScrollView only supports horizontal
scrolling.
• For vertical scroll, android uses ScrollView.
• Let's implement simple example of HorizontalScrollView.
06/08/2024 101
1. <?xml version="1.0" encoding="utf-8"?> 45. android:layout_width="wrap_content"
2. <RelativeLayout xmlns:android="http:// 25. android:layout_height="wrap_content"
schemas.android.com/apk/res/android" 46. android:layout_height="wrap_content"
3. android:layout_width="fill_parent" 26. android:text="New Button2"
4. android:layout_height="fill_parent"> 27. android:id="@+id/button2" /> 47. android:text="New Button6"
5. <LinearLayout 28. 48. android:id="@+id/button6" />
6. android:layout_width="match_parent" 29. <Button 49. <Button
7. android:layout_height="match_parent" 30. android:layout_width="wrap_content" 50. android:layout_width="wrap_content"
8. android:layout_marginTop="25dp">
31. android:layout_height="wrap_content" 51. android:layout_height="wrap_content"
9. <HorizontalScrollView
10. android:layout_width="match_parent" 52. android:text="New Button7"
32. android:text="New Button3"
11. android:layout_height="60dp" 53. android:id="@+id/button7" />
33. android:id="@+id/button3" />
12. android:id="@+id/horizontalScrollView"> 54. <Button
34. <Button
13. 55. android:layout_width="wrap_content"
35. android:layout_width="wrap_content"
14. <LinearLayout
15. android:layout_width="wrap_content" 36. android:layout_height="wrap_content" 56. android:layout_height="wrap_content"
16. android:layout_height="wrap_content"
17. android:orientation="horizontal"> 37. android:text="New Button4" 57. android:text="New Button8"
18. <Button 38. android:id="@+id/button4" /> 58. android:id="@+id/button8"/>
19. android:layout_width="wrap_content" 39. <Button 59. </LinearLayout>
40. android:layout_width="wrap_content" 60.
20. android:layout_height="wrap_content" 61. </HorizontalScrollView>
41. android:layout_height="wrap_content" 62. </LinearLayout>
21. android:text="New Button1" 63. </RelativeLayout>
22. android:id="@+id/button1" /> 42. android:text="New Button5"
23. <Button 43. android:id="@+id/button5" />
06/08/2024 102
24. android:layout_width="wrap_content" 44. <Button
1. package com.example.test.scrollviews;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13.}
06/08/2024 103
Android Activity Lifecycle
• Android Activity Lifecycle is controlled by 7 methods of
android.app.Activity class. The android Activity is the subclass of
ContextThemeWrapper class.
• An activity is the single screen in android. It is like window or frame
of Java.
• By the help of activity, you can place all your UI components or
widgets in a single screen.
• The 7 lifecycle method of Activity describes how activity will behave
at different states.
06/08/2024 104
06/08/2024 105
Moving To another activity
1.intent intent=new Intent(MainActivity.this,SecondActivity.class);
2.startActivityForResult(intent, 2);// Activity is started with requestCode
2
06/08/2024 106
#1 - Bluetooth App
• To develop this app:
o Introduction Bluetooth API in Android
o Methods and constants used in Bluetooth API
o Starting the program
o Sample Codes
o Result
06/08/2024 107
Introduction to Bluetooth API
• Bluetooth is a way to send and receive data between two different devices.
• It allows devices to wirelessly exchange data with other Bluetooth devices.
• Android provides Bluetooth API to perform these different operations.
o Switching ON / OFF the Bluetooth.
o Scan for other Bluetooth devices
o Get a list of paired devices
o Connect to other devices through service discovery
• Android provides BluetoothAdapter class to communicate with Bluetooth.
• Create an object of this calling by calling the static method getDefaultAdapter().
• Syntax:
BluetoothAdapter bluetoothAdapter_Name;
bluetoothAdapter_Name = BluetoothAdapter.getDefaultAdapter();
06/08/2024 108
Introduction to Bluetooth API, Cont. …
• In order to enable the Bluetooth of your device, call the intent with the following
Bluetooth constant ACTION_REQUEST_ENABLE.
• Syntax: Intent Intent_Name = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(Intent_Name, 0);
• Once you enable the Bluetooth, you can get a list of paired devices by calling
getBondedDevices() method.
• It returns a set of Bluetooth devices.
• Syntax:
private Set <BluetoothDevice> pairedDevices_Name;
pairedDevices_Name = bluetoothAdapter_Name. getBondedDevices();
• There are many other constants that used to develop a BLUETOOTH app.
• Here it is as shown in next slide of the table.
06/08/2024 109
Constants to Develop Bluetooth
• a
06/08/2024 110
Bluetooth App
• In this, we will consider only switching ON and OFF the Bluetooth.
o Two Button (one for ON and other for OFF) – to switch ON & OFF
06/08/2024 111
Steps of the Code:
• The developing steps are as follows:
6. Throwing the Action Listener for the buttons. We need to use “ShowToast” and “Intent” and define as a
method. Apply the ImageView within. (Right click on Drawable New Image Asset Change the
“Icon Type” to “Action Bar and Tab Icons” Asset Type “Clip Art” Click on “Clip Art” icon
Select the icon you need Change the “Theme to Custom Next Finish).
06/08/2024 112
#1 - Bluetooth, Cont. …
• Add the following permissions in the manifests source code to develop a Bluetooth
applications.
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
• Go to the “res layout activity_main.xml”, in the text part of the file and write
the following source codes.
06/08/2024 114
Bluetooth, Cont. …
•<!--
Cont.
ON…Button -->
<Button
android:id="@+id/onBtn“
android:text="Turn On"
android:minWidth="200dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/Base.Widget.AppCompat.Button.Colored"
/>
<!-- Off Button -->
<Button
android:id="@+id/offBtn“
android:text="Turn Off"
android:minWidth="200dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/Base.Widget.AppCompat.Button.Colored"
/>
06/08/2024 115
Bluetooth, Cont. …
• Cont. …
onBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(bluetoothAdapter.isEnabled()){
showToast("Bluetooth is already ON.");
}
else{
showToast("Turning on Bluetooth ...");
imgIconView.setImageResource(R.drawable.ic_action_on);
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 0);
}
}
});
06/08/2024 116
Bluetooth, Cont. …
• Cont. …
offBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(bluetoothAdapter.isEnabled()){
bluetoothAdapter.disable();
imgIconView.setImageResource(R.drawable.ic_action_off);
showToast("Turning OFF Bluetooth ...");
}
else{
showToast("Bluetooth is already OFF.");
}
}
});
06/08/2024 117
Bluetooth, Cont. …
• Cont. …
private void showToast(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
06/08/2024 118
#2 - Phone Call App
• It is used to give an option to your user to make a call using a hard coded phone
number.
• The Intent is used to make phone call by calling built-in Phone Call functionality of
the Android
Action or
No Description
Data/Type
It is used to trigger built-in phone call functionality available in Android
1. ACTION_CALL device.
Syntax: Intent Intent_Name = new Intent(Intent.ACTION_CALL);
2. ACTION_DIAL It is used to provide an option to modify hardcoded phone number before
making a call instead of making a direct call.
3. setData() It is used to make a phone call at a given number, by specifying tel: as URI
using setData().
Syntax: phoneIntent.setData(Uri.parse(tel:”+phone_number”);
06/08/2024 119
Phone Call App, Cont. ..
• Steps:
1. Create a new project.
2. Add “CALL_PHONE” & ”READ_PHONE_STATE” permissions in the
AndroidManifest.xml.
3. Use one EditText and one ImageView.
4. Declare and initialize in java source code.
5. Throw an ActionListener on the ImageView. Use Intent within and call
“ACTION_CALL” or “ACTION_DIAL” constant.
6. Handle the permission by using exceptional handling methods.
7. Run and see the result.
06/08/2024 120
#3 - SMS App
• SMS – Short Message Service
• There are two ways to develop to send SMS using Android device:
1) Using Built-in Intent to send SMS
2) Using SmsManager to send SMS
Using Built-in Intent to send SMS
• Android built-in Intent is used to send SMS by calling built-in SMS functionality of the
Android.
• ACTION_VIEW action is used to launch an SMS client installed on your Android device.
• Syntax:
Intent smsIntent_Name = new Intent(Intent.ACTION_VIEW);
• To send an SMS you need to specify smsto: as URI using setData() method and data type will
be to vnd.android-dir/mms-sms using setType() method.
• Syntax:
smsIntent_Name.setData(Uri.parse("smsto:"));
smsIntent_Name.setType("vnd.android-dir/mms-sms");
06/08/2024 121
SMS App, Cont. …
• The built-in putExtra() method is used to add phone number and text message to
send an SMS.
• Syntax:
smsIntent_Name. putExtra("sms_body" , getTextView);
smsIntent_Name. putExtra("address" , getTextView));
• Steps of developing the apps:
1. Use two TextView, two EditText and one ImageView.
2. Declare and initialize EditText and ImageView.
3. Throw the ActionListener on ImageView. Also, implement the Intent and SMS
methods.
4. Run and see the result.
06/08/2024 122
(Option-2-): SMS App, Cont. …
Using SmsManager to send SMS
• The SmsManager manages SMS operations such as sending data to the given mobile
device.
• You can create this object by calling the static method SmsManager.getDefault()
• Syntax:
SmsManager SmsManager_Name = SmsManager.getDefault();
• Once you have SmsManager object, you can use sendTextMessage() method to send
SMS.
• Syntax: SmsManager_Name.sendTextMessage(destAddress, srcAddress, message,
senderPendingIntent, receiverPendingIntent);
06/08/2024 123
SMS App, Cont. …
• Syntax:
PendingIntent sentPIName, deliveredPIName;
sentPIName = PendingIntent.getBroadcast(Context contextName, int
requestCodeValue, new Intent intentName, int flags);
deliveredPIName = PendingIntent.getBroadcast(Context contextName, int
requestCodeValue, new Intent intentName, int flags);
• PendingIntent - is an intent that will perform at a later time or specifies an action to take in
future.
o It must need a regular intent to be created, but not vice-versa.
• BroadcastReceiver - is an Android component which allows you to register for system or
application events.
o All registered receivers for an event are notified by the Android runtime once this event
happens.
06/08/2024 124
#4 - Sending Email App
• ACTION_SEND constant action is used to launch an email client installed on your
Android device.
• To send an email you need to specify mailto: as URI using setData() method and data
type will be to text/plain using setType() method.
• Syntax: email_Intent_Name.setData(Uri.parse("mailto:"));
email_Intent_Name.setType("text/plain");
06/08/2024 125
Sending Email App, Cont. …
• Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be
attached to the intent before sending the intent to a target email client. They are
1. EXTRA_BCC – is a String[] holding e-mail addresses that should be blind carbon copied.
2. EXTRA_CC – is s String[] holding e-mail addresses that should be carbon copied.
3. EXTRA_EMAIL – is a String[] holding e-mail addresses that should be delivered to.
4. EXTRA_SUBJECT – is a constant string holding the desired subject line of a message.
5. EXTRA_TEXT – is a constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.
6. EXTRA_HTML_TEXT – is an alternative to step (5).
7. EXTRA_TITLE – is a CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.
06/08/2024 126
Sending Email App, Cont. …
• Syntax:
06/08/2024 127
#5 - Display one Activity into Another
• It is a chat application message transfer functions.
• This is used to send one data from activity to another activity.
• Steps to open one activity into another:
1) Open the first activity with one “TextView” and one “Button”
2) Open the 2nd activity. (Right click on the package of the java that contains the
“MainActivity New Activity Empty Activity).” We need only one
“TextView” in the “activity_main2.xml”
3) Call the 2nd activity name in the 1st activity of the java source code.
4) Run and see the result.
06/08/2024 128
#6 - Audio Capture App
• This app can easily control your ringer volume and ringer profile i.e. (silent, vibrate,
loud etc.) in android.
• Android provides AudioManager class that provides access to these controls.
• Create an object of AudioManager class by calling the getSystemService() method
to use it.
• Syntax:
audioManagerName. setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
06/08/2024 129
Audio Capture App, Cont. …
• The method setRingerMode takes an integer number as a parameter.
• For each mode, an integer number is assigned that will differentiate between different
modes. The possible modes are.
1. RINGER_MODE_VIBRATE – sets the device at vibrate mode.
2. RINGER_MODE_NORMAL – sets the device at normal (loud) mode.
3. RINGER_MODE_SILENT – it sets the device at silent mode.
4. MODE_RINGTONE – it sets the device at ring mode.
• Once the mode has set, by calling the getRingerMode() method the state of the
system can be set.
• Syntax:
int modeName = audioManagerName.getRingerMode();
06/08/2024 130
Audio Capture App, Cont. …
• Steps of developing the app:
1. Create a new project.
2. Specify one TextView and four (4) Button.
3. Declare the palette and AudioManager globally and initialize them.
4. Throw an ActionListener on each of the Button and make the status of the action
to be displayed on TextView by using any of the control structures.
5. Run and see the result.
06/08/2024 131
#7 - Camera App
• These are the following two ways, in which you can use camera in your application
1. Using existing android camera application in our application
• Syntax:
Intent intentName = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
06/08/2024 132
Camera App, Cont. …
• There are other available Intents provided by MediaStore develop camera apps:
1. ACTION_IMAGE_CAPTURE_SECURE – It returns the image captured from
the camera, when the device is secured.
2. ACTION_VIDEO_CAPTURE – it calls the existing video application in android
to capture video.
3. EXTRA_SCREEN_ORIENTATION – is used to set the orientation of the screen
to vertical or landscape.
4. EXTRA_FULL_SCREEN – is used to control the user interface of the
ViewImage.
5. INTENT_ACTION_VIDEO_CAMERA – is used to launch the camera in the
video mode.
6. EXTRA_SIZE_LIMIT – is used to specify the size limit of video or image capture
size.
06/08/2024 133
Camera App, Cont. …
• The method startActivityForResult() or startActivity() is used to launch this
activity and wait for its result.
• Syntax:
startActivityForResult(intentName,0); OR startActivity(intentName);
• Steps of developing an Apps:
1. Create a new project.
2. Add in AndroidManifest.xml the following line of code.
<uses-feature android:name="android.hardware.camera2" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
3. Use only one ImageView and include image as “src”.
4. Throw an ActionListener on the ImageView, create Intent and use important
constants.
5. Run and see the result.
06/08/2024 134
#8 - Google Map App
• You can able to show any location or routes on the map.
• Google provides this facility using Google Play Services library which you have to
download externally and integrate it with your project.
• In the end you have to integrate your application with google via Google Console.
Google Map - Activity File
• Google provides GoogleMap and MapFragment API to integrate map in your
android application.
• In order to use GoogleMap, you have to create an object of GoogleMap and get the
reference of map from the xml layout file.
• Syntax:
GoogleMap googleMapName;
googleMapName = ((MapFragment)
getFragmentManager().findFragmentById(R.id.fragment_ID)).getMap();
06/08/2024 135
Google Map App, Cont. …
Google Map - Layout File
• The following map fragment should be include into xml layout file.
• Syntax:
<fragment
android:name="com.google.android.gms.maps.MapFragment"
/>
06/08/2024 136
Google Map App, Cont. …
Google Map – AndroidManifest.xml File
• The following permissions should be added along with the Google Map API key in
the AndroidManifest.xml file.
• Syntax: <!--Permissions-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--Google MAP API key-->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0"
/>
06/08/2024 137
Google Map App, Cont. …
Adding Marker
• You can place a marker with some text over it displaying your location on the map.
06/08/2024 138
Google Map App, Cont. …
Changing Map Type
• You can also change the type of the MAP.
• There are four different types of map and each give different view of the map.
• These types are
• Normal,
• Hybrid,
• Satellite and
• terrain.
• The way to use: googleMapName.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMapName.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMapName.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMapName.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
06/08/2024 139
Google Map App, Cont. … (Enable/Disable zoom)
• You can also enable or disable the zoom gestures in the map by calling the
setZoomControlsEnabled(boolean) method.
• Syntax:
googleMapName.getUiSettings().setZoomGesturesEnabled(true);
• The methods used in GoogleMap to customize.
06/08/2024 140
Google Map App, Cont. …
No. Methods Description
7. It repositions the camera according to the
moveCamera(CameraUpdate update)
instructions defined in the update.
8. setTrafficEnabled(boolean enabled) It toggles the traffic layer on or off.
9. snapshot(GoogleMap.SnapshotReady It takes a snapshot of the map.
Callback callback)
10. It stops the camera animation if there is one in
stopAnimation()
progress.
06/08/2024 141
Google Map App, Cont. …
Obtaining the API key
• This part is further divided into two steps. First you have to get an SHA1 fingerprint
key from your pc and then you have to get map API key from google console.
Getting Certificate from KeyTool
• You need to get a certificate key because you have to provide it to google console in
order to get your API key for map.
• Open your command prompt and move to the path where your java jre has been
placed.
• Now type this command.
• Copy the SHA1 key because you need it in the next step.
06/08/2024 142
Google Map App, Cont. …
Getting key from Google Console
• Open Google Console and sign in by clicking a new project.
• Click on services from the left tab and then navigate to the Google Maps Android API
v2.
• You have to turn them on like this
• Now again go to the left tab and select API access. And click on create new android
key.
• Now paste the key that you copied and put a semicolon and paste your project name
and click create.
06/08/2024 143
Google Map App, Cont. …
• It would be like this and now copy the API key that has been given to your by
android, because you have to paste it into your manifest file.
06/08/2024 144
Google Map App, Cont. …
Specify Android Manifest Settings
• The final step is to add the API key to your application.
• Open your manifest file and place this code right before closing the application tag.
• Syntax:
<meta-data
android:name="com.google.android.maps.v2.API_KEY“
android:value="API_KEY“
• In the second line replace API_KEY with your API key and you are done.
/>
• You need to add some permissions in your manifest too.
06/08/2024 145
Google Map App, Cont. …
• Steps:
1. Create “New Project”.
2. Add the “com.google.android.gms:play-services-maps:11.0.4” in the
dependencies the project structure.
3. Add the permissions and API Key in the AndroidManifest.xml.
06/08/2024 146
#9 - SQLite Database
• SQLite is an open source SQL database that stores data to a text file on a device.
• To access this database, you don't need to establish any kind of connections for it like
Database Package
• The main package is android.database.sqlite that contains the classes to manage your
own databases.
06/08/2024 147
SQLite Database, Cont. …
Database Creation:
• It returns an instance of SQLite database which you have to receive in your own
object.
• Syntax:
SQLiteDatabase databaseName = openOrCreateDatabase(“Your DB name", MODE_PRIVATE, null);
06/08/2024 148
SQLite Database, Cont. … (Methods)
1. openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
DatabaseErrorHandler errorHandler)
o This method only opens the existing database with the appropriate flag mode.
o The common flags mode could be OPEN_READWRITE OPEN_READONLY.
2. openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
o It is similar to the above method as it also opens the existing database but it does
not define any handler to handle the errors of databases.
3. openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
o It not only opens, but creates the database if it does not exists.
o This method is equivalent to openDatabase method.
4. openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
o This method is similar to above method but it takes the File object as a path rather
than a string.
o It is equivalent to file.getPath()
06/08/2024 149
SQLite Database, Cont. …
Database - Insertion
• We can create table or insert data into table using execSQL method defined in
SQLiteDatabase class.
• Syntax:
databaseName.execSQL("CREATE TABLE IF NOT EXISTS tableName(Column1,
Column2, …);");
databaseName.execSQL("INSERT INTO tableName
VALUES(‘Column1Value’, ‘Column2Value');");
Other Method
• execSQL(String sql, Object[] bindArgs)
o This method not only insert data, but also used to update or modify already existing data
in database using bind arguments
06/08/2024 150
SQLite Database, Cont. …
Database - Fetching
• We can retrieve anything from database using an object of the Cursor class.
• We will call a method of this class called rawQuery and it will return a resultset with
the cursor pointing to the table.
• We can move the cursor forward and retrieve the data.
• Syntax:
Cursor resultSet = databaseName.rawQuery("Select * from tableName", null);
resultSet.moveToFirst();
String column1 = resultSet.getString(1);
• There areString
othercolumn2
methods= resultSet.getString(2);
available in the Cursor class that allows us to effectively
retrieve the data. That includes-
06/08/2024 151
SQLite Database, Cont. …
1. getColumnCount() – this method returns the total number of columns of the table.
2. getColumnIndex(String columnName) – this method returns the index number of
a column by specifying the name of the column.
3. getColumnName(int columnIndex) – this method returns the name of the column
by specifying the index of the column.
4. getColumnNames() – this method returns the array of all the column names of the
table.
5. getCount() – this method returns the total number of rows in the cursor.
6. getPosition() – this method returns the current position of the cursor in the table.
7. isClosed() – this method returns true if the cursor is closed and returns false
otherwise.
06/08/2024 152
SQLite Database, Cont. …
Database - Helper class
• For managing all the operations related to the database, a helper class has been given
and is called SQLiteOpenHelper.
• It automatically manages the creation and updating of the database.
• Syntax:
06/08/2024 153
Example – Login App
• c
06/08/2024 154
Login App (steps):
1. Create a new project with and name it as “LoginAppA”
2. Use two “EditText” (for username and password), and one “Button” (for login).
3. Declare and initialize the palette.
4. Create a SECOND Activity that helps you validate your login.
5. Throw the ActionListener on the “Button”. Use the control structure to validate
your login and Intent to start the app.
6. Create a SQLite database with a class name as “ConnectDatabase”. (Right click
on java package name New New Class). Then, extends
SQLiteOpenHelper
7. If you will get an error line of code, click on the bulb icon and implement methods,
i.e.
06/08/2024 155
Login App (steps), Cont. …
8. Again, if there is an error in class line of code, click on bulb icon and “create
constructor matching super”
DATABASENAME LoginAppA.db
TABLENAME App
USERNAME Name
USERPASSWORD
Make all of as Password
public static final String …..
06/08/2024 156
Login App (steps), Cont. …
10. Add only one argument for the “constructor” and its super, as follows.
06/08/2024 157
Login App (steps), Cont. …
15. Run the application.
16. Open the “Tools Android Device Monitor” File Explorer data data
open your app name open databases select your database name click
pull a file from the device and save it.
17. To know whether it is created or not, install SQLite Manager into your PC.
18. Open the file.
19. Insert data into the table by adding a separate method for data insertion and call it in
the MainActivity.java class of thrown ActionListener with the instance name of the
database.
20. Run and see the result.
06/08/2024 158
Login App (steps), Cont. …
• The result seems as follows:
06/08/2024 159
Thanks!
06/08/2024 160
Google Map App - Reference
• https://developers.google.com/maps/documentation/android-sdk/start
• http://www.androiddocs.com/google/play-services/setup.html
• Externally add:
1. Google Play Services
2. Google Repository
06/08/2024 161
SMS App - References
• https://www.brainbell.com/android/activities.html
• https://developer.android.com/reference/android/app/Activity
• https://www.oreilly.com/library/view/head-first-android/9781449362171/ch04.html
• https://www.androidauthority.com/android-app-lifecycle-879968/
• https://www.javatpoint.com/android-life-cycle-of-activity
• http://www.vogella.com/tutorials/AndroidLifeCycle/article.html
06/08/2024 162
Thanks!!!
06/08/2024 163