References Mad Lab Manual
References Mad Lab Manual
in
Table of Contents
1. Introduction to Android
1.1 Android
1.2 Development Environment
1.3 Creating an App in Android Studio
1.4 Anatomy of Android Project
1.5 Running the First App
1.6 Ingredients of an Android App
5. Graphical Primitives
5.1 Running the Graphical Primitives App
7. Multithreading
7.1 Media Player API
7.2 Android Camera API
7.3 Running the Multithreading App
Objectives
After completing this chapter we will be able to understand the following topics.
• Android Introduction
• Development Environment
• Creating an App in Android Studio
• Anatomy of Android Project
• Running the First App
• Ingredients of an Android App
It was originally developed by a startup of the same name, Android, Inc. In 2005, as part of
its strategy to enter the mobile space, Google purchased Android and took over its
development work. Google wanted Android to be open and free; hence, most of the Android
code was released under the open source Apache License, which means that anyone who
wants to use Android can do so by downloading the full Android source code.
The main advantage of adopting Android is that it offers a unified approach to application
development. Developers need only develop for Android, and their applications should be able to
run on numerous different devices, as long as the devices are powered using Android.
Android Versions
Android has gone through quite a number of updates since its first release. The follow table
shows the various versions of Android and their codenames.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Features of Android
As Android is open source and can be customized by the manufacturers, there are no fixed
hardware or software configurations. Android itself supports the following features:
Android Architecture
Linux Kernel
Since the android architecture is built on top of Linux Kernel, the Kernel is used as a hardware
abstraction layer. i.e, It can be used as an abstraction layer between hardware and software. For
example, consider the battery function. The devices which run on android will have hardware
component like camera, blue tooth, battery etc. The power management interface from the Kernel
will interact with the battery (hardware). There is a list of low level interfaces provided by the
Kernel such as camera driver, audio drivers, memory management, display driver etc.
Libraries
The libraries are the APIs which contains the features of android operating
system. Android Runtime Contains two elements
Dalvik Virtual Machine
Core Libraries
The role of Dalvik virtual machine is similar to java virtual machine. While java virtual
machine executes byte code, on the other side, in android programming Dalvik virtual
machine executes Dalvik byte code (.dex files).
cseitquestions.blogspot.in cseitquestions.blogspot.in
Core Libraries
Core libraries are core API s of java programming language which provides powerful
interfaces for implementing file access, network access, utility, data structures etc.
Application Framework
The application framework contains libraries for various areas like power management, multimedia,
storage access and graphical user interface. The libraries in the framework are written in Java and
run on top of the core libraries of the Android Runtime. The application framework of android provides
managers for various purposes such as resources handling, content providers, system wide
notification etc. The android applications are using the services of these managers.
Application
On Android, every application runs in its own process, each of which runs in its own virtual
machine (VM). Applications are the android applications which are executed on a device.
The applications are the top layer in the android architecture. This layer will consists of pre-
installed and our own applications. The android application we develop goes into this layer.
AVD Manager
The AVD Manager stands for Android Virtual Device Manager. As the name implies, the
AVD Manager is used for creating and managing Android Virtual Devices.
Emulator
This is one of the most important tools provided by android SDK. The emulator is a virtual
mobile device that runs on the computer. It can be used to test our android applications. It
allows the developer to test and run the android applications without using a physical mobile
device during development stage. The emulator for each android project can be configured
with the help of Android Virtual Device (AVD) Manager.
Systrace
The Systrace tool helps analyze the performance of our application by capturing and displaying
execution times of our applications processes and other Android system processes. The tool
combines data from the Android kernel such as the CPU scheduler, disk activity, and application
threads to generate an HTML report that shows an overall picture of an Android device‘s system
processes for a given period of time. The Systrace tool is particularly useful in diagnosing display
problems where an application is slow to draw or stutters while displaying motion or animation.
Device Monitor
Android Device Monitor is a stand-alone tool that provides a graphical user interface for
several Android application debugging and analysis tools. It encapsulates the following tools:
• DDMS
• Tracer for OpenGL ES
• Hierarchy Viewer
• Systrace
• Traceview
b) Platform Tools
The platform tools are generally updated each time we install a new SDK platform. Each
update of the platform tools is backward compatible with older platforms. Usually, we directly
use only one of the platform tools—the Android Debug Bridge (adb). The other platform
tools, such as aidl, aapt, dexdump, and dx, are typically called by the Android build tools or
Android Development Tools (ADT), so we rarely need to invoke these tools directly.
Android Debug Bridge controls both emulators and devices. It allows us to install and
remove programs in emulators and android devices. Simply it acts as bridge between the
system and the android device to establish communication between them. Through this
communication we can get connected to the android device and we can perform the actions
such as moving and synchronising the files to the device, reading the device memory usage
etc. Actually it is a command line tool. The complex commands can be executed through
command line mode using the commands available for ADB.
DX.exe
The DX.exe file is one of the most useful tools. These .dex files are understood by android devices.
The DX.exe works as compiler of the android SDK. It creates .dex extensions files when we are
running the java files. The .java files written in IDE, are compiled with the help of java compiler. The
byte code files are read and converted as .dex (dalvik executable) format by DX tool.
While writing java programs, the code is compiled into byte code and jvm executes that byte
code. On the other side, in android programming we still write java code and it is compiled to
a byte code format. Finally the byte code is converted to Dalvik executable format (.dex).
This .dex files are read by the Dalvik virtual machine.
ADT provides GUI access to many of the command line SDK tools as well as a UI design
tool for rapid prototyping, designing, and building our application's user interface.
integrated tool from the Android Studio menu and independently from the command line.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Android Studio provides a memory monitor view so the app's memory usage such as to find
deallocated objects, locate memory leaks and track the amount of memory the connected
device is using can be monitored. Some of the features of android studio are given below.
In the dialog box, it prompts for the project name which is indicated as application name.
cseitquestions.blogspot.in cseitquestions.blogspot.in
The package name is the name of the package where our application code resides. Android
Studio provides default package name. If we wish to change the default package name, we
can use the edit option given along the package name. The project location is the Android
Studio workspace where all our android projects are getting stored. We can change the
project location if we desire to choose different location.
After filling the fields, click next to proceed. The next option is choosing the app type. i.e the
target device type such as phone or tablets or tv etc. Also choose the minimum API level which
requires running our app. After choosing the minimum SDK version click next to proceed.
The next option is choosing an activity type. Since each app at least would have one activity, Android
Studio provides options to choose an activity type while creating project. We can choose any type of
activity we want from the given activity types. In this demo, we will choose ‗Blank Activity‘ type. To
proceed with next step click next option. Then a dialog box will appear as shown in the below picture.
cseitquestions.blogspot.in cseitquestions.blogspot.in
The last step in creating project is providing names for activity, layout and menu. The activity
name we provide is the name of the activity file which is created under src directory.
1. .idea
2. app
3. build
4. gradle
5. External Libraries
6. Other files ( .gitignore, build.gradle ,gradle.properties,
gradlew, gradlew.bat, local.properties,
MyApplication2.iml, settings. gradle)
Main Project
This would be entire project context. A project is an organizational unit
that represents a complete software solution. In the above screenshot
―MyApplication2‖ is the name of the project we have created.
Note:
This means that, in theory it is possible to build multiple apps within the same project. Creating
multiple apps within the same project doesn‘t work well. So, it is recommended that not making our
hands dirty trying the same thing. Instead, it is a better idea to create single app per single project.
1. .idea
It is the folder for IntelliJ IDEA settings. The .idea folder is created
for storing project specific metadata. This means the project
specific metadata is stored by Android Studio. In Eclipse the
project. properties file does the same thing. The .idea folder
contains sub folders copyright, libraries, scopes and files such as
.name and xml files.
2. app
This is the actual project folder where our application code
resides. The application folder has following sub directories.
a) build: This has all the complete output of the make process i.e. classes.dex, compiled classes
and resources, etc. In the Android Studio GUI, only a few folders are shown. The important
part is that the R.java is found under build/source/r/<build variant>/<package>/R.java
cseitquestions.blogspot.in cseitquestions.blogspot.in
b) libs : This folder holds the libraries or .jar files. It contains private libraries.
c) src: The src folder can have both application code and android unit test script.
resources, such as drawable files, layout files, and string values, and manifest file.
app/src/androidTest
The test projects are now automatically part of the app source folder. When a new application
module is created, Android Studio creates the src/androidTest . This contains tests for the default
configuration and is combined with the debug build type to generate a test application.
These test projects contain Android applications that we write using the Testing and
Instrumentation framework. The framework is an extension of the JUnit test framework and
adds access to Android system objects.
app/src/main
The main/ folder contain the following list of directories and files.
• java/
• res/
• AndroidManifest.xml
cseitquestions.blogspot.in cseitquestions.blogspot.in
The app/src/main/java folder contains the java code for the application. Our app activities
code resides in this folder.
The app/src/main/res folder contains resources for our application. We should always
externalize application resources such as images and strings from our code, so that we can
maintain them independently. At runtime, Android uses the appropriate resource based on
the current configuration. For example, if we need to provide a different UI layout depending
on the screen size or different strings depending on the language setting we have to provide
them in the resource file. The app/src/ main/res folder contains the following sub directories.
o drawables
o layout
o menu
o values
o AndroidManifest
drawables - For bitmap files (PNG, JPEG, or GIF), 9-Patch image files, and XML files
that describe Drawable shapes or Drawable objects that contain multiple states.
layout - Contains XML files that are compiled into screen layouts (or part of a screen). The
layout resource defines the architecture for the UI in an Activity or a component of a UI.
menu
- Contains XML files that define application menus. The menu resource defines an
application menu such as options menu, context menu, sub menu etc.
values - For XML files that define resources by XML element type. Unlike other resources in the
res/ directory, resources written to XML files in this folder are not referenced by the file name.
Instead, the XML element type controls how the resources defined within the XML files are
placed into the R class. The values directory contains the following three XML files.
o dimens.xml
o strings.xml
o styles.xml
AndroidManifest.xml - The control file that describes the nature of the application and each of its
components. For instance, it describes: certain qualities about the activities, services, intent
receivers, and content providers; what permissions are requested; what external libraries are
needed; what device features are required, what API Levels are supported or required;
and others. See the AndroidManifest.xml documentation for more information.
.gitignore/ - Specifies the untracked files ignored by git.app.iml/ - IntelliJ IDEA module
build.gradle - Customizable properties for the build system. You can edit this file to
override default build settings used by the manifest file and also set the location of our key
store and key alias so that the build tools can sign our application when building in release
mode. This file is integral to the project, so maintain it in a source revision control system.
cseitquestions.blogspot.in cseitquestions.blogspot.in
3. build
The build folder stores the build output for all project modules.
4. gradle
The gradle folder contains gradle wrapper files. This is where the
gradle build system‘s jar wrapper i.e. this jar is how Android
Studio communicates with gradle installed in Windows (the OS).
5. External Libraries
This is not actually a folder but a place where Referenced
Libraries and information on targeted platform SDK is shown.
6. Other files
.gitignore – Specifies the files that should be ignored by Git.
• build.gradle - This file contains properties for the build system. We can edit this file tospecify
the default build settings used by the application modules and also set the location of
our keystore and key alias so that the build tools can sign our application when
building in release mode. This file is integral to the project, so it must be maintained
in a source revision control system.
• gradle.properties - The gradle.properties file contains project-wide Gradle settings.
• Gradlew - The gradlew file is the gradle startup script for Unix.
• gradlew.bat - The gradlew.bat file is the gradle startup script for Windows.
• local.properties - This file has the properties for the build system, such as the SDK
installation path. Since the content of the file is specific to the local installation of the
SDK, it should not be maintained in a source revision control system.
• .iml - The file with .ml extension stores the module information.
• settings.gradle - It specifies the sub-projects to build.
Android Studio provides tool bar option to open AVD Manager. Click
the Android Virtual Device Manager in the toolbar to open it and
create new virtual devices for running our app in the emulator.
cseitquestions.blogspot.in cseitquestions.blogspot.in
AVD Manager
AVD Manager has updated screens with links to help us select the most popular device
configurations, screen sizes and resolutions for our app previews. The AVD Manager comes
with emulators for Nexus 6 and Nexus 9 devices and also supports creating custom Android
device skins based on specific emulator properties and assigning those skins to hardware
profiles. Android Studio installs the Intel® x 86 Hardware Accelerated Execution Manager
(HAXM) emulator accelerators and creates a default emulator for quick app prototyping.
When the AVD Manager icon is selected, the following screen will be shown. This screen will
display list of created virtual devices or emulators with the option to create a new one.
To create a new emulator, click on the ‗Create Virtual Device‘ option. The following dialog
box will appear with the options to create a new one.
cseitquestions.blogspot.in cseitquestions.blogspot.in
The AVD shows the list of defined hardware profiles such as memory, screen size,
resolution etc. To define our own hardware profile, AVD Manager provides an option called
‗New Hardware Profile‘. Also we can import the hardware profiles. The following screen
shows the option to create new hardware profiles.
We have created an android application. To run that application we have created a virtual device.
Now select the run option to run the application. When choosing the run option, a dialog box will
appear with the option to launch an emulator or choose the existing (already launched or
running) emulator. The AVD Manager allows us to create any number of emulators with the
hardware profiles we want. The advantage is, while running an android app we can choose the
emulator to run. Emulators are not depending or specific to an android project or application.
The following screen shows the list of created emulators. If an emulator is created successfully,
then a run symbol will be shown along with edit and delete options. If the creation of emulator is
not successful, then finally the status of emulator will be displayed with error message.
cseitquestions.blogspot.in
cseitquestions.blogspot.in
In the above picture we are going to choose the ‗Launch emulator‘ option.
cseitquestions.blogspot.in cseitquestions.blogspot.in
The emulator appears with the typical mobile screen. We can watch that our app has been
installed. Now if we click on the app icon, it will be launched and the outcome is shown in the
above picture. The output is simply showing the text ‗Hello World‘.
Activity
Activity is an individual user interface where visual components can be placed. These visual
components are known as Views (also known as widgets). The user can perform various actions
by interacting with it. In an android application, the whole window gives the user an interface to
interact with and therefore this complete screen makes an Activity. The controls placed in the
window allow the user to perform certain actions and are called Views or Widgets.
An application can have more than one activity and each activity operates independently,
but can be linked to one another. Each activity must be defined in application‘s manifest file.
Each Activity in android will be subclass of Activity class defined in Android SDK.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Intent
Although intents are known as one among the components, actually it is not. It is used to activate
a component in an application. For example, in an android application when we want to open a
image or video, an option will be shown to the user to choose. The option is for mentioning how
to complete the opening action by using which editor the user wants to open.
Here opening of an image or a video is an activity. We want to start another activity called choose the
option. To invoke a new activity from our current activity, we need to fire an intent specifying the new
activity. And if we want to start other application from our activity, then also we need to fire intent.
That is by firing intent, we are telling the android system to make something happen.
Service
A service is an android application component that runs in background and has no visual UI.
Services are used to perform the processing parts of our application in the background.
While the user is working on the foreground UI, services can be used to handle the
processes that need to be done in the background. A service can be started by another
android application components such as an activity or other services and it will continue to
run in the background even after the user switches to another application. Thus services are
less likely to be destroyed by Android system to free resources, than Activities.
Broadcast Receiver
Broadcast receivers are one of android application components that is used to receive messages
that are broadcasted by the android system or other android applications. There are many
broadcasts that are initiated by the android system itself and other applications can receive by
using Broadcast receiver. Examples of broadcasts initiated by the system are:
Content Provider
Content providers in android provide a flexible way to make data available across applications.
For example, consider we are creating a to do list in our application, and we are storing it at any
storage location such as the data base, file system or in any online storage space. Now through
content providers other applications are able to access or even modify the data we have created.
In a similar way we can access the data that other utilities have created, by using content
providers. Example for content provider in android is the contacts database. The content provider
of contacts database allows other applications to query, read, modify and write the contacts info.
Android comes with several other built in Content providers that we can use in our application. All
content providers are implemented as a subclass of ContentProvider class.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Objectives
After completing this chapter we will be able to understand the following topics.
• Activity
• Life Cycle of an Activity
• Creating an Activity
• Intents
• Types of Intents
• GUI Components
• Fonts and Colors
2.1 Activity
Activity is the basic building block of any android application. Android applications contain one or
more Activities. The introduction of activity has been given in the previous chapter ‗Ingredients of
an android application‘. As we have seen earlier, android activity always has a user interface.
When user launches an application, a window will be displayed. The whole window provides the user
interface to the user, this screen makes an activity. . The controls placed in the UI allow the user to do
a certain action. The controls in an activity can be created in two different ways. They can be created
either by java code or by adding XML code to define the UI. The latter method is always preferred.
Activity stack
An android application usually contains lots of activities. We can navigate over these activities. When
a user starts an activity, android OS pushes that into a stack. If user starts another activity then first
activity goes down and newly started activity is added to the top of the stack. When user pushes back
button, then top activity is destroyed and the activity which is below the top activity is resumed.
Example:
For example, a user receives a message on android phone. Now consider the actions performed
by the user. By tracking those actions, we can understand how activity stack works. The user
views the list of messages in inbox is activity 1. The user opens a message for reading is Activity
2. If the user replies to that message that becomes activity 3. If the user presses back
button, then he gets activity 2 again. When he gets activity 2 again, the activity 3 is
destroyed. Together these groups of activities form a task.
cseitquestions.blogspot.in cseitquestions.blogspot.in
A task is a collection of activities that users interact with when performing a certain job. The
activities are arranged in a stack (the back stack), in the order in which each activity is opened.
A representation of how each new activity in a task adds an item to the back stack. When the
user presses the Back button, the current activity is destroyed and the previous activity resumes.
For example, a user is playing game in his mobile. During that time, he receives a call from
someone. When playing game, if the user receives a call the game is paused and the calling
window appears on top of the game screen. When the call ends, the user can resume the
game at the point where he left. Here game is an application. When that application is
interfered by any other activity or application, the state of the game application is saved.
How the game state is saved and resumed? There must be some technique to save the game
state. To handle such situations android provides activity lifecycle. The life cycle of an activity is
handled by a set of functions and they are invoked when something happens to the activity.
Activity States
An activity life cycle starts from creating an activity. A created activity, in a running
application can be in one of the following three states:
• Resumed – Activity is running or in active state, it is focused and the user can interact with it.
• Paused – Activity is not running or focused, it might be covered by another
activity, or is transparent)
• Stopped – Activity is stopped or not visible.
cseitquestions.blogspot.in cseitquestions.blogspot.in
When an activity goes from one state to another, the different life cycle methods are invoked
where we can fill in with our code.
onCreate
The onCreate() method is called when an activity is created for the first time. This method is
invoked only once during the entire lifecycle of an activity. To create an activity, we must
override the onCreate() method which is available in the class named Activity. Since this
method is called only once at the beginning of an activity it can be used for initialization.
As the onCreate() method is called while creating an activity, the method for setting the
activity layout setContentView() is always invoked inside of this method.
onStart:
The onStart() method is called after the creation of an activity and just before the activity
becomes visible to the user. This onStart() method can be called from two places - after
onRestart() and OnCreate(). i.e., after creating an activity to start it for a first time, or to
restart an activity. This onStart() method can also be used to reset any data of an activity.
onResume:
The onResume() method is called when our activity comes into the foreground, from the paused
state. We already discussed an example that receiving a call while playing game in a phone. In
that example, when the received call is ended the game is resumed. During that time (when
game is resumed), the game activity is on top of the activity stack, so that the activity is ready to
interact with user. onResume() is a good place to update the screen with new results.
onPause:
The onPause() method is invoked, when a new activity comes on top of the existing activity. Typically
anything that steals the user away from an activity will result in calling onPause() method. The
onPause() method can have the code for releasing resources, saving the application data, stopping
background threads etc. It is always guaranteed that whenever the activity is becoming invisible or
partially invisible, onPause() will be called. But once onPause() is called, android reserves the right to
kill our activity at any point. Hence we should not be relying on receiving any further events.
onStop:
The onStop() method gets called when an activity finishes its work or stopped by the user. We can
use this method to shut down when we need to create time intensive or CPU intensive operations.
cseitquestions.blogspot.in cseitquestions.blogspot.in
onRestart:
The onRestart() method is similar to onCreate(), but onRestart() is called only after onStop().
Through this method in an application, we can understand that whether the application is
starting a fresh or getting restarted. When an activity invokes onRestart(), the activity state is
stored and variables are reinitialised.
onDestroy:
This method is invoked at the last stage of an activity life cycle. When an activity is killed, the
onDestroy() method is invoked. For example consider that when the user presses back button on any
activity, the foreground activity gets destroyed and control will be returned to the previous activity.
Even though, we use always onPause() and onStop() to clean up resources, the onDestory()
allows our application to have another chance to do that before it exits. But there is no
guarantee that onDestroy() will be called. It will be called only when the system is low on
resources or user press the back button or if we use finish () explicitly in our code.
Process Lifecycle
The Android system attempts to keep application process around for as long as possible, but
eventually will need to remove old processes when memory runs low. As described in Activity
Lifecycle, the decision about which process to remove is intimately tied to the state of the user's
interaction with it. In general, there are four states a process can be in based on the activities
running in it, listed here in order of importance. The system will kill less important processes (the
last ones) before it resorts to killing more important processes (the first ones).
• The foreground activity (the activity at the top of the screen that the user is currently
interacting with) is considered the most important. Its process will only be killed as a
last resort, if it uses more memory than is available on the device. Generally at this
point the device has reached a memory paging state, so this is required in order to
keep the user interface responsive.
• A visible activity (an activity that is visible to the user but not in the foreground, such as one
sitting behind a foreground dialog) is considered extremely important and will not be killed
unless that is required to keep the foreground activity running.
• A background activity (an activity that is not visible to the user and has been paused) is no
longer critical, so the system may safely kill its process to reclaim memory for other foreground or
visible processes. If its process needs to be killed, when the user navigates back
to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called
with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it
can restart itself in the same state as the user last left it.
Sometimes an Activity may need to do a long-running operation that exists independently of the
activity lifecycle itself. An example may be a camera application that allows you to upload a
picture to a web site. The upload may take a long time, and the application should allow the user
to leave the application will it is executing. To accomplish this, your Activity should start a Service
in which the upload takes place. This allows the system to properly prioritize your process
(considering it to be more important than other non-visible applications) for the duration of the
upload, independent of whether the original activity is paused, stopped, or finished.
3. Creating an Activity
Creating an activity class is as simple as creating a class in java. It simply involves creating
a class and overriding a method. To create an activity, we need to extend the Activity class
which is available in the android.app package. The onCreate() method must be overridden in
order to create a new activity. The example code gives an understanding of creating an
activity class and event handling in android. In an android project,
• Create an xml file under layout folder which is available in app/src/main/res
• Create an activity class under app/src/main/java folder
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_marginTop="37dp"
android:layout_centerHorizontal="true"
android:height="30dp" android:width="50dp"
android:background="#ff76ffa6" />
For each control an id is given which will be used as a reference to that control in code.
Here the attribute android:id contains the id for the control EditText.
The code for the controls is placed inside opening and closing layout tag. The layout tag
looks like as follows.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingLeft="@dimen/
activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
cseitquestions.blogspot.in cseitquestions.blogspot.in
There different types of layouts available such as relative layout, linear layout, grid layout
etc. The layouts are covered in detail in the user interface chapter. After creating the layout
xml file, we need to create activity class.
Activity class
We have created an activity class called MainActivity by extending the Activity class. Using
this activity we are going to perform addition of two numbers. To add two numbers we will
get input through text boxes and one button to perform the action. Finally to display the
result one text box or label we can have. The Button, EditText and TextView controls are
available in android.widget package.
Example
The onCreate() method is overridden. If we notice that the onCreate() method is having a
parameter Bundle type. Bundle is typically used to store the state of the Activity. Consider
the example screen rotation, during which the Activity gets killed or paused and onCreate()
is called again. We can determine if the Activity was already there, using Bundle so that you
do not have to create the Activity again.
To more elaborate, consider the screen rotation example. If a user has already filled some of the
fields and suddenly rotates his screen, the values filled in will be lost. Using Bundle, android
retains the values of these fields and re-populates the data after rotation automatically. The value
of Bundle will always be null when Activity is getting created for the first time. Always the
setContentView() method is called to display the user interface (to set the layout and controls for
activity). This method receives the layout xml file is as a parameter R.layout. activity_main.
Now the controls in the code must be linked to the controls in the xml file. In order to do that,
we call findViewById() method. This method is used for identifying the controls in the layout
file by their attribute named id. Since the return type of finViewById() does not match with
the controls type, they have type casted. The R is a class which stands for resources. It is
automatically generated and cannot be modified.
cseitquestions.blogspot.in cseitquestions.blogspot.in
After creating the UI, it is time to make work them. To perform event handling we need to
implement the listener interface and add the listener to the button control.
button.setOnClickListener(this);
Now if any click event happens on the button, the button is notified by the listener. To handle the
event, the code is written inside the event handler which is shown below.
Example
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://
schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/
editText" android:layout_marginTop="37dp"
android:layout_centerHorizontal="true"
android:height="30dp"
android:width="50dp"
android:background="#ff76ffa6" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Enter
the number1" android:id="@+id/textView2"
android:layout_alignTop="@+id/editText"
cseitquestions.blogspot.in
cseitquestions.blogspot.in
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="@+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Enter
the number2" android:id="@+id/textView3"
android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@
+id/editText2" android:layout_alignTop="@+id/
textView3" android:layout_alignLeft="@+id/editText"
android:layout_alignStart="@+id/editText"
android:width="50dp" android:height="30dp"
android:background="#ff6fffab" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" android:id="@+id/button"
android:layout_below="@+id/editText2"
android:layout_alignRight="@+id/editText2"
android:layout_alignEnd="@+id/editText2"
android:layout_marginTop="45dp" />
<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Result"
android:id="@+id/textView4" android:layout_below="@+id/button"
android:layout_alignRight="@+id/editText2" android:layout_alignEnd="@+id/
editText2" android:layout_marginTop="85dp" />
</RelativeLayout>
cseitquestions.blogspot.in cseitquestions.blogspot.in
MainActivity.java
Output
2.2 Intents
Actually intents are not one of android application components; but used for activating
components in Android. It is the part of core message system in android. It defines a
message to activate the target component. For example, if we want to invoke a new activity
from our current activity, then we need to fire an intent specifying the new activity. Further if
we want to start another application from our activity, then also we require intent.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Intent is a messaging object that can be used to request an action from another app
component. Although intents facilitate communication between components in several ways,
there are three fundamental use-cases:
• Activity
• Service
• Broadcast
Starting activities
We may want to start another activity from the existing one either as a new activity on top of
the activity stack or as a result back from the previous one. For example, if we start an
activity which allows the user to pick a person from a list of contacts, it returns the person
that was selected when selection completed i.e end of previous activity.
• startActivity(Intent)
• startActivityForResult(Intent, int)
The startActivity(Intent) method is used to start a new activity, which will be placed at the top
of the activity stack. It takes a single argument, an Intent, which describes the activity to be
executed. Sometimes we may want to get a result back from an activity when it ends. To
accomplish this, the startActivityForResult(Intent, int) method can be used. It is another form
of startActivity() method with a parameter identifying the call. The result will come back
through our onActivityResult(int, int, Intent) method.
To start an activity, the startActivity(intent) method will be invoked. This method is defined on
the Context object which Activity extends.
The following code demonstrates how another activity is started via intent.
Intents are covered in detail later on; however we need to use Intents in Activities. So we
cseitquestions.blogspot.in cseitquestions.blogspot.in
will explore briefly the concept of Intents.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Types of Intents
Intents have been classified into two types. They are
• Explicit Intents
• Implicit Intents
1) Explicit Intents:
Explicit intent is called for internal communication of an application. It is being invoked by mentioning
the target component name. The component or activity can be specified which should be active on
receiving the intent. For this reason mostly it is used for intra application communication. The
following code describes the way of creating an explicit intent. While creating explicit intent, the target
activity is specified so that the android system will invoke the activity.
Example
Activity1
int a,b,c;
a=Integer.parseInt(editText.getText().toString());
b=Integer.parseInt(editText2.getText().toString()); c=a+b;
Intent i=new Intent(this, MainActivity2.class);
i.putExtra(“result”,
c); startActivity(i);
Now the addition of two numbers program has been modified in order to use intent. In the
first activity, inside the onClick() method intent object is created. While creating intent object
the target component is specified that should be get activated. Here the MainActivity2 is the
target activity that will be invoked by this intent. Since intents are part of the core message
system of android, data is passed to the second activity ‗MainActivity2‘. i.e. input numbers
are read in the first activity, when the button is clicked intent object is created and the result
is passed through the intent object. It will activate the target activity. We will get the result in
the second activity. The code for second activity is given below.
Activity2
Bundle data=getIntent().getExtras();
if(data==null){
return; }
int myData=data.getInt("result");
cseitquestions.blogspot.in cseitquestions.blogspot.in
The second activity is activated by the intent object. Also the second activity receives data
or message from the first activity through intent object. The Bundle class is used to save the
activity state. So data from the intent object is read with the help of Bundle. The getIntent()
method will retrieve data from the intent object.
a) Component name - The name of the component to start. This is optional, but it's the
criticalpiece of information that makes an intent explicit, meaning that the intent should be
delivered
only to the app component defined by the component name. Without a component name,
the intent is implicit and the system decides which component should receive the intent
based on the other intent information (such as the action, data, and category).
b) Action - A string that specifies the generic action to perform (such as view or pick).
Somecommon actions for starting an activityare:
• ACTION_VIEW - This action is used in an intent with startActivity() when it has
some information that an activity can show to the user, such as a photo to
view in a gallery app, or an address to view in a map app.
• ACTION_SEND - Also known as the "share" intent, this intent is used with
startActivity() when some data that the user can share through another
app, such as an email app or social sharing app.
c) Data - The URI (a Uri object) that references the data to be acted on and/or the MIME type
ofthat data. The type of data supplied is generally dictated by the intent's action. For example,
if the action is ACTION_EDIT, the data should contain the URI of the document to edit.
d) Categories - A string containing additional information about the kind of component
thatshould handle the intent.
2) Implicit Intents:
When implicit intents are used, a message is sent to the android system
to find an appropriate activity to respond to the intent. For example, to
share a video, we can use intent. The video can be shared through any
type of external application. To do this we can use intent.
All user interface elements in an android app are built using View and ViewGroup objects. A
View is an object that draws something on the screen that the user can interact with. A
ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the
layout of the interface. All UI controls have attributes and id. Attributes are used to specify
values for the property of a UI control. The id for a UI control is used for referring the controls.
Attributes
Every View and ViewGroup object supports their own variety of XML attributes. Some attributes
are specific to a View object (for example, TextView supports the textSize attribute), but these
attributes are also inherited by any View objects that may extend this class. Some are common to
all View objects, because they are inherited from the root View class (like the id attribute). And,
other attributes are considered "layout parameters" which are attributes that describe certain
layout orientations of the View object, as defined by that object's parent ViewGroup object.
ID
Any View object may have an integer ID associated with it, to uniquely identify the View within
the tree. When the application is compiled, this ID is referenced as an integer, but the ID is
typically assigned in the layout XML file as a string, in the id attribute. This is an XML attribute
common to all View objects (defined by the View class) and you will use it very often. The
syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should parse
and expand the rest of the ID string and identify it as an ID resource. The plus symbol (+)
means that this is a new resource name that must be created and added to our resources
(inthe R.java file). There are a number of other ID resources that are offered by the Android
framework. When referencing an Android resource ID, you do not need the plus-symbol, but
must add the android package namespace, like so
cseitquestions.blogspot.in cseitquestions.blogspot.in
Input Controls
Input controls are the interactive components in our app's
user interface. Android provides a wide variety of controls
we can use in our UI, such as buttons, text fields, seek
bars, checkboxes, zoom buttons, toggle buttons etc.
Common Controls
Android provides more controls but only few are listed here. To explore other controls browse
the android.widget package. If our app requires a specific kind of input control, we can build
our own custom components.
EdiText
We can add a text box control to our app by adding EditText control called EditTextName in
the layout file. This EditText control called EditTextEmail acts as a form field for the user‘s
email address. The following code shows the edit text control added to the layout xml file.
The edit text control has a property called android:inputType . It provides advantage for
users to set the type of input we want to receive in the text box. The value for the input type
property can be any of the valid property values such as text, number, password, email etc.
<EditText
android:id="@+id/EditTextEmail"
android:layout_height="wrap_content"
android:hint="@string/feedbackemail"
android:inputType="textEmailAddress"
android:layout_width="fill_parent">
To read value from the text box the getText() method can be used. The following code
illustrates the use of getText() method.
Radio Buttton
To insert a radio button in a layout xml file we need to create radio button group. Under the
radio group we can add as many as radio buttons we want.
<RadioGroup
android:id="@+id/radioGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/genderMale"
android:layout_width="wrap_content"
android:text="Male"
android:checked="true" />
<RadioButton
android:id="@+id/genderFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
cseitquestions.blogspot.in cseitquestions.blogspot.in
cseitquestions.blogspot.in cseitquestions.blogspot.in
To identify the selected radio button, we can use the getCheckedRadioButtonId() method. It
returns the id of the radio button which is selected. With the help of the id, we can read the
value of the radio button using getText() method.
radioSexGroup = (RadioGroup) findViewById(R.id.radioGender); btnDisplay = (Button)
findViewById(R.id.btnDisplay)
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
Check Box
The CheckBox control can be added to layout file as given below. Similar to other controls we need to
provide id for the control which will be used in the activity file to refer it. To display an option to the
user besides check box, directly we can hardcode the string or pass the string value through strings
xml file. The following code snippet show sample checkbox control added in a layout file.
<CheckBox
android:id="@+id/CheckBoxResponse"
android:layout_height="wrap_content"
android:text="@string/feedbackresponse"
android:layout_width="fill_parent">
After completing the design of the checkbox control, we need to read data from the user.
Through code, we need to identify which check box was selected by the user or whether a check
box is selected or not. Sample code for reading data from a check box control is given below.
The isChecked() method is used to find whether a check box is selected by the user or not selected.
Spinner Control
To add a Spinner control we need to add the spiner control to the layout file. In the following
sample code the Spinner control called SpinnerFeedbackType allows the user to select the
type of feedback from a fixed list of options (Praise, Gripe, Suggestion, or Bug).
First, we need to define these choices as individual string resources in the strings.xml resource file.
Now we can configure the Spinner control in the layout. We can begin by supplying the
prompt attribute, which will provide a helpful string at the top of the Spinner control. Next, we
need to specify the list of string choices using the entries attribute—specifically, set the
entries attribute to the string array we just defined: @array/feedbacktypelist.
<Spinner
android:id="@+id/SpinnerFeedbackType"
android:layout_height="wrap_content" android:prompt="@string/
feedbacktype" android:layout_width="fill_parent"
android:entries="@array/feedbacktypelist">
</Spinner>
After completing the design of UI control, we need to write the code to read data from the
control. The getSelectedItem() method is used to read the data from this spinner control.
1. > Manifests
> AndroidManifest.xml
2. > java
> com.example.kamarajios34.guicomponents
> MainActivity
> com.example.kamarajios34.guicomponents
(androidTest) >ApplicationTest
cseitquestions.blogspot.in
cseitquestions.blogspot.in
3. > res
> drawable
> layout
> activity_main.xml
> mipmap
> ic_launcher.png
> ic_launcher.png (hdpi)
> ic_launcher.png (mdpi)
> ic_launcher.png (xhdpi)
> ic_launcher.png (xxhdpi)
> ic_launcher.png (xxxhdpi)
4. > values
> colors.xml
> dimens.xml
> strings.xml
> styles.xml
Step 1: Design
Step 2: Open res directory -> layout -> activity_main.xml and add following code
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GUI Components"
android:id="@+id/t1"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:autoText="false"
android:minHeight="40dp"
android:textStyle="bold"
android:textSize="30dp"
android:textIsSelectable="false"
android:textAlignment="center"
android:textColor="@color/accent_material_dark" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Green"
android:id="@+id/b1"
android:layout_alignTop="@+id/b2"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Red" android:id="@+id/b2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
cseitquestions.blogspot.in
cseitquestions.blogspot.in
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blue"
android:id="@+id/b3"
android:layout_alignTop="@+id/b2"
android:layout_alignEnd="@+id/t1" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/img1"
android:maxHeight="70dp"
android:layout_alignParentBottom="true"
android:src="@mipmap/ic_launcher"
android:layout_alignParentEnd="true"
android:layout_below="@+id/b1" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/imgb1"
android:maxHeight="10dp"
android:maxWidth="10dp"
android:longClickable="false"
android:visibility="visible"
android:minHeight="10dp"
android:contentDescription="CLICK BUTTON"
android:layout_gravity="left|top|bottom|center|right"
android:layout_above="@+id/b1"
android:layout_alignEnd="@+id/b3"
style="@style/AlertDialog.AppCompat.Light"
android:background="#dd2e2e"
android:layout_marginLeft=―@dimen
abc_action_bar_subtitle_bottom_margin_material"
android:layout_marginRight="@dimen/
abc_action_bar_subtitle_bottom_margin_material"
android:layout_marginBottom="@dimen/
abc_action_bar_subtitle_bottom_margin_material" />
cseitquestions.blogspot.in cseitquestions.blogspot.in
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click RED button"
android:id="@+id/textView"
android:layout_above="@+id/imgb1"
android:layout_alignStart="@+id/imgb1" />
<ToggleButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New ToggleButton"
android:id="@+id/toggleButton"
android:layout_below="@+id/t1"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Step 3: Open your Android studio project folder (e.g. Project name: GUI
Components ) —>Click app -> src -> main -> res -> drawable -> add *.png file.
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable; import
android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
cseitquestions.blogspot.in
cseitquestions.blogspot.in
public class MainActivity extends
AppCompatActivity { TextView text;
Button bu1,bu2,bu3;
ImageView image1;
ImageButton image2;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
bu1=(Button) findViewById(R.id.b1); bu2=(Button)
findViewById(R.id.b2); bu3=(Button)
findViewById(R.id.b3); text=(TextView)
findViewById(R.id.t1);
image1=(ImageView)findViewById(R.id.img1);
image2=(ImageButton)findViewById(R.id.imgb1);
image2.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
image1.setImageResource(R.drawable.corel);
}
});
bu1.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
bu1.setBackgroundColor(Color.GREEN);
text.setTextColor(Color.GREEN);
bu2.setBackgroundColor(Color.LTGRAY);
bu3.setBackgroundColor(Color. LTGRAY);
}});
bu2.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
bu2.setBackgroundColor(Color.RED);
bu3.setBackgroundColor(Color.LTGRAY);
bu1.setBackgroundColor(Color.LTGRAY);
text.setTextColor(Color.RED);
}});
bu3.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
bu3.setBackgroundColor(Color.BLUE);
text.setTextColor(Color.BLUE);
cseitquestions.blogspot.in
cseitquestions.blogspot.in
bu2.setBackgroundColor(Color.LTGRAY);
bu1.setBackgroundColor(Color.LTGRAY);
cseitquestions.blogspot.in
cseitquestions.blogspot.in
}});
}}
Step 1: Design
MainActivity.java
package com.example.kamarajios34.fontlistview;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
cseitquestions.blogspot.in cseitquestions.blogspot.in
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
"Angilla Tattoo",
"Cantate Beveled",
"Krinkes Decor PERSONAL",
"Krinkes Regular PERSONAL",
"Silent Reaction",
"Sweetly Broken",
"Xerox Sans Serif Narrow
Bold", "Xacto Blade"
};
listview.setAdapter(adapter);
listview.setOnItemClickListener(new
AdapterView.OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view, int position, long
id)
{
if(itemValue.equals("Cantate Beveled"))
{
txt.setText(e1.getText());
String fontPath="fonts/Cantate Beveled.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(),
fontPath); txt.setTypeface(tf);
}
if(itemValue.equals("Silent Reaction"))
{
txt.setText(e1.getText());
String fontPath="fonts/Silent Reaction.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(),
fontPath); txt.setTypeface(tf);
}
if(itemValue.equals("Sweetly Broken"))
{
txt.setText(e1.getText());
String fontPath="fonts/Sweetly Broken.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(),
fontPath); txt.setTypeface(tf);
}
if(itemValue.equals("Xacto Blade"))
{
txt.setText(e1.getText());
String fontPath="fonts/Xacto Blade.ttf";
Typeface tf = Typeface.createFromAsset(getAssets(),
fontPath); txt.setTypeface(tf);
}}
});}}
Step 4: Output
cseitquestions.blogspot.in cseitquestions.blogspot.in
XML layout attributes named layout_something define layout parameters for the View that are
appropriate for the ViewGroup in which it resides. Every ViewGroup class implements a nested class
that extends ViewGroup.LayoutParams. This subclass contains property types that define the size
and position for each child view, as appropriate for the view group. As given in the below picture, the
parent view group defines layout parameters for each child view (including the child view group).
Visualization of a view hierarchy with layout parameters associated with each view.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Android Layout Types
There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There
are few common attributes among all the layouts and they are other attributes which are
specific to that layout. Few attributes of layouts are given below.
Attribute Descriptio
android:id This is the ID which uniquely identifies the view.
android:layout_width This is the width of the layout.
android:layout_height This is the height of the layout
android:layout_weight This specifies how much of the extra space in the
layout should be allocated to the View.
Events are actions performed by users. It can be in any form. These events are the inputs to
the applications. When application interacts with user it receives input in the form events.
For example an event may be a button click, key press etc.
Event Listeners −An event listener is an interface in the View class that contains a
singlecallback method. These methods will be called by the Android framework when the
View to which the listener has been registered is triggered by user interaction with the item in
the UI.
Event Listeners Registration −Event Registration is the process by which an Event
Handler getsregistered with an Event Listener so that the handler is called when the
Event Listener fires the event.
Event Handlers −When an event happens and we have registered and event listener for the
event, the event listener calls the Event Handlers, which is the method that actually
handles the event.
Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there
are several tricky ways to register our event listener for any event, but we are going to
discuss only 3 ways, out of which we can use based on the requirement or scenario.
Listens to Event
event handler
invoked
Event
triggered
The event handling approach is to capture the events and take appropriate response based on the
event type. Event handling is accomplished with the help of event listeners and event handlers. Event
listeners listen to events and event handlers execute the appropriate code as response to the events.
When a control is created it must be registered with event listener in order to, notified by the listeners.
When an event is triggered by users, the listeners are notified, and the listeners inform the event
handlers that there is an event triggered. Then the event handler is executed, inside the event handler
the code is written which is specifying what should happen for the event which was triggered.
the item).
cseitquestions.blogspot.in cseitquestions.blogspot.in
OnMenuItemClickListener( onMenuItem This is called when the user
) Click() selects a menu item. You will
use onMenuItemClick() event
handler to handle such event.
To know more kind of event handlers listeners we can refer official documentation for
Android application development.
3.3 Menus
Menus are a common user interface component in many types of applications. To provide a
familiar and consistent user experience, we should use the Menu APIs.
Although the design and user experience for some menu items have
changed, the semantics to define a set of actions and options is still
based on the Menu APIs. We will discuss how to create fundamental
types of menus or action presentations on different versions of Android.
Options menu
The options menu is the primary collection of menu items for an activity.
It's where we should place actions that have a global impact on the
app, such as "Search," "Compose email," and "Settings."
If we are developing for Android 2.3 or lower, users can reveal the options
menu panel by pressing the Menu button. On Android 3.0 and higher, items from the options menu
are presented by the action bar as a combination of on-screen action items and overflow options.
Beginning with Android 3.0, the Menu button is deprecated (some devices don't have one), so we
should migrate toward using the action bar to provide access to actions and other options.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Context menu
A context menu is a floating menu that appears when the user performs a long-click on an
element. It provides actions that affect the selected content or context frame.
When developing for Android 3.0 and higher, we should instead use the contextual action
mode to enable actions on selected content. This mode displays action items that affect the
selected content in a bar at the top of the screen and allows the user to select multiple items.
Popup menu
A popup menu displays a list of items in a vertical list that's anchored to
the view that invoked the menu. It's good for providing an overflow of
actions that relate to specific content or to provide options for a second
part of a command. Actions in a popup menu should not directly affect the corresponding
content— that's what contextual actions are for. Rather, the popup menu is for extended
actions that relate to regions of content in our activity.
The easiest way to create a menu is to define the menu in XML layout and then inflate a
menu resource during the onCreateOptionsMenu() callback method.
cseitquestions.blogspot.in cseitquestions.blogspot.in
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu); return true;
}
When the user selects a menu item from the Options Menu the system calls the activity's
onOptionsItemSelected() method.This method passes the MenuItem that the user selected. We
can identify the menu item by calling getItemId(), which returns the unique ID for the menu item
(defined by the android:id attribute in the menu resource or with an integer given to the add()
method). We can match this ID against known menu items and perform the appropriate action. A
menu group is a collection of menu items that share certain traits. With a group, you can:
This example only deals with Options menu and Submenu only. This sample code helps to
understand the Menu life cycle and how to create menus using XML layout and
programmatically using code for adding and removing menus dynamically.
cseitquestions.blogspot.in cseitquestions.blogspot.in
3.4 Running the Layout Managers and Event Click Listener App
Step 2: After creating the project, open the res directory -> layout -> resource file
namedactivity_main.xml
Step 3: Create two resource (*.xml) file named activity_second.xml, activity_third.xml
& twoactivity (*.java) file named second.java and third.java file.
Right click res directory -> New -> Activity -> Empty Activity
Step 5: Create new Resource directory named menu and new resource file named menu
Right click res directory -> New -> Android Resource Directory -> resource type -
> select menu -> finish
cseitquestions.blogspot.in cseitquestions.blogspot.in
Right click menu directory -> New -> new menu resource file -> enter file name -> Ok
Step 4: Design (After the design, the xml code will be generated automatically in the
layoutfile )
33
activity_main.xml activity_second.xml activity_third.xml
cseitquestions.blogspot.in cseitquestions.blogspot.in
android:id="@+id/one"
android:title="One"/>
<item
android:id="@+id/two"
android:title="Two"/>
</menu>
Step 6: Open MainActivity.java, second.java & third.java and add the following code
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu pm = new PopupMenu(MainActivity.this,b1);
pm.getMenuInflater().inflate(R.menu.menu,pm.getMenu());
pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem
item)
{ switch (item.getItemId()) {
case R.id.one:
Intent o = new Intent(getApplicationContext(),
second.class); startActivity(o);
System.exit(0);
break;
cseitquestions.blogspot.in
cseitquestions.blogspot.in
case R.id.two:
Intent in = new Intent(getApplicationContext(),third.class);
startActivity(in);
System.exit(0);
break;
}
return false;
}
});
pm.show();
}
});
}
}
second.java
Third.java
@Override
protected void onCreate(Bundle savedInstanceState) {
cseitquestions.blogspot.in
cseitquestions.blogspot.in
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
back=(Button)findViewById(R.id.back);
img=(ImageView)findViewById(R.id.imageView);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
System.exit(0);
}
});
}
}
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Home" android:background="#fff"
android:weightSum="1">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="72dp"
android:id="@+id/onoff">
<Switch
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/switch1"
android:checked="false" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_gravity="center_horizontal"
android:id="@+id/l1">
cseitquestions.blogspot.in
cseitquestions.blogspot.in
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "@+id/display"
android:hint="Enter the Values"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="20dp"
android:id="@+id/l5">
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/one"
android:text="1" />
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/two"
android:text="2" />
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/three"
android:text="3" />
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/div" android:text="/"
/>
</LinearLayout>
cseitquestions.blogspot.in
cseitquestions.blogspot.in
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:paddingTop="20dp"
android:id="@+id/l2">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/four"
android:text="4" />
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/five"
android:text="5" />
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/six"
android:text="6" />
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/mul"
android:text="*" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="20dp"
android:id="@+id/l3">
cseitquestions.blogspot.in
cseitquestions.blogspot.in
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/seven"
android:text="7" />
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/eight"
android:text="8" />
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/nine"
android:text="9" />
<Button android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/sub" android:text="-
" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="20dp"
android:id="@+id/l4">
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/cancel"
android:text="C" />
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/zero"
android:text="0" />
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/equal"
android:text="=" />
cseitquestions.blogspot.in cseitquestions.blogspot.in
<Button
android:layout_width="55dp"
android:layout_height="wrap_content"
android:id = "@+id/add"
android:text="+" />
</LinearLayout>
</LinearLayout>
package com.example.kamarajios33.calc;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.RequiresPermission;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onoff = (Switch)findViewById(R.id.switch1);
onoff.setChecked(true);
one = (Button) findViewById(R.id.one);
two = (Button) findViewById(R.id.two);
cseitquestions.blogspot.in cseitquestions.blogspot.in
one.setEnabled(true);
two.setEnabled(true);
three.setEnabled(true);
four.setEnabled(true);
five.setEnabled(true);
six.setEnabled(true);
seven.setEnabled(true);
eight.setEnabled(true);
nine.setEnabled(true);
zero.setEnabled(true);
add.setEnabled(true);
sub.setEnabled(true);
mul.setEnabled(true);
sub.setEnabled(true);
cseitquestions.blogspot.in
cseitquestions.blogspot.in
mul.setEnabled(true);
div.setEnabled(true);
cancel.setEnabled(true);
equal.setEnabled(true);
disp.setEnabled(true);
}
else
{
one.setEnabled(false);
two.setEnabled(false);
three.setEnabled(false);
four.setEnabled(false);
five.setEnabled(false);
six.setEnabled(false);
seven.setEnabled(false);
eight.setEnabled(false);
nine.setEnabled(false);
zero.setEnabled(false);
add.setEnabled(false);
sub.setEnabled(false);
mul.setEnabled(false);
sub.setEnabled(false);
mul.setEnabled(false);
div.setEnabled(false);
cancel.setEnabled(false);
equal.setEnabled(false);
disp.setEnabled(false);
}
}
});
try {
one.setOnClickListener(this);
two.setOnClickListener(this);
three.setOnClickListener(this);
four.setOnClickListener(this);
five.setOnClickListener(this);
cseitquestions.blogspot.in
cseitquestions.blogspot.in
six.setOnClickListener(this);
seven.setOnClickListener(this);
eight.setOnClickListener(this);
nine.setOnClickListener(this);
zero.setOnClickListener(this);
cancel.setOnClickListener(this);
add.setOnClickListener(this);
sub.setOnClickListener(this);
mul.setOnClickListener(this);
div.setOnClickListener(this);
equal.setOnClickListener(this);
} catch (Exception e) {
}
}
case R.id.five:
if (op2 != 0) {
op2 = 0;
disp.setText("");
}
str = str.append(five.getText());
disp.setText(str);
break;
case R.id.six:
if (op2 != 0) { op2
= 0;
disp.setText("");
}
str = str.append(six.getText());
disp.setText(str);
break;
case R.id.seven:
if (op2 != 0) {
op2 = 0;
disp.setText("");
}
str = str.append(seven.getText());
disp.setText(str);
break;
case R.id.eight:
if (op2 != 0) {
op2 = 0;
disp.setText("");
}
str = str.append(eight.getText());
disp.setText(str);
break;
cseitquestions.blogspot.in
cseitquestions.blogspot.in
case R.id.nine:
if (op2 != 0) {
op2 = 0;
disp.setText("");
}
str = str.append(nine.getText());
disp.setText(str);
break;
case R.id.zero:
if (op2 != 0) {
op2 = 0;
disp.setText("");
}
str = str.append(zero.getText());
disp.setText(str);
case R.id.cancel:
op1 = 0;
op2 = 0;
disp.setText("");
disp.setHint("Perform
Operation"); break;
case R.id.add:
optr = "+";
if (op1 == 0) {
op1 = Integer.parseInt(disp.getText().toString());
disp.setText("");
}
else if (op2 != 0) {
op2 = 0;
disp.setText("");
}
else
{
op2 = Integer.parseInt(disp.getText().toString());
disp.setText("");
op1 = op1 + op2;
disp.setText(Integer.toString(op1));
}
break;
cseitquestions.blogspot.in
cseitquestions.blogspot.in
case R.id.sub:
optr = "-";
if (op1 == 0)
{
op1 = Integer.parseInt(disp.getText().toString());
disp.setText("");
}
else if (op2 != 0) {
op2 = 0;
disp.setText("");
}
else
{
op2 = Integer.parseInt(disp.getText().toString());
disp.setText("");
op1 = op1 - op2;
disp.setText(Integer.toString(op1));
}
break;
case R.id.mul:
optr = "*"; if
(op1 == 0)
{
op1 = Integer.parseInt(disp.getText().toString());
disp.setText("");
}
else if (op2 != 0) {
op2 = 0;
disp.setText("");
}
else
{
op2 = Integer.parseInt(disp.getText().toString());
disp.setText("");
op1 = op1 * op2;
disp.setText(Integer.toString(op1));
}
break;
cseitquestions.blogspot.in
cseitquestions.blogspot.in
case R.id.div:
optr = "/";
if (op1 == 0)
{
op1 = Integer.parseInt(disp.getText().toString());
disp.setText("");
}
else if (op2 != 0) {
op2 = 0;
disp.setText("");
}
else
{
op2 = Integer.parseInt(disp.getText().toString());
disp.setText("");
op1 = op1 / op2;
disp.setText(Integer.toString(op1));
}
break;
case R.id.equal:
if (!optr.equals(null))
{
if (op2 != 0)
{
if (optr.equals("+"))
{
disp.setText("");
op1 = op1 + op2;
disp.setText(Integer.toString(op1));
}
else if (optr.equals("-"))
{
disp.setText("");
op1 = op1 - op2;
disp.setText(Integer.toString(op1));
}
cseitquestions.blogspot.in
cseitquestions.blogspot.in
else if (optr.equals("*"))
{
disp.setText("");
op1 = op1 * op2;
disp.setText(Integer.toString(op1));
}
else if (optr.equals("/"))
{
disp.setText("");
op1 = op1 / op2;
disp.setText(Integer.toString(op1));
}
}
else
{
operation();
}
}
break; }}}
5. Graphical Primitives
Step1: Create an android project using android studio.
Step 2: After creating the project, open the java file named MainActivity.xml.
MainActivity.java
package com.example.kamarajios33.graphics;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dv = new DemoView(this);
setContentView(dv);
}
ob.setColor(Color.WHITE);
canvas.drawPaint(ob);
ob.setColor(Color.GRAY);
canvas.drawCircle(100, 100, 60, ob);
ob.setColor(Color.CYAN);
canvas.drawCircle(200, 50, 30, ob);
ob.setColor(Color.MAGENTA);
canvas.drawRect(200, 200, 400, 400,
ob); ob.setColor(Color.RED);
canvas.drawLine(250,50,350,400,ob);
canvas.rotate(-45); }}}
• Introduction to SQLite
• Android Database API
• Using Content Provider
• Connecting with Database Server
SQLite supports the data types such as TEXT (similar to String in Java), INTEGER (similar to long in Java)
and REAL (similar to double in Java). All other types must be converted into one of these fields before
getting saved in the database. SQLite does not validate,whether the data stored in to the columns are
actually of the defined type, e.g. wecan write an integer into a string column and vice versa.
SQLite is embedded into every android device. Since the database requires limited memory at
runtime (approx. 250 KByte) it is widely chosen for embedding in devices. Android platform
includes the SQLite embedded database and provides APIs to access the database. To use
the SQLite database in android,we donot require a setup procedure.
We need to only have to define the SQL statements for creating and updating the database.
Thenthe database will be managed by the android system. Access to the SQLite database
involves accessing the file system. This can be slow. Therefore it is recommended to perform
database operations asynchronously. If our application creates a database, this database is
stored by default in the following directory DATA/data/APP_NAME/databases/FILENAME.
• SQLiteDataBase
• Cursor
• SQLiteOpenHelper
1. SQLiteDatabase
SQLiteDatabase is the base class for working with a SQLite database in android and
provides methods to open, query, update and close the database. In addition it provides the
execSQL() method, which allows to execute an SQL statement directly.
To perform the following database operations, SQLiteDatabase class provides various methods.
a) Insert operation – For inserting values to the database, we need to save data into
contentvalues.ContentValues allow defining key/value pairs. The key represents the
table column name and the value represents the content corresponding to that column.
The object ContentValues allows to define key/values. The key represents the table column
identifier and the value represents the content for the table record in this column.
ContentValues can be used for inserts and updates of database entries.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(column1,value1
);values.put(column2,valu
e2);values.put(column3,va
l u e 3 ) ; values.put(column4, value4);
// insert row in table
b) Update Operation: To update the existing record in your Android sqlite database table,
you needto execute the following method.
db.update(TABLE_NAME,content_values,WHERE_CLAUSE,WHERE_ARGUMENTS);
• The third argument specifies the where clause (it‘s a condition). For example, update
the employee name where emloyee ID is ―123‖. Here, the where clause is the ―id=‖.
• The fourth argument takes the value corresponding to the where clause. For
the above example it is ―123‖.
c) Delete Operation: Similarly, you can perform the delete operation on an Android SQLite
database table. It takes three arguments. The first is the table name, the second is the
where clause, and the third is the value corresponding to that where clause.
db.delete(TABLE_NAME,WHERE_CLAUSE,WHERE_ARGUMENTS);
d) Read Operation: To read values from an Android SQLite database table, we need to learn
aboutcursors. We execute the select operation on the database and we get multiple rows as a result.
We
assign those rows to a cursor. A Cursor points to one row at a time. This is how we get
the required data.
Raw Query: This query directly accepts SQL as an input. You can pass SQL
statement(s) and SQLiteDatabase will execute that query for you.
db.rawQuery(sql_statement,null);
2. Cursor
A query returns a Cursor object. A Cursor represents the result of a query and basically
points to one row of the query result. This way Android can buffer the query results
efficiently; as it does not have to load all data into memory.
To get the number of elements of the resulting query use the getCount() method. To move
between individual data rows, you can use the moveToFirst() and moveToNext() methods.
The isAfterLast() method allows to check if the end of the query result has been reached.
In the following code, we assign the result of the select statement to the cursor and
manipulate the data.
cseitquestions.blogspot.in cseitquestions.blogspot.in
String selectQuery = "SELECT * FROM TABLE_NAME";
Cursor c = db.rawQuery(selectQuery, null);
SQLiteOpenHelper
To create and upgrade a database in our Android application we can usef the SQLiteOpenHelper class.
• onCreate() - is called by the framework, if the database is accessed but not yet created.
• onUpgrade() - called, if the database version is increased in your application code.
This method allows you to update an existing database schema or to drop the
existing database and recreate it via the onCreate() method.
• Both methods receive an SQLiteDatabase object as parameter which is the Java
representation of the database.
• TheSQLiteOpenHelperclassprovidesthegetReadableDa
t a b a s e ( ) a n d getWriteableDatabase() methods to get access to an
SQLiteDatabase object; either in read or write mode.
The database tables should use the identifier _id for the primary key of the table. Several
Android functions rely on this standard.
You also define an array which contains the column names and another array which
contains the IDs of Views which should be filled with the data
Content providers are simple interfaces which uses standard insert(), query(), update(),
delete() methods to access app data. A special URI starting with content:// will be assigned
to each content providers and that will be recognized across applicationsor apps.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Above diagram shows how content provider works. App 1 stores its data in its own database and
provides a content provider. App 2 communicates access App 1's data through the content provider.
2) Defining URI:
Content URI has a special path similar to HTTP. Content provider URI consists of four parts.
content://authority/path/id
• content:// All the content provider URIs should start with this value
• 'authority' is Java namespace of the content provider implementation. (fully
qualified Java package name)
• 'path' is the virtual directory within the provider that identifies the kind of data
being requested.
• 'id' is optional part that specifies the primary key of a record being
requested. We can omit this part to request all records.
b) Updating records
To update one or more records via content provider we need to specify the content
provider URI. update() method of the ContentProvider is used to update records. We
have to specify the ID of the record to be updated. To update multiple records, we
have to specify 'selection' parameter to indicate which rows are to be updated. This
method will return the number of rows updated.
cseitquestions.blogspot.in cseitquestions.blogspot.in
c) Deleting records
Deleting one or more records is similar to update operation. We need to specify
either ID or 'selection' to delete records. The delete() method of the ContentProvider
will return the number of records deleted.
e) getType() method
This method is used to handle requests for the MIME type of data at the given URI. We
use either vnd.android.cursor.item or vnd.android.cursor.dir/ The vnd.android.cursor.item
is used to represent specific item. Another one is used to specify all items.
Here authorities is the URI authority to access the content provider. Typically this will
be the fully qualified name of the content provider class.
Step 4: Design (After the design part, the xml code will be generated
automatically inthe layout file )
activity_main.xml activity_main2.xml
package com.example.kamarajios33.database;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
cseitquestions.blogspot.in cseitquestions.blogspot.in
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = openOrCreateDatabase("Mydb",MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(fname
VARCHAR,lname VARCHAR,email VARCHAR);");
Main2Activity.java
package com.example.kamarajios33.database;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
setContentView(R.layout.activity_main2);
fn=(EditText)findViewById(R.id.fn);
ln=(EditText)findViewById(R.id.ln);
em=(EditText)findViewById(R.id.em); back
=(Button)findViewById(R.id.button2);
next=(Button)findViewById(R.id.button);
prev=(Button)findViewById(R.id.b3);
db = openOrCreateDatabase("Mydb",MODE_PRIVATE,null);
back.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
Intent il = new Intent(getApplicationContext(),
MainActivity.class); startActivity(il);
System.exit(0);
}
});
next.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v)
{ try
{
c.moveToNext();
fn.setText(c.getString(c.getColumnIndex("fname")));
ln.setText(c.getString(c.getColumnIndex("lname")));
em.setText(c.getString(c.getColumnIndex("email")));
}
cseitquestions.blogspot.in cseitquestions.blogspot.in
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"Last
Record",Toast.LENGTH_LONG).show(); e.printStackTrace();
}
}
});
prev.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v)
{ try
{
c.moveToPrevious();
fn.setText(c.getString(c.getColumnIndex("fname")));
ln.setText(c.getString(c.getColumnIndex("lname")));
em.setText(c.getString(c.getColumnIndex("email")));
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"First
Record",Toast.LENGTH_LONG).show(); e.printStackTrace();
}}
});
}}
Step 6: Run the project. While running, the following output will be shown in the emulator.
cseitquestions.blogspot.in cseitquestions.blogspot.in
WebView
Android WebView component used in Android web app to render the android apps GUI. Webview
component is a browser supported view and it allows us implementing web pages in our android
application as we like. WebView gives most of the screen space in our android application.
<application
...></application
>
</manifest>
Using WebView
In order to use the Android WebView component We need to insert that component in our layout.
This is most often done by inserting a WebView element into the layout XML file for the layout we
want the WebView to be displayed in. Here is an example layout file with a WebView embedded:
cseitquestions.blogspot.in cseitquestions.blogspot.in
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/and roid"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<WebView android:id="@+id/webview"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</RelativeLayout>
Once we have inserted a WebView into a layout somewhere, we can access it from our
code. We need to access the WebView to make it do any interesting task for user. Typically
WebView control is accessed from inside an activity. Here is the sample code which
accesses a WebView embedded in its layout XML file:
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
WebViewwebView = (WebView)
findViewById(R.id.webview)
WebViewwebView = (WebView) findViewById(R.id.webview); webView.loadUrl("http://
www.kcetvnr.orgn");
}
}
Once inserted WebView control in the layout, we can refer it inside the activity class and can
instruct it to load URLs via HTTP or any other task. Here we have used the WebView's
loadUrl() method which loads the URL into the WebView.
cseitquestions.blogspot.in cseitquestions.blogspot.in
7. Multithreading
Objectives
After completing this chapter we will be able to understand the following topics.
• Multithreading
• Multimedia in Android
• Media Player API
• Camera API
• Running the Multithreading App
Multithreading
Multi-threading is defined as a feature through which we can run two or more
concurrent threads of a process. In this a process, the common data is shared
among all these threads also known as sub-processes exclusively.
Multimedia in Android
Multimedia capabilities, or the playing and recording of audio and video, is one such
significant task that many users find to be of great value. Take a quick look around us,
we will find people using the phone as a means to enjoy a variety of programs as well
as share self-recorded media among friends. Android provides APIs to easily access
this capability as well as embed multimedia and its manipulation directly within an
application. Usually multimedia involves in performing the following basic functions.
We will discuss the ‗Stagefright‘ architecture from Google. Because the foundation of
Android‘s multimedia platform is Google‘s new media platform Stagefright. Stagefright, as of
now, supports the following core media files, services, and features:
• Interfaces for third-party and hardware media codecs, input and output
devices, and content policies.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Playing Audio
Probably the most basic need for multimedia on a cell phone is the ability to play audio files,
whether new ringtones, MP3s, or quick audio notes. Media- Player of android is easy to use.
To play an MP3 file follow these steps:
• Place the MP3 in the res/raw directory in a project (note that we can also use
a URI to access files on the network or via the internet).
• Create a new instance of the MediaPlayer, and reference the MP3
by calling MediaPlayer.create().
• Call the MediaPlayer methods prepare() and start().
Playing Video
Playing a video is slightly more complicated than playing audio with the MediaPlayer API,
because we have to provide a view surface for our video to play on. Android has a
VideoView widget that handles this task for us. This widget can be used with any layout
manager. Android also provides a number of display options, including scaling and tinting.
cseitquestions.blogspot.in cseitquestions.blogspot.in
activity_main.xml
MainActivity.java
package com.example.kamarajios33.cameraview;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i=(ImageView)findViewById(R.id.img);
bu=(Button)findViewById(R.id.b1);
wall=(Button)findViewById(R.id.wall);
b3=(Button)findViewById(R.id.b3);
t=(ToggleButton)findViewById(R.id.tb);
bu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(in,CAMERA_REQUEST);
}
});
m = MediaPlayer.create(MainActivity.this,R.raw.sam);
wall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{ try {
if (flag == 1) {
getApplicationContext().setWallpaper(BitmapFactory.decodeFile(p));
Toast.makeText(getApplicationContext(), "Wallpaper
Changed from Gallery", Toast.LENGTH_SHORT).show();
} else if (flag == 2) {
getApplicationContext().setWallpaper(photo);
Toast.makeText(getApplicationContext(), "Wallpaper
Changed from Camera", Toast.LENGTH_SHORT).show();
cseitquestions.blogspot.in cseitquestions.blogspot.in
}
cseitquestions.blogspot.in cseitquestions.blogspot.in
else {
Toast.makeText(getApplicationContext(), "Wallpaper Not Set",
Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
{
if(requestcode==CAMERA_REQUEST)
{
photo = (Bitmap)data.getExtras().get("data");
i.setImageBitmap(photo);
flag =2;
}
if(requestcode==2 && resultcode == RESULT_OK)
{
Uri sel = data.getData();
String[] file ={MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(sel, file, null, null,
null); c.moveToFirst();
int co = c.getColumnIndex(file[0]);
p = c.getString(co);
c.close();
i.setImageBitmap(BitmapFactory.decodeFile(p));
flag = 1;
}}}
cseitquestions.blogspot.in cseitquestions.blogspot.in
Step 7: Open AndroidManifest.xml and add following code
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-
permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-
permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
This Chapter to describe implement an application that writes data to the SD card
Step 1: Select File -> New -> Project -> Android Application Project (or)
AndroidProject. Fill the forms and click ―Finish‖ button.
Step 2: Open res -> layout -> activity_main.xml -> click Design -> Put the
necessarycomponents in the layout.
Step 3: Create a layout file for UI ( Design for UI after that the code will be
generatedautomatically in activity_main.xml )
Design - activity_main.xml
cseitquestions.blogspot.in
cseitquestions.blogspot.in
Step 4: Create an activity file
MainActivity.java
package com.example.kamarajioslab01.sdcard;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
}// onCreate
}// AndSDcard
<uses-permission
android:name=―android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Step 6: Run the Project. While running, the following output will be shown
in theemulator.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Objectives
• Dialogs, Notifications
• Running the Alert App
Dialogs
A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events that
require users to take an action before they can proceed.
The Dialog class is the base class for dialogs, but we should avoid instantiating Dialog
directly. Instead, ne of the following subclasses can be used.
1. AlertDialog - A dialog that can show a title, up to three buttons, a list of selectable
items, or a custom layout.
2. DatePickerDialog or TimePickerDialog - A dialog with a pre-defined UI that allows
the user to select a date or time.
These classes define the style and structure for a dialog, but the DialogFragment must be used
as a container for our dialog. TheDialogFragment class provides all the controls required to
create a dialog, manage its appearance. Instead of calling methods on the Dialog object, the
DialogFragment class and its methods can be used. Using DialogFragment to manage the dialog
ensures that it correctly handles lifecycle events such as when the user presses the back button
or rotates the screen. The DialogFragment class also allows to reuse the dialog's UI as an
embeddable component in a larger UI, just like a traditional Fragment.
The AlertDialog class allows us to build a variety of dialog designs and is often the only dialog
class we will need. There are three regions of an alert dialog which is shown below in the image:
cseitquestions.blogspot.in cseitquestions.blogspot.in
1. Title
This is optional and should be used only when the content area is occupied by a detailed
message, a list, or custom layout. If we need to state a simple message or question
(such as the dialog in figure 1), title is not required.
2. Content area
This can display a message, a list, or other custom layout.
3. Action buttons
There should be no more than three action buttons in a dialog.
The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with these kinds of
content, including a custom layout. To build an AlertDialog, we can follow the steps given below.
To add action buttons like those in figure 2, call the setPositiveButton() and
setNegativeButton() methods:
The set...Button() methods require a title for the button (supplied by a string resource) and a
DialogInterface.OnClickListener that defines the action to take when the user presses the
button. There are three different action buttons you can add:
• Positive - should be used to accept and continue with the action (the "OK" action).
• Negative - should be used to cancel the action.
• Neutral - should be used when the user may not want to proceed with the action, but doesn't
necessarily want to cancel. It appears between the positive and negative buttons. For
example, the action might be "Remind me later."
We can add only one of each button type to an AlertDialog. That is, we cannot have more
than one "positive" button.
Notifications
A notification is a message which is displayed to the user outside of an application's normal UI.
When we tell the system to issue a notification, it first appears as an icon in the notification area.
To see the details of the notification, the user opens the notification drawer. Both the notification
area and the notification drawer are system-controlled areas that the user can view at any time.
Toasts
A toast provides simple feedback about an operation in a small popup. It only fills the amount of
space required for the message and the current activity remains visible and interactive.
cseitquestions.blogspot.in cseitquestions.blogspot.in
For example, navigating away from an email before you send it triggers a "Draft saved" toast to let
you know that you can continue editing later. Toasts automatically disappear after a timeout.
The toast control receives the message to be displayed by makeToast() method. It will be
visible only when the show() method is invoked. The above code can be combined into a
single line of code as shown below.
Step 1: Select File -> New -> Project -> Android Application Project (or)
AndroidProject. Fill the forms and click ―Finish‖ button.
Step 2: Create an activity file
MainActivity.java
package com.example.user.alertdemo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Uncomment the below code to Set the message and title from the strings.xml
file
cseitquestions.blogspot.in cseitquestions.blogspot.in
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
alert.setTitle("Alertdemo"); alert.show();
setContentView(R.layout.activity_main);
}}
cseitquestions.blogspot.in cseitquestions.blogspot.in
Step 3: Run the Project. While running, the following output will be shown in
theemulator.
cseitquestions.blogspot.in cseitquestions.blogspot.in
10.Alarm Clock
Objectives
After completing this chapter we will be able to understand the following topics.
• Introduction to Services
• Lifecycle of a Service
• Managing Services
• Introduction to Broadcast Receivers
• Types of Broadcast Receivers
• Creating and Registering Broadcast Receivers
While developing android app, we should be able to manage different task simultaneously.
For example, playing music in background while playing games. Such simultaneous tasks
are managed by services. To interact with services we need to create an activity. For
example, service might interact with a content provider, music player and so on. All these
tasks will be running in the background.
1. Forms of Services
Services are used for regularly updating the data source in background. The updated data
source is used by activities running on foreground. Services are mainly used for triggering
notifications such as email or message arrival. Services are controlled (i.e. Started/stopped)
from other android app components such as broadcast receivers, activities and other service
components. Services are classified into two types. They are
➢ Unbound Services
➢ Bound Services
cseitquestions.blogspot.in cseitquestions.blogspot.in
a) UnBound Service
The unbound service is also known as started service. The startService() method is used to
start the service,onces the service is started it will be running in background for indefinite
period of time, even if we destroy the started component. Started service performs the
intended operation and does not return any result to the caller component.
Example:
When we open the game, music starts playing in background automatically till we exit the game.
b) Bound Services
Bound Service can be referred as client–server approach . The bound services allow the
app components to interact with each other. It allows the appl components to send request
and getresult using inter process communication(IPC). Bound service uses bindService()
method to bind with one or more app components. Bound service will be running until
another component is bound to it. Multiple components can be binded to the service at a
time. The service will be destroyed when the bind components are unbind.
2. Lifecycle of a Service
The lifecycle of a service can follow two different paths depending on the form of the service,
which can be either unbound or bound.
To understand the lifecycle of a service, consider the example like playing games. When we open the
game app, an activity is started. During the lifetime of this app, activity may invoke a service.
i.e. service to enable or disable the music by changing the game or exiting the game. If user
exits the game app, all service components acquired by the app are released and destroyed.
Lifecycle Methods
Some of the important callback methods that you can override are:
service is stopped, when the system destroys service components and its resources.
The figure depicts the Callback method Executed during the Lifecycle of a started service or
unbound service.
For example, when a started service is downloading a file over a network, the service should
stop itself when the operation completed.
cseitquestions.blogspot.in cseitquestions.blogspot.in
The following figure depicts the callback method executed during the lifecycle of
a bound service.
Managing Services
1. Creating a Service
Service can be created in two ways,
Services are independent blocks of code to perform given tasks. The services are getting the latest
updated date from the other services which are running in the background. To create a service we
need to extend the Service class and override the some of the callback methods available in service
class. The class Service is available in the package ‗android.app ‗. The callback methods of services
handle the lifecycle of the service that has been created. It also allows the other service components
to connect to this newly created service by calling the bindService().
2. Starting a Service
To implement services in the Android apps, we need to:
Create a service by extending the android. app. Service class.
Register the service in the AndroidManifest.xml file.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Regardless of the service types whether it is bound or unbound serive, alwaya the
startService() callback method is invoked to start the service. This method takes Intent
object as parameter, which contains the info about the service need to be started.
The following code shows how to start a service.
When the service component call the startService() method, it will check whether the service
is running or not, if service is not running the android system will call onCreate() method, if
service is already running in background then android system will call onStartCommand()
method.When multiple components start a service, thay call onStartcommand() method then
each start request is called individually.
The service will start running after receiving request from the component. It will continue running,
until it stopSelf() or stopService() method is called. We have to note one point that even multiple
requests made to the startService() method, the call to the startService() method will not be
nested. No matter how many requests or calls to the startService() method made, but the service
will be stopped once the stopService() or stopSelf() method is called. . In bound service, the
component that starts the service can create a Pendinglntent[it is a token that is given to another
app (e.g. NotificationManager, AlarmManager, Home Screen AppWidgetManager), which allows
that app to use current app‘s permissions to execute a predefined piece of code] object and pass
this intent object to the caller service components. The service can then use this object to send a
result back to the calling component.
3. Stopping a Service
As discussed previously service is independent block of code, it needs to be manage its own
lifetime. The service will be running in the background until android platform regain the
memory occupied by the service. When service is ideal for long time, it has to be stopped by
itself by calling stopSelf() callback method. To destroy the service explicitly we need to call
the stopServcie(Intent Service) callback method. Unlike the onStartCommand() method, only
one call to the stopService or stopSelf() method destroys the service.
Example
This example will take us through simple steps to show how to create our own Android Service.
No Step
s
1 Create an android project in android studio.
For example, an app initiates broadcast message to another app stating that some data has
been downloaded to the device and available for use. Broadcast receiver will intercept this
communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents:
Normal Broadcasts
Ordered Broadcasts
cseitquestions.blogspot.in cseitquestions.blogspot.in
1. Normal Broadcasts
The broadcasts messenger sends message in undefined order to all the registered receivers
at the same time. For example, the broadcasts, such as battery low
(ACTION_BATTERYLOW) or timezone changed (ACTION_TIMEZONE_CHANGED) will be
received by all the registered receivers at the same time. This type of broadcasts are sent
using the sendBroadcast() method of the android.content.Context class.
Syntax
public abstract void sendBroadcast(Intent intent, String receiverPermission)
The fisrt parameter is Intent object that has to be broadcasted. All broadcast
receivers with intent filters matching this intent will receive thes broadcast.
The second parameter is receiverPermission. It is an optional parameter that
specifies a permission that a broadcast receiver must have in order to receive
the broadcast.
2. Ordered Broadcasts
The broadcast messenger sends message to all the registered receivers in an ordered manner, which
means that a broadcast is delivered to one receiver at a time. When a receiver receives a broadcast,
it can either propagate the broadcast to the next receiver or it can completely abort the broadcast. If a
broadcast message is aborted by a receiver, it will not be passed to other receivers.
This type of broadcasts are sent using the sendOrderedBroadcast() method of the
android.content.BroadcastReceiver class.
Syntax
public abstract void sendOrderedBroadcast (Intent intent, String receiverPermission)
The onReceive() method is called when a broadcast receiver receives a broadcast intent object. This
method must include the code that needs to be executed when a broadcast is received. This method
is usually called within the main thread of its process. Therefore, we should not perform long-running
operations in this method. The system allows a timeout of 10 seconds before considering the receiver
to be blocked. The system can kill a receiver that has been blocked. Also, we cannot launch a pop-up
dialog in our onReceive ( ) method implementation. The signature of the onReceive () method is:
where,
• context is the context in which the receiver is running.
• intent is the Intent object being received.
To declare a broadcast receiver in the manifest file, you need to add a <receiver> element
as a child of the <application> element by specifying the class name of the broadcast
receiver to register. The <receiver> element also needs to include an <intent-filter> element
that specifies the action string being listened for.
Static Registering
Example:
<application android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver
android:name="MyReceiver"><intent
-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED">
</action></int
ent-filter>
</receiver>
cseitquestions.blogspot.in cseitquestions.blogspot.in
</application>
cseitquestions.blogspot.in cseitquestions.blogspot.in
There are several system generated events defined as final static fields in the Intent class.
The following table lists a few important system events.
Dynamic Registering
We can register a broadcast receiver using the registerReceiver() method. The
registerReceiver() method is called with a broadcast intent that matches the filter in the main
app thread. The signature of the registerReceiver() method is :
where,
receiver describes the broadcast receiver to handle the broadcast.
filter describes the intents that the broadcast receiver can receive.
The following code snippet shows how to register a broadcast receiver dynamically:
To broadcast an event using intents, we need to create an Intent object and specify its
action, data, and category components in such a way that the registered broadcast receivers
are able to identify the event accurately.
The following code snippet illustrates the broadcasting of an event using intents:
Step 3: Right Click res -> New -> Android Resource directory -> select ―raw‖
Resourcetype -> Ok
Step 5: After creating the layout, open the manifest file named
AndroidManifest.xml.Define the receiver using the <receiver> tag.
cseitquestions.blogspot.in cseitquestions.blogspot.in
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
><activity android:name=".MainActivity"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/></intent-filter>
</activity>
<receiver android:name="alaram"/>
</application>
</manifest>
alaram.java
package com.example.kamarajios33.alaram;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; import
android.media.MediaPlayer; import
android.widget.*;
/**
* Created by kamarajios33 on
13/11/15. */
public class alaram extends
BroadcastReceiver { MediaPlayer m;
cseitquestions.blogspot.in cseitquestions.blogspot.in
{
m = MediaPlayer.create(context,R.raw.cine1);
m.start();
Toast.makeText(context, "Alarm....Get up", Toast.LENGTH_LONG).show();
}}
MainActivity.java
package com.example.kamarajios33.alaram;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
}
}
Step 8: Run the Project, While running, the following output will be shown
inemulator.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Objectives
After completing this chapter we will be able to understand the following topics.
• What is GPS
• Android Location API
Android devices use the same global positioning technology as Google Maps and most third-
party GPS tools do. This allows users to locate themselves on a map, find and navigate to
destinations via detailed directions, and search maps using a number of different methods.
There are two ways to get Android GPS service. They are
• Android Location API
• Google Maps API
display, and touch gestures on the map. We can also use API calls to add markers,
polygons and overlays, and to change the user's view of a particular map area.
The key class in the Google Maps Android API is MapView. A MapView displays a map with
data obtained from the Google Maps service. When the MapView has focus, it will capture
keypresses and touch gestures to pan and zoom the map automatically, including handling
network requests for additional maps tiles. It also provides all of the UI elements necessary
for users to control the map. Our application can also use MapView class methods to control
the map programmatically and draw a number of overlays on top of the map.
Location
The Location class represents a geographic location. A location can consist of a latitude,
longitude, timestamp, and other information such as bearing, altitude and velocity.
LocationListener
Used for receiving notifications from the LocationManager when the location has changed.
LocationManager
The LocationManager class provides access to the Android location service. This services allows
to access location providers, to register location update listeners and proximity alerts and more.
LocationProvider
The LocationProvider class is the superclass of the different location providers which deliver
the information about the current location. This information is stored in the Location class.
Address
Address is a class representing an address, i.e, a set of Strings describing a location. The
addres format is a simplified version of xAL (eXtensible Address Language)
GeoCoder
Using the Geocoder class in the Android framework location APIs, you can convert an
address to the corresponding geographic coordinates. This process is called geocoding.
Alternatively, you can convert a geographic location to an address. The address lookup
feature is also known as reverse geocoding.
The Android device might have several LocationProvider available and you can select which
one you want to use. In most cases you have the following LocationProvider available.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Typically you would open an AlarmDialog prompt the user and if he wants to enable GPS or
if the application should be canceled. You cannot enable the GPS directly in your code, the
user has to do this.
Step 1:
To use GPS in your application first of all you must specify the uses-permission in Android
manifest file:
AndroidManifest.xml
<manifest><uses
-permission
android:name="android.permission.ACCESS_FINE_LOCATION"></uses-
permission>
import java.io.IOException;
import java.util.List; import
java.util.Locale;
import android.app.Activity; import
android.content.Context; import
android.location.Address; import
android.location.Geocoder; import
android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
super.onCreate(savedInstanceState); setContentView(R.layout.main);
gpsLocationView=(TextView) findViewById(R.id.gps_text);
LocationManager mlocManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, mlocListener);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
@Override
public void onProviderDisabled(String provider)
{
Toast.makeText(getApplicationContext(),"Gps
Disabled",Toast.LENGTH_SHORT ).show();
@Override
public void onProviderEnabled(String provider)
{
Toast.makeText(getApplicationContext(),"Gps
Enabled",Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
Output
cseitquestions.blogspot.in cseitquestions.blogspot.in
Objectives
After completing this chapter we will be able to understand the following topics.
• Debugging
• Android App Development Life Cycle
• APK Conversion Process
• App Publishing Guidance
• Tips for Launching an App
1. Debugging
The Android SDK provides most of the tools that you need to debug your applications. You
need a JDWP-compliant debugger if you want to be able to do things such as step through
code, view variable values, and pause execution of an application. If you are using Android
Studio, a JDWP- compliant debugger is already included and there is no setup required. If
you are using another IDE, you can use the debugger that comes with it and attach the
debugger to a special port so it can communicate with the application VMs on your devices.
The main components that comprise a typical Android debugging environment are:
adb
adb acts as a middleman between a device and your development system. It provides
various device management capabilities, including moving and syncing files to the emulator,
running a UNIX shell on the device or emulator, and providing a general means to
communicate with connected emulators and devices.
The Dalvik VM (Virtual Machine) supports the JDWP protocol to allow debuggers to attach to a
VM. Each application runs in a VM and exposes a unique port that you can attach a debugger to
via DDMS. If you want to debug multiple applications, attaching to each port might become
tedious, so DDMS provides a port forwarding feature that can forward a specific VM's debugging
port to port 8700. You can switch freely from application to application by highlighting it in the
Devices tab of DDMS. DDMS forwards the appropriate port to port 8700. Most modern Java IDEs
include a JDWP debugger, or you can use a command line debugger such as jdb.
DDMS
Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides
port-forwarding services, screen capture on the device, thread and heap information on the device,
logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing,
and more. This page provides a modest discussion of DDMS features; it is not an exhaustive
exploration of all the features and capabilities. The following operation done using DDMS
• Viewing heap usage for a process
• Tracking memory allocation of objects
• Working with an emulator or device's file system
• Examining thread information
• Starting method profiling
• Network Traffic tool
• LogCat
• Emulating phone operations and location
You will need to export your application as an APK (Android Package) file before you upload
it Google Play marketplace.
To export an application, just open that application project in Android studio and selectBuild
→ Generate Signed APK from your Android studio and follow the simple steps to export your
application.
Exporting (generating signed APK) your application from Android Studio for installing on
mobile devices. Application is exported with apk extension.
cseitquestions.blogspot.in
cseitquestions.blogspot.in
Example
a. Open Android Studio and first project Hello World
c. In next window Generate Signed APK Wizard on Key store path chooseCreate new…
cseitquestions.blogspot.in cseitquestions.blogspot.in
d. Complete the fields. On Key store path you choose a path and a name for your jks (we
choose signature for this example). On Password you choose your own
password. Click OK.
g. You find your app in project folder ->HelloWorld -> app -> app-release.apk.
h. You can rename your apk application, copy in mobile device and install it.
You usually perform the tasks listed in figure 2 after you have throroughly debugged and
tested your application. The Android SDK contains several tools to help you test and debug
your Android applications.
Cryptographic keys
The Android system requires that each installed application be digitally signed with a certificate
that is owned by the application's developer (that is, a certificate for which the developer holds
the private key). The Android system uses the certificate as a means of identifying the author of
an application and establishing trust relationships between applications. The certificate that you
use for signing does not need to be signed by a certificate authority; the Android system allows
you to sign your applications with a self-signed certificate.
Important: Your application must be signed with a cryptographic key whose validity period
ends after 22 October 2033.
You may also have to obtain other release keys if your application accesses a service or uses a
third-party library that requires you to use a key that is based on your private key. For example,
cseitquestions.blogspot.in cseitquestions.blogspot.in
if your application uses the MapView class, which is part of the Google Maps external library, you
will need to register your application with the Google Maps service and obtain a Maps API key.
Application Icon
Be sure you have an application icon and that it meets the recommended icon guidelines.
Your application's icon helps users identify your application on a device's Home screen and
in the Launcher window. It also appears in Manage Applications, My Downloads, and
elsewhere. In addition, publishing services such as Google Play display your icon to users.
Note: If you are releasing your application on Google Play, you need to create a high resolution
version of your icon. See Graphic Assets for your Application for more information.
Miscellaneous Materials
You might also have to prepare promotional and marketing materials to publicize your
application. For example, if you are releasing your application on Google Play you will need to
prepare some promotional text and you will need to create screenshots of your application.
Important: Ensure that you disable debugging for your app if using WebView to display paid
for content or if using JavaScript interfaces, since debugging allows users to inject scripts
and extract c o n t e n t u s i n g C h r o m e D e v T o o l s . T o d i s a b l e d e b u g g i n g ,
u s e t h e WebView.setWebContentsDebuggingEnabled() method.
Also, if your application fetches content from a remote server or a real-time service (such as
a content feed), be sure the content you are providing is up to date and production-ready.
You can check a detailed publishing process at Android official website, but this topic will
take you through simple steps to launch your application on Google Play. Here is a
simplified check list which will help you in launching your Android application
Ste Activit
p y
Regression Testing Before you publish your application, you need to make sure
that its meeting the basic quality expectations for all Android apps, on all of the
1
devices that you are targeting. So perform all the required testing on different
devices including phone and tablets.
Application Rating When you will publish your application at Google Play, you
will have to specify a content rating for your app, which informs Google Play
2
users of its maturity level. Currently available ratings are (a) Everyone (b) Low
maturity (c) Medium maturity (d) High maturity.
3 Targeted Regions Google Play lets you control what countries and territories
where your application will be sold. Accordingly you must take care of setting
cseitquestions.blogspot.in cseitquestions.blogspot.in
SDK and Screen Compatibility It is important to make sure that your app is
5 designed to run properly on the Android platform versions and device
screen sizes that you want to target.
Application Pricing Deciding whether you app will be free or paid is important
6 because, on Google Play, free app's must remain free. If you want to sell
your application then you will have to specify its price in different currencies.
8 will upload to the Developer Console and distribute to users. You can
check complete detail on how to create a release-ready version of your
app: Preparing for Release.
Standard HTML5 -This project code base uses HTML5 and JavaScript* code, may use
W3C*standard APIs, but does not support the use of Apache Cordova* APIs (aka Cordova*
plug-ins). It can be deployed as a packaged hybrid mobile app on many platforms
(Android*, Android Crosswalk*, Apple iOS* and Microsoft Windows 8*) or as a hosted web
app for certain web- or OS-based platforms.
HTML5 + Cordova -This project code base uses HTML5 and JavaScript* code, and supports the useof
Apache Cordova* APIs (via Cordova* plug-ins). It can be built and deployed as a packaged hybrid
mobile app for Android*, Android Crosswalk*, Apple iOS*, and Windows 8* devices.
Internet of Things embedded apps (Intel® XDK IoT Edition only) - This project code base
consists ofembedded JavaScript* intended for execution on a Node.js runtime. This project
type is only recognized by the Intel XDK IoT Edition. It requires an IoT maker board and is
not built like mobile web apps for phones and tablets.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Let‘s jump-start this tutorial using a working, HTML5+Cordova demo app as the base
for your new app.
If this is your first project in the Intel XDK - The Intel XDK displays the START A
NEW PROJECTpalette in the PROJECTS tab and offers an opportunity to take
a Quick Tour when project setup is complete.
You already have active projects in the Intel XDK - Click the PROJECTS tab drop-
down arrow to display the YOUR INTEL® XDK PROJECTS dashboard. Then click the
START A NEW PROJECTbutton to display the START A NEW PROJECT palette.
Get to Know the START A NEW PROJECT Palette on the PROJECTS Tab
6. In the LIVE DEVELOPMENT TASKS palette in the DEVELOP tab, click Live
Layout Editing to display preview options similar to the following.
2. Click the Run in Emulator icon to display an Intel XDK Emulator floating window
similarto the following.
Sl Descriptio
n
NO
Use the Intel XDK Emulator floating window to quickly identify and fix defects
before you test your app on an actual mobile device. You can simulate app functionality
on a variety of virtual devices using this device simulator based on the Apache Ripple*
emulator. You can also launch a built-in version of the CDT debugger from this floating
1 window to debug app functionality. (We will do this later in this tutorial.)
Use the toolbar buttons to reload your app source files and restart your app, launch the
2 built-in debugger in another floating window, display and change emulator settings,
and stop executing the app in the emulator.
Use the Auto Zoom icon to zoom the device visual representation to the
maximum size that fully fits in the window, and the slider to manually resize the
3
device visual representation.
Use the palettes in the accordion-style columns to configure various virtual devices
that help you quickly determine how well your app works in different orientations and
4 a variety of screen sizes and aspect ratios. You can open and close each palette, hide
and show the columns, move columns, and move palettes within a column.
5 Use the device visual representation view and test your app.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Play with Your App, Virtual Device Skins, and Palettes
Running your XDKTutorial app - How can you possibly resist clicking the Beep! button?
Choosing a different virtual device - Click the DEVICES palette drop-down arrow and
choose among the skins.
Changing virtual device orientation - Click the orientation icons in the DEVICES palette.
Opening and closing each palette - Click the palette header bar.
Hiding and showing each palette column - Click the and controls.
Moving a palette - Click and drag a palette header bar to move it up or down the palette
column or to another column.
More Handy Information
The emulator is also accessible from the EMULATE tab.
The Intel XDK Emulator floating window is also accessible by clicking the Undock
icon at the top right corner of the EMULATE tab label.
The Undock icon at the top right corner of the EMULATE tab label changes to a Dock
icon and the EMULATE tab is disabled when the Intel XDK Emulator floating window is
displayed. To re-enable the EMULATE tab, either close the floating window or click the
Dock icon at the top right corner of the EMULATE tab label.
The emulator is actually a web app that runs inside a node webkit. Your app runs
within an inner HTML frame.
The runtime engine rendering your HTML5 code in the emulator is based on the
Chromium open source browser. This up-to-date web runtime engine may implement
HTML5 features more correctly than the web runtime on a real mobile device, especially
if that mobile device has an old OS version.
Previous versions of the Intel XDK or appMobi* software refer to appmobi.js in
source files. Replace all mentions of appmobi.js with intelxdk.js.
The emulator does not support the use of *.mp3 audio files.
Sl Descriptio
1 Use the DEVELOP tab to edit files and add files to your project. You can use the built-
in code editor or your favorite code editor.
2 Use the file tree to view the files associated with the active project, including image
files, and to choose a file for editing.
3 Use the menu options (or equivalent shortcut keys) to perform common code editor
functions.
4 Use the code editor view to edit file contents. Context menus are also available.
Use the Intel XDK toolbar buttons (present on all tabs) to access Help information for
the displayed tab and general Help information, start the Quick Tour, display and change
5 Intel XDK settings, view recent Twitter Tweets* about the Intel XDK, and display and
change account settings.
Use the LIVE DEVELOPMENT TASKS palette to preview your code in a browser, on
a real mobile device, or on virtual devices. Notice the XDKTutorial app is still running in
the Intel XDK Emulatorfloating window and is set to restart after you save your
6 changes to project files. With Live Editing Layout, code changes appear immediately
after you make your edits using the built-in code editor, or after you save project files
using an external editor.
Use the WEB SERVICES palette to explore built-in third-party web service APIs
7 (cloud services) as well as integrate other third-party web service APIs. This tutorial
does not cover web services. See theDevelop Overview for more information.
1. Use the built-in code editor to uncomment <script src="js/debug.js"></script> near line 10.
2. Choose File > Save to save your edit and change the contents of the Intel XDK
Emulator floating window.
More Handy Information
The built-in code editor is based on the Brackets* editor, so you can easily add
Brackets* extensions (File > Extension Manager).
If you use a code editor external to the Intel XDK, you must click the Reload App icon
on the toolbar to update all files and restart your app when you return to the emulator.
cseitquestions.blogspot.in cseitquestions.blogspot.in
If you create an app using the App Designer (Hello World demo files were not created with the App
Designer), the Intel XDK offers the CODE and DESIGN views in the DEVELOP tab so you can
switch back and forth between the built-in code editor and the drag-and-drop HTML5 layout editor
The App Designer editor is available only when you are editing HTML5 files created
with the editor.
The App Designer is a round-trip editor. For example, you can start creating your apps in the
App Designer, switch to the code editor to view the code corresponding to your layout
efforts, modify code in the code editor, then switch back to the App Designer to view those
modifications – as long as you do not change the App Designer class=‖uib*‖ tag labels
(uib stands for user interface builder).
Any elements the App Designer does not recognize are still rendered in the
DESIGN view; however, they are not editable in the DESIGN view.
1. Click the Launch Debugger icon on the Intel XDK Emulator toolbar to open a
built-in version of the CDT debugger in a floating window.
2. Click the Sources button to open a file.
3. Press Ctrl+O and choose the debug.js file.
Caution: Modifying code in the debugger window impacts future app behavior in the emulator;
however it does not modify actual source code, so make your source code modifications in
the DEVELOP tab.
Now try clicking the Bad button in the Intel XDK Emulator floating window. Better? If not,
click the the Reload App icon on the toolbar and try again.
Sl No Descriptio
Use the TEST tab to evaluate - over the network - how your app looks and performs
1 on real physical hardware without performing a full build.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Use the MOBILE button to test via a test server in the cloud. Advantages: Requires
minimal setup; avoids potential firewall and network topography issues; you can pull
your files down anytime from anywhere in the cloud. Use the WIFI button to test via
2 a local Wi-Fi network to which both your development machine and test mobile
device are connected. Advantages: Usually faster once set up; does not
consume mobile data; pulls files directly from your development machine.
3 Use the instructions as a refresher for testing via mobile or Wi-Fi, with or
without the App Preview QR code reader.
4 Use the PUSH FILES button to push the most recent project files
on your development machine to the test server in the cloud.
Use the QR code with the App Preview QR code reader (accessible from the camera
icon) to launch your app on your test mobile device. Tip: Alternatively, you can
5
launch your app from the Server Apps list (MOBILE mode) or Local
Appslist (WIFI mode) on the App Preview tool.
You can also remotely debug your app while it runs on real physical hardware using
6 the TEST tab and the weinre* (which stands for web inspector remote) debug console.
cseitquestions.blogspot.in cseitquestions.blogspot.in
More Handy Information
App Preview keeps track of all the apps you upload to the test server.
What you are actually testing on the real physical hardware is your app loaded into a
platform-specific container app that is representative of the native wrapper included with
your app when you build your app.
Android* mobile devices: If you cannot access the Google* Play Store, click
the Informationicon to email the App Preview download to your mobile device or copy
the AppPreview download link to your clipboard.
4. Package Options
Check Your App Package Options
Now that you are confident the XDKTutorial app works properly on a real mobile device, it is
time to build your app. But let's check your app package options first. Click the PROJECTS
tab to display a window similar to the following.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Get to Know the PROJECTS Tab
Sl Descriptio
No n
Use the PROJECTS tab to manage projects and project information, including options
1 to package your app for submission to app stores.
2 The YOUR INTEL® XDK PROJECTS dashboard lists all known Intel XDK
projects on your development machine.
The Intel XDK operates on only one project at a time. The currently active project is
always marked in the YOUR INTEL® XDK PROJECTS dashboard and is the
project on which all other tabs operate.
3 All your project files are stored locally on your development machine.
The Source Directory is the root location of your sources, including
the index.html file, which is the main entry point to your project. The Source Directory
and the Project Path may or may not refer to the same directory location, but the root
Source Directory must be at or below the Project Path.
4 NOTE: If you plan to build your app using Cordova* 2.x APIs instead of Cordova*
3.x APIs, specify package options in the BUILD tab instead of the PROJECTS tab.
Use CORDOVA 3.X HYBRID MOBILE APP SETTINGS to generate platform-
specific intelxdk.conf.<platform>.xml configuration files when you upload your app
to the build server for packaging. These configuration files are then stored in your
project directory.
Plug-ins provide a way to extend your app JavaScript* APIs, resulting in a tighter
integration between your app and mobile device software and hardware.
Use PLUGINS AND PERMISSIONS to specify standard Cordova* 3.x plug-ins,
featured and custom Cordova* plug-ins, Intel XDK plug-ins, additional third-party plug-
ins, and platform-specific permissions in addition to permissions required by chosen plug-
ins. Use BUILD SETTINGS to specify details typically needed by app stores. Use
LAUNCH ICONS AND SPLASH SCREENS to choose orientation, icons, and splash
screens. See the Projects Overview for more information.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Explore Your App Package Options
Take a moment to check out your app package options. When you are ready to submit your
own apps to various app stores, you will need to supply values, such as App ID, App Name,
and App Description. The default values are sufficient for this tutorial.
Sl Descriptio
NO n
Use the BUILD tab to:
Package your app and deploy it as locally installed hybrid mobile app, thereby
enabling the use of the same distribution and monetization channels, as well as the
1 same app download, installation, and launch experience as native mobile apps.
Create an HTML5 bundle you can submit to certain app stores (such as
the Google Chrome* Web Store) or place (hosted) on web servers.
2 Use the PREVIOUS BUILDS palette to view (and refresh) a list of previous
builds. You can also hide/show the entire PREVIOUS BUILDS palette.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Use CORDOVA 3.X HYBRID MOBILE APP PLATFORMS to create a native
app package suitable for submission to app stores. Packages support
Cordova* 3.x core APIs and selected plug-ins, and Intel XDK APIs. See the
Projects Overview for more information.
4
The Tizen* OS is an open source, standards-based, software platform for
devices such as smart phones, tablets, netbooks, in-vehicle infotainment
devices, and smart TVs. See the Build Tab Overview for more information.
NOTE: If your app is a Standard HTML5 project type instead of an HTML5 + Cordova
project type, the Build tab also includes a BUILD AS A WEB APP region.
cseitquestions.blogspot.in cseitquestions.blogspot.in
Package Your App as a Mobile App for an Android* Store
1. Click the Android BUILD button in the CORDOVA 3.X HYBRID MOBILE APP
PLATFORMSregion to connect to the build server, upload your XDKTutorial app to the
cloud, and display a window similar to the following.
2. Notice all packaging configuration has already been performed (in the PROJECTS tab); there is
nothing preventing you from building your XDKTutorial app right now. Click the Build App
Nowbutton to build the XDKTutorial app as an Android* mobile app and ultimately display a
window similar to the following.
If the build fails, click the link to review a more detailed build log.
The Intel XDK does not provide actual store submission services for your app; however, it does
explain a variety of possible next steps (which we obviously will not perform for this
XDKTutorialapp).
Click the Close Build Page button.