MC4204 - Mobile Application Development
MC4204 - Mobile Application Development
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
Scanned by TapScanner
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
pg. 1
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.
Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout
may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is a
simple example of XML file having LinearLayout −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />
pg. 2
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction,
vertically or horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a
single view.
6 List View
ListView is a view group that displays a list of scrollable items.
pg. 3
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable
grid.
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 their are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
1
android:id
This is the ID which uniquely identifies the view.
2
android:layout_width
This is the width of the layout.
3
android:layout_height
This is the height of the layout
4
android:layout_marginTop
This is the extra space on the top side of the layout.
5
android:layout_marginBottom
This is the extra space on the bottom side of the layout.
6
android:layout_marginLeft
This is the extra space on the left side of the layout.
7
android:layout_marginRight
This is the extra space on the right side of the layout.
8
android:layout_gravity
pg. 4
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
9
android:layout_weight
This specifies how much of the extra space in the layout should be allocated to
the View.
10
android:layout_x
This specifies the x-coordinate of the layout.
11
android:layout_y
This specifies the y-coordinate of the layout.
12
android:layout_width
This is the width of the layout.
13
android:paddingLeft
This is the left padding filled for the layout.
14
android:paddingRight
This is the right padding filled for the layout.
15
android:paddingTop
This is the top padding filled for the layout.
16
android:paddingBottom
This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of
dp (Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an
inch), px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
android:layout_width=wrap_content tells your view to size itself to the dimensions
required by its content.
pg. 5
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
top 0x30 Push object to the top of its container, not changing
its size.
left 0x03 Push object to the left of its container, not changing
its size.
right 0x05 Push object to the right of its container, not changing
its size.
center_vertical 0x10 Place object in the vertical center of its container, not
changing its size.
center 0x11 Place the object in the center of its container in both
the vertical and horizontal axis, not changing its size.
fill 0x77 Grow the horizontal and vertical size of the object if
needed so it completely fills its container.
clip_vertical 0x80 Additional option that can be set to have the top
and/or bottom edges of the child clipped to its
container's bounds. The clip will be based on the
pg. 6
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
clip_horizontal 0x08 Additional option that can be set to have the left
and/or right edges of the child clipped to its
container's bounds. The clip will be based on the
horizontal gravity: a left gravity will clip the right
edge, a right gravity will clip the left edge, and
neither will clip both edges.
end 0x00800005 Push object to the end of its container, not changing
its size.
View Identification
A view object may have a unique ID assigned to it which will identify the View uniquely within
the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
Following is a brief description of @ and + signs −
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. To create an instance of the view object and capture it from the
layout, use the following −
Button myButton = (Button) findViewById(R.id.my_button);
pg. 7
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
UI Elements
A View is an object that draws something on the screen that the user can interact with and
a ViewGroup is an object that holds other View (and ViewGroup) objects in order to define the
layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the layout,
similar to HTML. For example, a simple vertical layout with a text view and a button looks like
this −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>
Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical user
interface for your app.
pg. 8
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
1 TextView
This control is used to display text to the user.
2 EditText
EditText is a predefined subclass of TextView that includes rich editing
capabilities.
3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it
shows a list of completion suggestions automatically while the user is typing.
4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.
5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact
location of its children. This shows a button with an image (instead of text)
that can be pressed or clicked by the user.
6 CheckBox
An on/off switch that can be toggled by the user. You should use check box
when presenting users with a group of selectable options that are not mutually
exclusive.
7 ToggleButton
An on/off button with a light indicator.
8 RadioButton
The RadioButton has two states: either checked or unchecked.
9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.
pg. 9
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks,
such as when you are performing a task in the background.
11 Spinner
A drop-down list that allows users to select one value from a set.
12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode.
13 DatePicker
The DatePicker view enables users to select a date of the day.
Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides a
wide variety of controls you can use in your UI, such as buttons, text fields, seek bars, check
box, zoom buttons, toggle buttons, and many more.
As explained in previous chapter, a view object may have a unique ID assigned to it which will
identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/text_id"
To create a UI Control/View/Widget you will have to define a view/widget in the layout file and
assign it a unique ID as follows −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Then finally create an instance of the Control object and capture it from the layout, use the
following −
TextView myText = (TextView) findViewById(R.id.text_id);
pg. 10
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
OnClickListener()
onClick() This is called when the user either clicks or touches or
focuses upon any widget like button, text, image etc. You
will use onClick() event handler to handle such event.
OnLongClickListener()
OnFocusChangeListener()
onFocusChange() This is called when the widget looses its focus ie. user goes
away from the view item. You will use onFocusChange()
event handler to handle such event.
pg. 11
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
OnFocusChangeListener()
onKey() This is called when the user is focused on the item and
presses or releases a hardware key on the device. You will
use onKey() event handler to handle such event.
OnTouchListener()
onTouch() This is called when the user presses the key, releases the key,
or any movement gesture on the screen. You will use
onTouch() event handler to handle such event.
OnMenuItemClickListener()
onMenuItemClick()
This is called when the user selects a menu item. You will
use onMenuItemClick() event handler to handle such event.
onCreateContextMenuItemListener()
onCreateContextMenu()
This is called when the context menu is being built(as the
result of a sustained "long click)
There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc which may be needed for your application. So I recommend to refer official
documentation for Android application development in case you are going to develop a
sophisticated apps.
Event Listeners Registration
Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are
several tricky ways to register your event listener for any event, but I'm going to list down only
top 3 ways, out of which you can use any of them based on the situation.
Using an Anonymous Inner Class
Activity class implements the Listener interface.
Using Layout file activity_main.xml to specify event handler directly.
Below section will provide you detailed examples on all the three scenarios −
Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by
touching the on-screen virtual buttons, images, etc.You can check if the device is in touch mode
by calling the View class‟s isInTouchMode() method.
pg. 12
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Focus
A view or widget is usually highlighted or displays a flashing cursor when it‟s in focus. This
indicates that it‟s ready to accept input from the user.
isFocusable() − it returns true or false
isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A
view may be focusable when using a hardware key but not when the device is in touch
mode)
android:foucsUp="@=id/button_l"
onTouchEvent()
public boolean onTouchEvent(motionEvent event){
switch(event.getAction()){
case TOUCH_DOWN:
Toast.makeText(this,"you have clicked down Touch button",Toast.LENTH_LONG).show();
break();
case TOUCH_UP:
Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
break;
case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}
pg. 13
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Step Description
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.myapplication as explained in
the Hello World Example chapter.
2 Modify src/MainActivity.java file to add click event listeners and handlers for
the two buttons defined.
5 Run the application to launch Android emulator and verify the result of the
changes done in the aplication.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = new ProgressDialog(this);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
pg. 14
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(25);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setTextSize(55);
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
Here abc indicates about tutorialspoint logo
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event Handling "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
<TextView
android:id="@+id/textView2"
pg. 15
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_above="@+id/imageButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small font"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Font"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/textView"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:textSize="25dp" />
</RelativeLayout>
pg. 16
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your myapplication application. I assume you had created your AVD while
doing environment setup. To run the app from Android Studio, open one of your project's
activity files and click Run icon from the toolbar. Android Studio installs the app on your
AVD and starts it and if everything is fine with your setup and application, it will display
following Emulator window −
pg. 17
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Now you try to click on two buttons, one by one and you will see that font of the Hello
World text will change, which happens because registered click event handler method is being
called against each click event.
Exercise
I will recommend to try writing different event handlers for different event types and understand
exact difference in different event types and their handling. Events related to menu, spinner,
pickers widgets are little different but they are also based on the same concepts as explained
above.
1.4 Android - Styles and Themes
A style resource defines the format and look for a UI. A style can be applied to an individual
View (from within a layout file) or to an entire Activity or application (from within the manifest
file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout.
This XML file resides under res/values/ directory of your project and will have <resources> as
the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it
must use the .xml extension.
You can define multiple styles per file using <style> tag but each style will have its name that
uniquely identifies the style. Android style attributes are set using <item> tag as shown below −
<?xml version="1.0" encoding="utf-8"?>
<resources>
pg. 18
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>
The value for the <item> can be a keyword string, a hex color, a reference to another resource
type, or other value depending on the style property.
Using Styles
Once your style is defined, you can use it in your XML Layout file using style attribute as
follows −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />
</LinearLayout>
To understand the concept related to Android Style, you can check Style Demo Example.
Style Inheritance
Android supports style Inheritance in very much similar way as cascading style sheet in web
design. You can use this to inherit properties from an existing style and then define only the
properties that you want to change or add.
To implement a custom theme create or edit MyAndroidApp/res/values/themes.xml and add the
following −
<resources>
...
<style name="MyCustomTheme" parent="android:style/Theme">
<item name="android:textColorPrimary">#ffff0000</item>
</style>
...
</resources>
pg. 19
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
In your AndroidManifest.xml apply the theme to the activities you want to style −
<activity
android:name="com.myapp.MyActivity"
...
android:theme="@style/MyCustomTheme"
/>
Your new theme will be applied to your activity, and text is now bright red.
pg. 20
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
pg. 21
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
<item name="android:buttonStyle">@style/MyCustomButton</item>
</style>
...
</resources>
Android Themes
Hope you understood the concept of Style, so now let's try to understand what is a Theme. A
theme is nothing but an Android style applied to an entire Activity or application, rather than an
individual View.
Thus, when a style is applied as a theme, every View in the Activity or application will apply
each style property that it supports. For example, you can apply the
same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will
have green monospace font.
To set a theme for all the activities of your application, open the AndroidManifest.xml file and
edit the <application> tag to include the android:theme attribute with the style name. For
example −
<application android:theme="@style/CustomFontStyle">
But if you want a theme applied to just one Activity in your application, then add the
android:theme attribute to the <activity> tag only. For example −
<activity android:theme="@style/CustomFontStyle">
There are number of default themes defined by Android which you can use directly or inherit
them using parent attribute as follows –
pg. 22
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Above layout has designed based on style.xml file,Which has placed at res/values/
<resource>
<style name="AppTheme" parent="android:Theme.Material">
<item name ="android:color/primary">@color/primary</item>
<item name ="android:color/primaryDark">@color/primary_dark</item>
<item name ="android:colorAccent/primary">@color/accent</item>
</style>
<resource>
pg. 23
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
1 You will use Android studio IDE to create an Android application and name it
as myapplication under a package com.example.tutorialspoint7.myapplication as
explained in the Hello World Example chapter.
pg. 24
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
2 Create an XML res/values/attrs.xml file to define new attributes along with their
data type.
3 Create src/mainactivity.java file and add the code to define your custom
component
5 Run the application to launch Android emulator and verify the result of the
changes done in the application.
Create the following attributes file called attrs.xml in your res/values folder.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TimeView">
<declare-styleable name="TimeView">
<attr name="title" format="string" />
<attr name="setColor" format="boolean"/>
</declare-styleable>
</declare-styleable>
</resources>
Change the layout file used by the activity to the following.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.tutorialspoint7.myapplication.TimeView
android:id="@+id/timeView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="40sp"
custom:title="my time view"
custom:setColor="true" />
<TextView
android:layout_width="match_parent"
pg. 25
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
android:layout_height="wrap_content"
android:id="@+id/simple"
android:layout_below="@id/timeView"
android:layout_marginTop="10dp" />
</RelativeLayout>
Create the following java file called timeview for your compound view.
package com.example.tutorialspoint7.myapplication;
/**
* Created by TutorialsPoint7 on 9/14/2016.
*/
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.TextView;
pg. 26
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
setTimeView();
} else if(attr == R.styleable.TimeView_setColor) {
// set the color of the attr "setColor"
color = typedArray.getBoolean(attr, false);
decorateText();
}
}
}
if(this.titleText != null )
setText(this.titleText+" "+time);
else
setText(time);
}
pg. 27
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Change your Main activity java file to the following code and run your application.
package com.example.tutorialspoint7.myapplication;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pg. 28
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Applicability parameters allow a model to use multiple UIs, each targeted to a different channel
of use.
Applicability helps you present the UI that's most appropriate to the context.
You may need to configure the same model in multiple host applications, each having
different UI requirements.
o Host application A is used by self-service customers with elementary knowledge
of your product line. You might need to present a simplified UI for Product X that
guides the user through each step of the configuration, and hides some product
details that might be confusing.
o Host application B is used by internal sales fulfillment staff who are very familiar
with your product line. You might need to present a full-featured UI for Product
X that exposes every option, in a layout that enables users to reach those options
most efficiently.
You may need to present the same product to the same type of audience, but in different
countries. Consequently you need to present the UI in multiple languages.
To provide for such multiple requirements, you can set the applicability parameters for a UI.
On the Overview tab for the UI, you can choose the applications and languages for which your
user interface is applicable.
1. Edit your configurator model and navigate to the Overview subtab of the User Interfaces
tab.
2. Under Applicability, select a parameter:
o Applications sets the applications that the UI will be used for. For example, if
you select Order Management, then the UI will be presented when Configurator
is invoked by Oracle Fusion Order Management.
o Languages sets the languages that the UI will be used for.For example, if you
select Korean and American English, then the UI will be presented when
Configurator is invoked by applications using one of those languages.
3. The default setting for each parameter is All, meaning that the UI is available at run time
to all channels.
4. Select the Selected setting. The Select button becomes enabled.
By default, the currently selected parameter is None. If you leave the setting as None,
then the UI will not be available at run time to any of that parameter's options. If no UIs
are available, then the default UI is used.
pg. 29
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
5. Click the Select button. The selection dialog box for the parameter presents a list of
available options, from which you select one or more to determine the applicability of the
UI.
6. If more than one UI has the same applicability parameter settings, then the sequence of
UIs in the table on the User Interfaces tab determines which UI will be used at run time.
To change the sequence in the table of UIs, select a UI then select one of
the Move commands on the Actions menu.
1.7 GESTURE BASED UI
Tapping, swiping, dragging, long-pressing – these are but a few of the gestures that have come to
dominate our digital experiences. Touch screen iPhones mainstreamed mobile gestures years
ago, and we haven‟t looked back since.
Gestures affect how we interact with interfaces, including phones, laptops and iPads. But we
don‟t have to look far to find a gestural interface beyond our work and entertainment devices.
It‟s no longer uncommon to use gestures when interacting with car screens or bathroom sinks.
Natural User Interfaces (NUIs) are so natural to users that the interface feels, and sometimes is,
invisible, like a touch screen interface. Some NUIs even use gesture control, allowing users to
interact with the interface without direct physical contact. BMW recently released a gesture
control feature that gives users touchless control over car volume, calls and more.
Gestures are growing more common in user interface design and play increasingly complex roles
in our everyday lives.
As technology advances, UX and UI designers and businesses will need to adapt. You don‟t have
to know all the technological intricacies or have an in-depth knowledge of computer intelligence.
Still, you should have a basic understanding of the capabilities, functions and best design
practices for gesture technology.
pg. 30
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
pg. 31
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
Tap
A tap gesture is when you tap on the screen with one finger to open or select something, like an
app or page. Here‟s a tip: Design clickable interface elements so that the entire box or row is
clickable – not just the text. Giving users more space increases usability.
Double-Tap
Double-tapping is when you tap the screen twice in a row in close succession. Many applications
use this gesture to zoom in, but on Instagram, users can double-tap a photo to like it.
Swipe
Swiping involves moving your finger across the screen in one direction, touching down on one
side and lifting your finger on the other. Swipe gestures are often used for scrolling or switching
between pages. Tinder uses swiping right to match with a profile and swiping left to pass over
one.
Multiple-Finger Swipe
You can also conduct a swipe gesture with two or three fingers. This is a common feature on
laptop touchpads that use two- and three-finger swipes for different actions.
Drag
Dragging uses the same general motion as a swipe, only you move your finger slower and don‟t
lift it until you‟ve pulled the object to where you want it to be. You use dragging to move an
item to a new location, like when re-organizing your phone apps.
Fling
Like swiping, a fling gesture is when you move your finger across the screen at a high speed.
Unlike a drag, your finger doesn‟t remain in contact with an element. Flings are often used to
remove something from view.
Long Press
A long press is when you tap the screen but hold your finger down for longer than usual. Long
presses open up menu options, like when you hold text to copy it or hold down an app to delete
it.
Pinch
One of many two-finger gestures, a pinch is when you hold two fingers apart on the screen and
then drag them towards each other in a pinching motion. Pinch gestures are often used to zoom
back out after zooming in. Sometimes they present a view of all your open screens for navigation
purposes.
Pinch-Open or Spread
A pinch-open or spread gesture is the opposite of a pinch. You hold your two fingers down close
together and then spread them apart. Spreading, like double-tapping, is generally used to zoom
in.
Rotation
To do a rotation, press on the screen with two fingers and rotate them in a circular motion. The
best example of rotation is when you turn the map on Google Maps to see what‟s around you.
Gestures have been around for a while, so for most gestures, general guidelines exist.
And in most cases, there are rules you‟ll want to follow when designing gestures for an interface.
When creating an app, for example, you‟ll need to consider which interfaces users will use your
app on. There is the chance that users will download your app on Android and Apple phones,
both of which already use product-specific gestures. You‟ll need to evaluate the gestures of your
pg. 32
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
product‟s interfaces and decide how you‟ll take advantage of them or if it‟s worth it to add
gestures users are not familiar with.
Here are some handy gesture and motion guidelines for popular product interfaces.
Google Gesture Guidelines
Microsoft Gesture Guidelines
Apple Gesture Guidelines
Android Gesture Guidelines
When designing gesture-based user interfaces, it‟s good practice to stick with what users know.
You can get creative if it‟s called for, but a level of consistency among gestures and interfaces
helps keep them intuitive to users, increasing the usability of your product.
If you think a new gesture is in store, you need to test it extensively before implementing it.
You‟ll conduct a series of user research methods to test the usability, effectiveness, learning
curves and user satisfaction with a gesture before releasing it to the public.
You have the option to reuse a well-known gesture for a different purpose, but again, you should
test the effectiveness of this strategy in advance. The benefit here is that users are at least
familiar with the motion.
Take, for example, Instagram‟s use of the double-tap to like or “heart” a post. A double-tap is
usually used to zoom in, but it works well for Instagram‟s purpose. It‟s also a great study in
efficiency: Tapping the heart below a post requires one less tap but more aim. The alternative
double-tap method allows users to scroll faster since they have the whole image to aim for, and
it‟s intuitive to tap the object you‟re liking.
Designers have begun to develop a design language with hands, circles and arrows for
communicating gesture intent to product developers and strategists. This language is near
universal with minimal deviation.
pg. 33
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
driving cars are being enforced with gesture recognition technology to improve their
effectiveness and safety.
But you can still get creative with phone gestures while thinking outside of the screen. Devices
have been using rotation and shaking as methods of interaction for years now.
For example, Apple‟s „Shake to Undo‟ gives users the option to undo an action by shaking their
phone. And by now, you‟re probably familiar with rotating screens horizontally to watch a video
on full screen.
As long as they are tested first, creative gesture technologies can take products further and
increase usability.
Gestures and Accessibility
Gestures, like all things, should be accessible. Accessibility refers to making a product accessible
and usable to all people in all contexts, including people with disabilities. Gestures should adhere
to accessible design best practices to contribute to an equal environment, comply with the
Americans With Disabilities Act (ADA) and allow everyone who could benefit from your
product to use it.
Outside of making sure interface gestures are accessible, it‟s worth considering how you can use
gestures to improve accessibility. Apple realized that the iPhone‟s flat, textureless screens
presented an obstacle to blind users. So, they used their gesture-based interface to create
additional accessibility-based gestures that help the visually impaired use their products.
Don’t Forget UX
It‟s common to use the terms UX and UI interchangeably, but this is an inaccurate practice. UX
stands for user experience, and it deals with the user‟s perceptions and emotions while engaging
with a product. UI stands for user interface and involves the elements of a product a user
interacts with. UI is an important element of UX design. If you‟re interested in learning more
about each and their differences, check out our guide on UX vs UI Design.
The point here is that UX and UI are different, but it‟s critical to consider user experience when
designing interfaces. UI gestures that are fun but unhelpful or interesting but have poor usability
are a result of designers and developers who forgot about UX.
No matter how much testing you did, give users the option to remove certain gesture features.
Tapping is a vital touch screen gesture that everyone is familiar with, but some gestures aren‟t
crucial to a product‟s functioning and exist only to make it more usable. Sometimes, gestures
like these annoy users who aren‟t familiar with them or trigger the gesture without meaning to.
For example, on a Mac, swiping two fingers left or right on the touchpad sends a web browser
back or forward a page. Many users make this gesture by accident and are frustrated when the
page keeps changing. So, Apple gives users the option to disable this feature and many others.
Refine User Onboarding
User onboarding improves the successful use of a product by teaching users how to use it. Think
about a new program that, upon opening for the first time, guides you through all the functions or
steps to use it.
User onboarding is important for touch gestures because they‟re often hidden and easy to miss,
especially if a user isn‟t familiar with a gesture or doesn‟t have experience with it in that context.
If they don‟t know that they can use it or how to use it, they won‟t.
When onboarding a user, you want to be brief, teach one thing at a time and follow the learning
curve proven to work best in testing. Long tutorials and step-by-step lists are boring, less
interactive and often get skipped.
pg. 34
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
The elements that constitute a Screen can be Data Elements, labels, or Screens. You call them
and specify their display characteristics in the Screen layout.
This wizard displays the three Data Element formats in the following order:
internal format, input format, and output format.
Select one or more Data Elements and click OK. Indicate the call values directly
in the table or in the Field definition section. When a field is inserted, you can
add controls to it (such as presence check, validation conditions, update option).
To do so, select a field (a Data Element) in the tree and click Add additional
controls for the field or select this action in the contextual menu. Indicate the call
values directly in the table or in the Additional controls for the field section that
opens.
pg. 35
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204 - MOBILE APPLICATION DEVELOPMENT UNIT - 2
b. A label. To do so, click Add Label or select this action in the contextual menu.
Indicate the call values directly in the table or in the Label definition section that
opens up.
c. A Screen call. To do so, click Add Screen element or select this action in the
contextual menu. Select a Screen in the selection wizard and indicate the call
values directly in the table or in the Screen call definition section.
Voice XML is an Extensible Markup Language (XML) standard for storing and processing
digitized voice, input recognition and defining human and machine voice interaction. Voice
XML uses voice as an input to a machine for desired processing, thereby facilitating voice
application development. A voice-based application is managed by a voice browser.
Voice XML
Voice XML is developed as a standard markup language for delivering and processing voice
dialogs. Voice XML applications include automated driving assistance, voice access to email,
voice directory access and other services. Voice XML pages are transported online via the HTTP
protocol.
Document server: Like a server that accepts client requests and generates appropriate
response post processing
Voice XML interpreter subsystem: Processes request response output generated by the
document server.
Implementation platform: Generates actions in response to user input
Voice XML goals: Integrates voice-based services with Web applications for efficiency
pg. 36
Prepared By. M.Rajeswari.MCA.,M.Phil,.
MC4204_Mobile Application Development Unit-3
Memory Management – Design Patterns for Limited Memory – Workflow for Application
development – Java API – Dynamic Linking – Plugins and rule of thumb for using DLLs –
Multithreading in Java - Concurrency and Resource Management.
What do you understand by the Memory Management?
Android uses paging and mmap instead of providing swap space, which means any
memory your application touches cannot be paged out unless you release all references.
The Dalvik* Virtual Machine‘s heap size for application processes is limited.
Applications start up with 2 MB, and the maximum allocation, marked as ―largeHeap,‖ is
limited to 36 MB (depending on the specific device configuration). Examples of large heap
applications are Photo/Video Editor, Camera, Gallery, and Home Screen.
Android stores background application processes in an LRU cache. When the system
runs low on memory, it will kill processes according to the LRU strategy, but it will also
consider which application is the largest memory consumer. Currently, the maximum
background process count is 20 (depending on the specific device configuration). If you need
your app to live longer in the background, de-allocate unnecessary memory before moving to the
background and the Android system will be less likely to generate an error message or even
terminate the app.
Write a short note on Garbage Collection.
A managed memory environment, like the ART or Dalvik virtual machine, keeps track
of each memory allocation. Once it determines that a piece of memory is no longer being used
by the program, it frees it back to the heap, without any intervention from the programmer. The
mechanism for reclaiming unused memory within a managed memory environment is known
as garbage collection. Garbage collection has two goals: find data objects in a program that
cannot be accessed in the future; and reclaim the resources used by those objects.
Android‘s memory heap is a generational one, meaning that there are different buckets of
allocations that it tracks, based on the expected life and size of an object being allocated. For
example, recently allocated objects belong in the Young generation. When an object stays active
long enough, it can be promoted to an older generation, followed by a permanent generation.
Each heap generation has its own dedicated upper limit on the amount of memory that
objects there can occupy. Any time a generation starts to fill up, the system executes a garbage
collection event in an attempt to free up memory. The duration of the garbage collection depends
on which generation of objects it‘s collecting and how many active objects are in each
generation.
Creational Patterns
Builder
Dependency Injection
Singleton
Factory
Structural Patterns
Adapter
Facade
Decorator
Composite
Behavioral Patterns
Command
Observer
Strategy
State
Creational Patterns
“When I need a particularly complex object, how do I get an instance of it?” – Future You
Future You hopes the answer isn‘t ―Just copy and paste the same code every time you need an
instance of this object―. Instead, Creational patterns make object instantiation straightforward
and repeatable.
Builder
At a certain restaurant, you create your own sandwich: you choose the bread, ingredients and
condiments you‘d like on your sandwich from a checklist on a slip of paper. Even though the
checklist instructs you to build your own sandwich, you only fill out the form and hand it over
the counter. You don‘t build the sandwich, just customize and consume it. :]
Aler
This builder proceeds step-by-step and lets you specify only the parts of AlertDialog that you need
to specify. Take a look at the AlertDialog.Builder documentation. You‘ll see there are quite a few
commands to choose from when building your alert.
A different set of choices would result in a completely different sandwich– er, alert. :]
Dependency Injection
Dependency injection is like moving into a furnished apartment. Everything you need is
already there. You don‘t have to wait for furniture delivery or follow pages of IKEA instructions
to put together a Borgsjö bookshelf.
In software terms, dependency injection has you provide any required objects to instantiate a
new object. This new object doesn‘t need to construct or customize the objects themselves.
In Android, you might find you need to access the same complex objects from various points in
your app, such as a network client, image loader or SharedPreferences for local storage. You
can inject these objects into your activities and fragments and access them right away.
Currently, there are three main libraries for dependency injection: Dagger ‗2‘, Dagger Hilt,
and Koin. Let‘s take a look at an example with Dagger. In it you annotate a class
with @Module, and populate it with @Provides methods like:
The module above creates and configures all required objects. As an additional best practice in
larger apps, you could create multiple modules separated by function.
Then, you make a Component interface to list your modules and the classes you‘ll inject:
The component ties together where the dependencies are coming from, the modules, and where
they‘re going to, the injection points.
Finally, you use the @Inject annotation to request the dependency wherever you need it, along
with lateinit to initialize a non-nullable property after you create the containing object
This pattern may seem complicated and magical at first, but it can help simplify your activities
and fragments.
The Singleton pattern specifies that only a single instance of a class should exist with a global
access point. This pattern works well when modeling real-world objects with only one instance.
For example, if you have an object that makes network or database connections, having more
than one instance of the project may cause problems and mix data. That‘s why in some scenarios
you want to restrict the creation of more than one instance.
The Kotlin object keyword declares a singleton without needing to specify a static instance like
in other languages:
When you need to access members of the singleton object, you make a call like this:
Behind the scenes, an INSTANCE static field backs the Kotlin object. So, if you need to use a
Kotlin object from Java code, you modify the call like this:
By using object, you‘ll know you‘re using the same instance of that class throughout your app.
The Singleton is probably the most straightforward pattern to understand initially but can be
dangerously easy to overuse and abuse. Since it‘s accessible from multiple objects, the singleton
can undergo unexpected side effects that are difficult to track down, which is exactly what
Future You doesn‘t want to deal with. It‘s important to understand the pattern, but other design
patterns may be safer and easier to maintain.
Factory
As the name suggests, Factory takes care of all the object creational logic. In this pattern, a
factory class controls which object to instantiate. Factory pattern comes in handy when dealing
with many common objects. You can use it where you might not want to specify a concrete
class.
// 1
interface HostingPackageInterface {
// 2
STANDARD,
PREMIUM
// 3
return ...
}}
// 4
return ...
}}
// 5
object HostingPackageFactory {
// 6
HostingPackageType.STANDARD -> {
HostingPackageType.PREMIUM -> {
PremiumHostingPackage()
} } }}
val standardPackage =
HostingPackageFactory.getHostingFrom(HostingPackageType.STANDARD)
Structural Patterns
“So, when I open this class, how will I remember what’s it doing and how it’s put together?” –
Future You
Future You will undoubtedly appreciate the Structural Patterns you used to organize the guts of
your classes and objects into familiar arrangements that perform typical
tasks. Adapter and Facade are two commonly-seen patterns in Android.
Adapter
A famous scene in the movie Apollo 13 features a team of engineers tasked with fitting a square
peg into a round hole. This, metaphorically, is the role of an adapter. In software terms, this
pattern lets two incompatible classes work together by converting a class‘s interface into the
interface the client expects.
Consider your app‘s business logic. It might be a Product or a User or Tribble. It‘s the square
peg. Meanwhile, a RecyclerView is the same basic object across all Android apps. It‘s the
Facade
The Facade pattern provides a higher-level interface that makes a set of other interfaces
easier to use. The following diagram illustrates this idea in more detail:
If your Activity needs a list of books, it should be able to ask a single object for that list
without understanding the inner workings of your local storage, cache and API client. Beyond
keeping your Activities and Fragments code clean and concise, this lets Future You make any
required changes to the API implementation without impacting the Activity.
Square‘s Retrofit is an open-source Android library that helps you implement the Facade
pattern. You create an interface to provide API data to client classes like so:
interface
BooksApi {
The client needs to call listBooks() to receive a list of Book objects in the callback. It‘s nice
and clean. For all it knows, you could have an army of Tribbles assembling the list and
sending it back via transporter beam. :]
This lets you make all types of customizations underneath without affecting the client. For
example, you can specify a customized JSON deserializer that the Activity has no clue about:
val retrofit = Retrofit.Builder()
.baseUrl("http://www.myexampleurl.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
Decorator
The Decorator pattern dynamically attaches additional responsibilities to an object to
extended its functionality at runtime. Take a look at the example below:
//1
interface Salad {
//2
//3
open class SaladDecorator(protected var salad: Salad) : Salad {override fun getIngredient():
String {
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 14
MC4204_Mobile Application Development Unit-3
return salad.getIngredient()
//4
//5
. Every salad needs a base. This base is Arugula & Lettuce thus, PlainSalad.
By using the SaladDecorator class, you can extend your salad easily without having to
change PlainSalad. You can also remove or add any salad decorator on runtime. Here‘s how
you use it:
val cucumberSalad = Cucumber(Carrot(PlainSalad()))
print(cucumberSalad.getIngredient()) // Arugula & Lettuce,
Carrot, Cucumberval carrotSalad = Carrot(PlainSalad())
interface Entity {
//2
return name
//3
val ericTeamComposite =
Raywenderlich("Eric")val aaqib =
Team("Aaqib")
Behavioral Patterns
“So… how do I tell which class is responsible for what?” – Future You
Behavioral Patterns let you assign responsibility for different app functions. Future You
can use them to navigate the project‘s structure and architecture.
These patterns can vary in scope, from the relationship between two objects to your
app‘s entire architecture. Often, developers use several behavioral patterns together in the
same app.
Command
When you order some Saag Paneer at an Indian restaurant, you don‘t know which cook
will prepare your dish. You just give your order to the waiter, who posts the order in the
kitchen for the next available cook.
Similarly, the Command pattern lets you issue requests without knowing the receiver. You
encapsulate a request as an object and send it off. Deciding how to complete the request is
an entirely separate mechanism.
Greenrobot‘s EventBus is a popular Android framework that supports this pattern in the
following manner:
An Event is a command-style object that‘s triggered by user input, server data or pretty much
anything else in your app. You can create specific subclasses which carry data as well:
class MySpecificEvent { /* Additional fields if needed */ }
After defining your event, you obtain an instance of EventBus and register an object as a
subscriber. For example, if you register an Activity you‘ll have:
override fun onStart() {
super.onStart()
EventBus.getDefault().re
gister(this)
override fun
onStop() {
super.onStop()
EventBus.getDefault().unregister(this)
Now that the object is a subscriber, tell it what type of event to subscribe to and what it
should do when it receives one:
@Subscribe(threadMode =
ThreadMode.MAIN)fun
onEvent(event:
MySpecificEvent?) {
/* Do something */
Finally, create and post one of those events based on your criteria:
EventBus.getDefault().post(MySpecificEvent())
Since so much of this pattern works its magic at run-time, Future You might have a little
trouble tracing this pattern unless you have good test coverage. Still, a well-designed
flow of commands balances out the readability and should be easy to follow later.
Observer
The Observer pattern defines a one-to-many dependency between objects. When one
object changes state, its dependents get a notification and updates automatically.
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
In short, you define Observable objects that will emit values. These values can emit all at
once, as a continuous stream or at any rate and duration.
Subscriber objects will listen for these values and react to them as they arrive. For
example, you can open a subscription when you make an API call, listen to the server‘s
response and react accordingly.
More recently Android also introduced a native way to implement this pattern through
LiveData. You can learn more about this topic here.
Strategy
You use a Strategy pattern when you have multiple objects of the same nature with
different functionalities. For a better understanding, take a look at the following code:
// 1
interface
TransportTypeStrategy
{fun travelMode():
String
// 2
class Car :
TransportTypeStrategy {
override fun travelMode():
String {
return "Road"
class Ship :
TransportTypeStrategy {
return "Sea"
class Aeroplane :
TransportTypeStrategy {
override fun travelMode():
String {
return "Air"
// 3
this.strategy = strategy
. Travelling Client composes strategy and uses its functionalities inside the functions exposed
to the client side.
interface
PrinterState {
fun print()
// 2
class Ready :
PrinterState {override
fun print() {
print("Printed Successfully.")
// 3
class NoInk :
PrinterState {override
fun print() {
// 4
class Printer() {
init {
state = ready
// 5
fun
startPrint
ing() {
ink--
if (ink >= 0) {
setPrinterState(rea
dy)
} else {
setPrinterState(n
oInk)
state.print()
// 6
fun
installIn
k() {ink
=2
print("Ink installed.")
. Ready is a concrete class implementing PrinterState to define a ready state of the printer.
. NoInk is a concrete class implementing PrinterState to define that the printer has no ink.
So, you create an object of the class Printer to print. The Printer class handles all the states of
the printer internally. It‘s either on a Ready state or in a NoInk state.
Explain in detail about the Workflow for Application development
A workflow application is a software tool that automates the tasks involved in a business process.
The workflow application routes data along a predefined path until an item in the process is
completed. Tasks in the workflow may include approvals, adding information, or data transfers.
Workflow applications can be standalone apps that exist on their own or built on a platform where
endless numbers of applications reside. Workflow applications help business owners to automate
Workflow apps will break a workflow down into a set of data needed to complete the process, and a
path for the data to follow. The workflow application will use a form to collect data at different
The workflow to develop an app for Android is conceptually the same as other app
platforms. However, to efficiently build a well-designed app for Android, you need some
specialized tools. The following list provides an overview of the process to build an Android app
and includes links to some Android Studio tools you should use during each phase of
development.
Public
Public (or open) APIs are Java APIs that come with the JDK. They do not have strict restrictions
about how developers use them.
Private
Private (or internal) APIs are developed by a specific organization and are accessible to only
employees who work for that organization.
Partner
Partner APIs are considered to be third-party APIs and are developed by organizations for
strategic business operations.
Composite
Composite APIs are microservices, and developers build them by combining several service
APIs.
Now that we‘ve covered the types of Java APIs, let‘s discuss the categorization of Java APIs
based on the services that different varieties of APIs in Java provide.
Dynamic Linking
What is dynamic linking?
Dynamic linking means that the code for some external routines is located and loaded when
the program is first run. When you compile a program that uses shared libraries, the shared
libraries are dynamically linked to your program by default.
Dynamically linked programs take up less disk space and less virtual memory if more
than one program uses the routines in the shared libraries.
Static linking copies all the libraries required for the program into the final executable file.
The linker performs this task, and it is the last step of compilation. The linker combines the
relevant libraries with the program code to resolve external references. Finally, the linker
generates an executable file suitable for loading into memory. The final statistically linked file
contains the calling program and called programs. Generally, these files are large because they
are connected with other files.
In dynamic linking, the names of the external libraries /shared libraries are copied into the final
executable; thus, the real linking occurs at run time when the executable file and libraries load to the
memory. The operating system performs dynamic linking. Generally, there is only one copy of a shared
library is in the memory. Therefore, the size of the executable file is lower. It is possible to update and
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1. New
In this state, a new thread begins its life cycle. This is also called a born thread. The thread
is in the new state if you create an instance of Thread class but before the invocation of
the start() method.
2. Runnable
A thread becomes runnable after a newly born thread is started. In this state, a thread would
be executing its task.
3. Running
When the thread scheduler selects the thread then, that thread would be in a running state.
4. Non-Runnable (Blocked)
The thread is still alive in this state, but currently, it is not eligible to run.
5. Terminated
A thread is terminated due to the following reasons:
Either its run() method exists normally, i.e., the thread‘s code has executed the
program.
Or due to some unusual errors like segmentation fault or an unhandled exception.
A thread that is in a terminated state does not consume ant cycle of the CPU.
// Start a transaction
ut.begin();
// Invoke a Service or an EJB
myEJB.businessMethod();
// Update a database entity using an XA JDBC driver
myEJB.updateCustomer(customer);
// Commit the transaction
ut.commit();
}}
Concurrency and Security
Concurrency Utilities for Java EE defers most security decisions to the application server
implementation. If, however, the container supports a security context, that context can be
propagated to the thread of execution. The ContextService can support several runtime
behaviors, and the security attribute, if enabled, will propagate the container security principal.
Resource management in Java
Explain in detail about the concept of Resource management in java
A resource is an object which is required to be closed once our program finishes. For example, a
file is read, database connection and so on.
Resource management or try-with-resources is a new exception handling mechanism that was
introduced in Java 7, which automatically closes the resources used within the try-catch block.
Usage
To use the try-with-resources statement, you simply need to declare the required resources
within the parenthesis, and the created resource will be closed automatically at the end of the
block. Following is the syntax of the try-with-resources statement.
Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}}
Following is the program that reads the data in a file using the try-with-resources statement.
Example
import java.io.FileReader;
import java.io.IOException;
Mobile OS: Android, iOS – Android Application Architecture – Understanding the anatomy
of a mobile application - Android basic components –Intents and Services – Storing and
Retrieving data – Packaging and Deployment – Security and Hacking
Mobile OS:
A mobile operating system is an operating system that helps to run other application
software on mobile devices. It is the same kind of software as the famous computer operating
systems like Linux and Windows, but now they are light and simple to some extent.
The operating systems found on smartphones include Symbian OS, iPhone OS, RIM's
BlackBerry, Windows Mobile, Palm WebOS, Android, and Maemo. Android, WebOS, and
Maemo are all derived from Linux. The iPhone OS originated from BSD and NeXTSTEP,
which are related to Unix.
It combines the beauty of computer and hand use devices. It typically contains a cellular
built-in modem and SIM tray for telephony and internet connections. If you buy a mobile, the
manufacturer company chooses the OS for that specific device.
Popular platforms of the Mobile OS
Android OS: The Android operating system is the most popular operating system today.
It is a mobile OS based on the Linux Kernel and open-source software. The android operating
system was developed by Google. The first Android device was launched in 2008.
Bada (Samsung Electronics): Bada is a Samsung mobile operating system that was
launched in 2010. The Samsung wave was the first mobile to use the bada operating system. The
bada operating system offers many mobile features, such as 3-D graphics, application
installation, and multipoint-touch.
BlackBerry OS: The BlackBerry operating system is a mobile operating system
developed by Research In Motion (RIM). This operating system was designed specifically for
BlackBerry handheld devices. This operating system is beneficial for the corporate users
because it provides synchronization with Microsoft Exchange, Novell GroupWise email, Lotus
Domino, and other business software when used with the BlackBerry Enterprise Server.
iPhone OS / iOS: The iOS was developed by the Apple inc for the use on its device. The
iOS operating system is the most popular operating system today. It is a very secure operating
system. The iOS operating system is not available for any other mobiles.
Symbian OS: Symbian operating system is a mobile operating system that provides a
high-level of integration with communication. The Symbian operating system is based on the
java language. It combines middleware of wireless communications and personal information
management (PIM) functionality. The Symbian operating system was developed by Symbian
Ltd in 1998 for the use of mobile phones. Nokia was the first company to release Symbian OS
on its mobile phone at that time.
Windows Mobile OS: The window mobile OS is a mobile operating system that was
developed by Microsoft. It was designed for the pocket PCs and smart mobiles.
Harmony OS: The harmony operating system is the latest mobile operating system that
was developed by Huawei for the use of its devices. It is designed primarily for IoT devices.
Palm OS: The palm operating system is a mobile operating system that was developed
by Palm Ltd for use on personal digital assistants (PADs). It was introduced in 1996. Palm OS
is also known as the Garnet OS.
WebOS (Palm/HP): The WebOS is a mobile operating system that was developed
by Palm. It based on the Linux Kernel. The HP uses this operating system in its mobile and
touchpads.
Android OS
Android is a software package and linux based operating system for mobile devices such
as tablet computers and smartphones.
It is developed by Google and later the OHA (Open Handset Alliance). Java language is
mainly used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves the
mobile experience for end users.
There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc
Open Handset Alliance (OHA)
It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI,
Garmin, Teleca, Ebay, Intel etc.
It was established on 5th November, 2007, led by Google. It is committed to advance
open standards, provide services and deploy handsets using the Android Platform.
Features of Android
After learning what is android, let's see the features of android. The important features of
android are given below:
It is open-source.
Anyone can customize the Android Platform.
There are a lot of mobile applications that can be chosen by the consumer.
It provides many interesting features like weather details, opening screen, live RSS
(Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage
(SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.
Categories of Android applications
There are many android applications in the market. The top categories are:
o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.
IOS
IOS is a Mobile Operating System that was developed by Apple Inc. for iPhones,
iPads, and other Apple mobile devices. iOS is the second most popular and most used Mobile
Operating System after Android.
The structure of the iOS operating System is Layered based. Its communication doesn’t
occur directly. The layer’s between the Application Layer and the Hardware layer will help for
Communication. The lower level gives basic services on which all applications rely and the
higher-level layers provide graphics and interface-related services. Most of the system
interfaces come with a special package called a framework.
A framework is a directory that holds dynamic shared libraries like .a files, header
files, images, and helper apps that support the library. Each layer has a set of frameworks that
are helpful for developers.
Architecture of IOS
COREOSLayer
All the IOS technologies are built under the lowest level layer i.e. Core OS layer.
These technologies include:
Core Bluetooth Framework
External Accessories Framework
Accelerate Framework
Security Services Framework
Local Authorization Framework etc.
It supports 64 bit which enables the application to run faster.
CORESERVICESLayer
Some important frameworks are present in the CORE SERVICES Layer which helps
the iOS operating system to cure itself ad provide better functionality. It is the 2nd lowest
layer in the Architecture as shown above. Below are some important frameworks present in
this layer:
AddressBook Framework
The Address Book Framework provides access to the contact details of the user.
CloudKit Framework
This framework provides a medium for moving data between your app and iCloud.
CoreData Framework
This is the technology that is used for managing the data model of a Model View
Controller app.
CoreFoundation Framework
This framework provides data management and service features for iOS
applications.
CoreLocation Framework
This framework helps to provide the location and heading information to the
application.
CoreMotion Framework
All the motion-based data on the device is accessed with the help of the Core
Motion Framework.
Foundation Framework
Objective C covering too many of the features found in the Core Foundation
framework.
Health Kit Framework
This framework handles the health-related information of the user.
Home Kit Framework
This framework is used for talking with and controlling connected devices with the
user’s home.
SocialFramework
It is simply an interface that will access users’ social media accounts.
StoreKit Framework
This framework supports for buying of contents and services from inside iOS apps.
MEDIA Layer
With the help of the media layer, we will enable all graphics video, and audio
technology of the system. This is the second layer in the architecture. The different
frameworks of MEDIA layers are:
ULKit Graphics
This framework provides support for designing images and animating the view
content.
CoreGraphics Framework
This framework support 2D vector and image-based rendering ad it is a native
drawing engine for iOS.
Core Animation
This framework helps in optimizing the animation experience of the apps in iOS.
MediaPlayer Framework
This framework provides support for playing the playlist and enables the user to
use their iTunes library.
AVKit
This framework provides various easy-to-use interfaces for video presentation,
recording, and playback of audio and video.
OpenAL
This framework is an Industry Standard Technology for providing Audio.
Core Images
This framework provides advanced support for motionless images.
GL Kit
This framework manages advanced 2D and 3D rendering by hardware-accelerated
interfaces.
COCOA TOUCH
COCOA Touch is also known as the application layer which acts as an interface for the
user to work with the iOS Operating system. It supports touch and motion events and many
more features. The COCOA TOUCH layer provides the following frameworks :
EvenKit Framework
This framework shows a standard system interface using view controllers for
viewing and changing events.
GameKitFramework
This framework provides support for users to share their game-related data online
using a Game Center.
MapKitFramework
This framework gives a scrollable map that one can include in your user interface
of the app.
PushKitFramework
This framework provides registration support.
FeaturesofiOSoperating System
Let us discuss some features of the iOS operating system
Highly Securer than other operating systems.
iOS provides multitasking features like while working in one application we
can switch to another application easily.
iOS’s user interface includes multiple gestures like swipe, tap, pinch, Reverse
pinch.
iBooks, iStore, iTunes, Game Center, and Email are user-friendly.
Linux kernel
It is the heart of android architecture that exists at the root of android
architecture. Linux kernel is responsible for device drivers, power management, memory
management, device management and resource access.
Native Libraries
On the top of linux kernel, their are Native libraries such as WebKit, OpenGL,
FreeType, SQLite, Media, C runtime library (libc) etc.
The WebKit library is responsible for browser support, SQLite is for database,
FreeType for font support, Media for playing and recording audio and video formats.
Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine)
which is responsible to run android application. DVM is like JVM but it is optimized for
mobile devices. It consumes less memory and provides fast performance.
Android Framework
On the top of Native libraries and android runtime, there is android framework.
Android framework includes Android API's such as UI (User Interface), telephony,
resources, locations, Content Providers (data) and package managers. It provides a lot of
classes and interfaces for android application development.
Applications
On the top of android framework, there are applications. All applications such as
home, contact, settings, games, browsers are using android framework that uses android
runtime and libraries. Android runtime and native libraries are using linuxkernal.
Understanding the anatomy of a mobile application
Developing Android applications for mobile devices with limited resources requires a thorough
understanding of the application lifecycle. Android uses its own terminology for these
application building blocks—terms such as context, activity, and intent. This chapter familiarizes
you with the most important terms, and their related Java class components, used by Android
applications.
Mastering Important Android Terminology
This chapter introduces you to the terminology used in Android application development and
provides you with a more thorough understanding of how Android applications function and
interact with one another. Here are some of the important terms covered in this chapter:
Context: The context is the central command center for an Android application. Most
application-specific functionality can be accessed or referenced through the context. The
Context class (android.content.Context) is a fundamental building block of any Android
application and provides access to application-wide features such as the application’s private
files and device resources as well as system-wide services. The application-wide Context object
is instantiated as an Application object (android.app.Application).
Activity: An Android application is a collection of tasks, each of which is called an
activity. Each activity within an application has a unique task or purpose. The Activity
class (android.app.Activity) is a fundamental building block of any Android application,
and most applications are made up of several activities. Typically, the purpose is to
handle the display of a single screen, but thinking only in terms of “an activity is a
screen” is too simplistic. An Activity class extends the Context class, so it also has all of
the functionality of the Context class.
Fragment: An activity has a unique task or purpose, but it can be further
componentized; each component is called a fragment. Each fragment within an
application has a unique task or purpose within its parent activity. The Fragment class
(android.app.Fragment) is often used to organize activity functionality in such a way as
to allow a more flexible user experience across various screen sizes, orientations, and
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 9
MC4204-Mobile Application Development Unit-4
aspect ratios. A fragment is commonly used to hold the code and screen logic for placing
the same user interface component in multiple screens, which are represented by multiple
Activity classes.
Intent: The Android operating system uses an asynchronous messaging mechanism to
match task requests with the appropriate activity. Each request is packaged as an intent.
You can think of each such request as a message stating an intent to do something. Using
the Intent class (android.content.Intent) is the primary method by which application
components such as activities and services communicate with one another.
Image Service: Tasks that do not require user interaction can be encapsulated in a
service. A service is most useful when the operations are lengthy (offloading time-
consuming processing) or need to be done regularly (such as checking a server for new
mail). Whereas activities run in the foreground and generally have a user interface, the
Service class (android.app.Service) is used to handle background operations related to an
Android application. The Service class extends the Context class.
The Application Context:
The application Context is the central location for all top-level application functionality.
The Context class can be used to manage application-specific configuration details as well as
application-wide operations and data. Use the application Context to access settings and
resources shared across multiple Activity instances.
Retrieving the Application Context
You can retrieve the Context for the current process using the getApplicationContext()
method, found in common classes such as Activity and Service, like this:
Context context = getApplicationContext();
Using the Application Context
After you have retrieved a valid application Context object, it can be used to access
application-wide features and services, including the following:
Image Retrieving application resources such as strings, graphics, and XML files
Image Accessing application preferences
Image Managing private application files and directories
Image Retrieving uncompiled application assets
Image Accessing system services
Image Managing a private application database (SQLite)
Image Working with application permissions
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 10
MC4204-Mobile Application Development Unit-4
A startup or splash screen: This activity serves as the primary entry point to the application. It
displays the application name and version information and transitions to the main menu after a
short interval.
A main menu screen: This activity acts as a switch to drive the user to the core activities of the
application. Here, the users must choose what they want to do within the application.
A game play screen: This activity is where the core game play occurs.
A high scores screen: This activity might display game scores or settings.
A Help/About screen: This activity might display the information the user might need to play the
game.
Android applications can be multiprocess, and the Android operating system allows multiple
applications to run concurrently, provided memory and processing power are available.
Applications can have background behavior, and applications can be interrupted and paused
when events such as phone calls occur. Only one active application can be visible to the user at a
time—specifically, a single application Activity is in the foreground at any given time.
Android applications are responsible for managing their state and their memory, resources, and
data. They must pause and resume seamlessly. Understanding the different states within the
Activity lifecycle is the first step in designing and developing robust Android applications.
Here are the method stubs for the most important callbacks of the Activity class:
An android component is simply a piece of code that has a well defined life cycle e.g.
Activity, Receiver, Service etc.
The core building blocks or fundamental components of android are activities, views,
intents, services, content providers, fragments and AndroidManifest.xml.
Activity
An activity is a class that represents a single screen. It is like a Frame in AWT.
View
A view is the UI element such as button, label, text field etc. Anything that you see is a
view.
Intent
Intent is used to invoke components. It is mainly used to:
o Start the service
o Launch an activity
o Display a web page
o Display a list of contacts
o Broadcast a message
o Dial a phone call etc.
For example, you may write the following code to view the webpage.
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.javatpoint.com"));
startActivity(intent);
Service
Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is accessed from within
the application whereas remote service is accessed remotely from other applications running on
the same device.
Content Provider
Content Providers are used to share data between the applications.
Fragment
Fragments are like parts of activity. An activity can display one or more fragments on the
screen at the same time.
AndroidManifest.xml
It contains informations about activities, content providers, permissions etc. It is like the
web.xml file in Java EE.
Android Virtual Device (AVD)
It is used to test the android application without the need for mobile or tablet etc. It can
be created in different configurations to emulate different types of real devices.
Storing and Retrieving data
Android also supports data storage in a local database, and the operating system provides a good
infrastructure for storing and retrieving data. In most cases, the most simple and straightforward
way to acquire and preserve user data is via SQLite databases.
Ways to store data
Shared Preferences
Internal storage
External storage
SQLite databases
Shared Preferences
Shared Preferences is the way to go if you’re saving primitive data as key-value pairs. It requires
a key, which is a String, and the corresponding value for the said key. The value can be any of
the following: a boolean, float, int, long, or another string.
Your Android device stores each app’s Shared Preferences inside of an XML file in a private
directory.
Before you can store data with shared preferences, you must first get a SharedPreferences
object. There are two Context methods that you can use to retrieve a SharedPreferences
object.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
For when your app will have a single preferences file, and
SharedPreferences sharedPreferences = getSharedPreferences(fileNameString, MODE_PRIVATE);
for when your app could have multiple preferences files, or if you prefer to name your
SharedPreferences instance.
On getting the SharedPreferences object, you then access its Editor using the edit() method.
To actually add a value, use the Editor’s putXXX() method, where XXX is one of Boolean,
String, Float, Long, Int, or StringSet. You can also remove a key-value preference pair with
remove().
Finally, make sure to call the Editor’s commit() method after putting or removing values. If
you don’t call commit, your changes will not be persisted.
For our sample app, we allow the user to specify a SharedPreferences filename. If the user
specifies a name, we request for the SharedPreferences with that name; if not, we request the
default SharedPreference object.
String fileNameString = sharedPreferencesBinding.fileNameEditView.getText().toString();
SharedPreferences sharedPreferences;
if(fileNameString.isEmpty()) {
sharedPreferences = getPreferences(MODE_PRIVATE);
}
else {
sharedPreferences = getSharedPreferences(fileNameString, MODE_PRIVATE);
}
Internal storage
Using internal storage is similar to saving with any other file system. You can get references
to File objects, and you can store data of virtually any type using a FileOutputStream. What
sets it apart is the fact that its contents are only accessible by your app.
To get access to your internal file directory, use the Context getFilesDir() method. To create
(or access) a directory within this internal file directory, use the getDir(directoryName,
Environment.getExternalStorageStage().
If MEDIA_MOUNTED is returned, that means you can read and write files to external
storage. You will find a number of predefined directories that should aid with logical storage
and prevent clutter. These include the likes of DIRECTORY_DOCUMENTS and
DIRECTORY_MOVIES.
SQLite
SQLite is a relational database technology that’s used most often when the developer requires an
embedded database in a small system. SQLite is included with the Android system and can be
easily used in your Android app.
For this sample, we create a single table.
public class SampleSQLiteDBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "sample_database";
public static final String PERSON_TABLE_NAME = "person";
public static final String PERSON_COLUMN_ID = "_id";
public static final String PERSON_COLUMN_NAME = "name";
public static final String PERSON_COLUMN_AGE = "age";
public static final String PERSON_COLUMN_GENDER = "gender";
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 18
MC4204-Mobile Application Development Unit-4
String selection =
SampleSQLiteDBHelper.PERSON_COLUMN_NAME + " like ? and " +
SampleSQLiteDBHelper.PERSON_COLUMN_AGE + " > ? and " +
SampleSQLiteDBHelper.PERSON_COLUMN_GENDER + " like ?";
String[] selectionArgs = {"%" + name + "%", age, "%" + gender + "%"};
Cursor cursor = database.query(
SampleSQLiteDBHelper.PERSON_TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // don't sort
);
Log.d("TAG", "The total cursor count is " + cursor.getCount());
activityBinding.recycleView.setAdapter(new MyRecyclerViewCursorAdapter(this,
cursor));
}
SQLite storage offers the power and speed of a full-featured relational database to your app.
If you intend to store data that you may later query, you should consider using the SQLite
storage option.
Saving cache files
Android also provides a means to cache some data rather than store it permanently. You can
cache data in either internal storage or external storage. Cache files may be deleted by the
Android system when the device is low on space.
We are able to save or read data from the device internal memory. FileInputStream and
FileOutputStream classes are used to read and write data into the file.
Here, we are going to read and write data to the internal storage of the device.
Example of reading and writing data to the android internal storage
activity_main.xml
Drag the 2 edittexts, 2 textviews and 2 buttons from the pallete, now the activity_main.xml file
will like this:
File: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 20
MC4204-Mobile Application Development Unit-4
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:layout_marginTop="24dp"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="24dp"
android:ems="10" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="File Name:" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 21
MC4204-Mobile Application Development Unit-4
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Data:" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginLeft="70dp"
android:layout_marginTop="16dp"
android:text="save" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="read" />
</RelativeLayout>
Activity class
Let’s write the code to write and read data from the internal storage.
File: MainActivity.Java
Package example.javatpoint.com.internalstorage:
importandroid.content.Context;
import android.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importanroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
Prepared By. M.Rajeswari.MCA.,M.Phil,. Page 22
MC4204-Mobile Application Development Unit-4
importjava.io.BufferedReader;
importJava.io.FileNotFoundException;
importjava.io.FileOutputstream;
importjava.io.IOException;
importjava.io.InputStreamReader;
Public class MainActivity extends AppCompatActivity{
EditTexteditTextFileName.editTextData;
Button saveButton,readButton;
@Override
protected void onCreat(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity main);
editTextFileName=findViewById(R.id.editText1);
editTextData=findViewById(R.id.editText2);
saveButton=findViewById(R.id.button1);
readButton=findViewById(R.id.button2);
//Performing Action on Read Button
saveButton.setOnClickListener(new View.OnClickListerner(){
@Override
Public void onClick(View arg0) {
String filename=editTextFileName.getTexxt().toString();
String data=editTextData.getText().toString();
FileOutpustreamfos;
try {
fos=openFileOutput(filename.Context.MODE_PRIVATE);
//default mode is PRIVATE. Can be APPEND etc.
fos.write(data.getBytes());
fos.close();
Toast.makeText(getApplicationContext().filename+"saved",
Toast.LENGTH_LONG).show();
});
//Performing Action on Read Button
readButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
String filename=editTextFileName.getText().toString();
StringBufferstringBuffer=new StringBuffer();
try{ //Attaching BufferedReader to the FileInputStream by the help of
InputStreamReader
BufferedReaderinputReader=new BufferedReader(new InputStreamReader(
openFileInput(filename)));
String inputString;
//Reading data line by line and storing in into the stringbuffer
While ((inputString=inputReader.readLine())!=null) {
stringBuffer.append(inputString + "\n");
} } catch (IOException e) {
e.printStactTrace(); }
//Displayingdataonthetoast
Toast.makeText(getApplicationContext(),stringBuffer.toString(),Toast.LENGTH_LONG).show
();
} }); }}
Step 1: To create a new package inside the Src folder in Android studio open your project
in Android mode first as shown in the below image.
Step 2: Now go to the java > right-click > New > Package as shown in the below image.
Step 3: Then a pop-up screen will arise like below and here select the main\java and click
on OK.
Step 4: On the next screen write down your new package name. Here I have given my new
package name GeeksforGeeks. And you are done.
Now go to the app > java > GeeksforGeeks and you can find your new package as shown in
the below image. You can keep separate Java or Kotlin files inside it.
Before you generate a signed application package, you must check the settings of your
application, such as the application version, and update any settings that are incorrect. See
Preparing an Android Application for Deployment.
To generate a signed package containing your application, do the following:
On the Project Manager, expand the Build Configurations node and double-click the Release
configuration, or any other platform-agnostic configuration that you want to use to build your
signed application package.
Expand the Target Platforms node and double-click the Android target platform to select that
platform. The selected target platform is displayed using a bold font.
Expand the Android node, expand the Configuration node within, and double-click the
Application Store platform configuration node to select that platform configuration. The selected
platform configuration is displayed using a bold font.
Select Project > Options > Provisioning, and check that all fields are filled with the right values.
A keystore file and a certificate are required to sign your application.
Select Project > Deployment, and click the Deploy DMgrDeploy.png button to deploy your
application.
RAD Studio builds your application using the Android SDK you previously added to the IDE
and signs your application using the signing certificate specified in the Provisioning page.
You can find your signed application package (.apk) in your project folder:
<Your Project Folder>\Android\<Selected Configuration>\<Project Name>\bin\<Project
Name>.apk
For example: C:\Users\Myname\Documents\RAD
Studio\Projects\ProjectFolder\Android\Release\MyProject\bin\MyProject.apk.
Security and Hacking
Android has built-in security features that significantly reduce the frequency and impact of
application security issues. The system is designed so that you can typically build your apps
with the default system and file permissions and avoid difficult decisions about security.
The following core security features help you build secure apps:
App sandbox
The Android platform takes advantage of the Linux user-based protection to identify and isolate
app resources. To do this, Android assigns a unique user ID (UID) to each Android app and runs
it in its own process. Android uses this UID to set up a kernel-level App Sandbox.
App signing
App signing allows developers to identify the author of the app and to update their app without
creating complicated interfaces and permissions. Every app that runs on the Android platform
must be signed by the developer.
Authentication
Android uses the concept of user-authentication-gated cryptographic keys that requires
cryptographic key storage and service provider and user authenticators.
On devices with a fingerprint sensor, users can enroll one or more fingerprints and use those
fingerprints to unlock the device and perform other tasks. The Gatekeeper subsystem performs
device pattern/password authentication in a Trusted Execution Environment (TEE).
Android 9 and higher includes Protected Confirmation, which gives users a way to formally
confirm critical transactions, such as payments.
Biometrics
Android 9 and higher includes a BiometricPrompt API that app developers can use to integrate
biometric authentication into their apps in a device- and modality-agnostic fashion. Only strong
biometrics can integrate with BiometricPrompt.
Encryption
Once a device is encrypted, all user-created data is automatically encrypted before committing it
to disk and all reads automatically decrypt data before returning it to the calling process.
Encryption ensures that even if an unauthorized party tries to access the data, they won’t be able
to read it.
Keystore
Android offers a hardware-backed Keystore that provides key generation, import and export of
asymmetric keys, import of raw symmetric keys, asymmetric encryption and decryption with
appropriate padding modes, and more.
Security-Enhanced Linux
As part of the Android security model, Android uses Security-Enhanced Linux (SELinux) to
enforce mandatory access control (MAC) over all processes, even processes running with
root/superuser privileges (Linux capabilities).
Trusty Trusted Execution Environment (TEE)
Trusty is a secure Operating System (OS) that provides a Trusted Execution Environment (TEE)
for Android. The Trusty OS runs on the same processor as the Android OS, but Trusty is
isolated from the rest of the system by both hardware and software.
Verified Boot
Verified Boot strives to ensure all executed code comes from a trusted source (usually device
OEMs), rather than from an attacker or corruption. It establishes a full chain of trust, starting
from a hardware-protected root of trust to the bootloader, to the boot partition and other verified
partitions.
Hacking
Mobile hacking apps break or crack the security measures of a software system by penetrating or
interfering with the security layout. They perform network security assessments too.
Android hacking apps are application packages ready to install in a device, APK, and can
modify HTML responses. Some apps have features to identify the weak links in the security of a
system, control WiFi, lock screen widget, and map devices.
These hacking apps have dozens of free network tools with modifications that make them
undetectable by anti-virus scanners.
Following is a handpicked list of the Top best Android hacking apps and great hacking tools,
with their popular features and download links. The list contains open-source (free) and
commercial(paid) software.
Name Reason Chosen Founded
AndroRAT It is versatile and enables access to Android devices remotely, and is 2012
undetectable by anti-virus scanners
cSploit It is the best hacking app for new hackers because it would allow them to 2017
learn new techniques
DroidSheep It is the most efficient mobile hacking app for use if you want to hack social 2012
media accounts and other messaging apps like Facebook and Instagram
on Android devices.
Kali NetHunter It runs security analysis efficiently and also has multi-language support. 2014
Network Mapper It maps out the security of a system and finds the vulnerabilities on its own 1997
NetX Network Tool Its design makes fetching and accessing information from network 2008
analysis easy
Sniffer Wicap It has a friendly UX, is simple to understand, and does not need root 2013
access.
Hackode Scans target security system and expose vulnerability 2013
zAnti It modifies HTML responses and requests, and access password 2012
WiFiKiLL It is able to disable devices connected to a Wi-Fi network. 2016
PART –A
2 MARKS
2. Write the directory path where images are stored while developing Android
applications.
13 AND 15 MARKS
1. Explore the Steps to install and configure Android Studio and SDK
8. Discuss in detail about the anatomy of mobile application with neat diagram.
Communication via the Web – Notification and Alarms – Graphics and Multimedia:
Layer Animation, Event handling and Graphics services – Telephony – Location based
services
Using networks of internet servers and specialized client software, IRC let anyone set up chat
rooms, or "channels," devoted to topics of their choice. It influenced subsequent chat systems
such as AOL and Yahoo chat and even contributed the convention of using the "@" symbol
before a username and the "#" symbol to denote a topic.
3. Instant Messaging Services
In the 1990s, computer-based instant messaging tools such as ICQ, AOL Instant
Messenger, MSN Messenger and Yahoo Messenger became popular ways to stay in touch
with people down the street or around the world for no cost beyond whatever users already
paid to connect to the internet. Some of these tools developed cult followings among
particular types of users, such as Yahoo Messenger's rise among oil traders.
Most of these early tools have since been retired by the companies that operated them, though
a few, such as ICQ, live on with loyal fan bases.
4. Smart Phone Messaging Apps
Most of the 1990s chat tools have since been supplanted by a new breed of messaging
tools, including Facebook Messenger, Google Hangouts, Apple Messages and simple
cellphone-based text messaging. Many of these tools work on smart phones as well as
desktop computers, or even on smart phones alone, and they contain more features than their
earlier counterparts.
Workplace messaging tools, such as Slack and Microsoft Teams, have also become
popular in many companies as a way to share information without picking up the phone or
even drafting an email.
5. Internet Message Boards
Many of today's internet users are familiar with the concept of online discussion
forums, including Facebook groups, subreddits on the forum site Reddit or independent
forums on special interest sites. These let people discuss the news of the day or details of
their hobbies, medical conditions or hometowns. Many have moderators in place to keep the
peace and repel trolls, fraudsters and other undesirable users.
As the old saying goes, don't believe everything you read. This is especially true when
it comes to online message boards, where rumors and misinformation can spread quickly. It's
also a good idea to hold your temper rather than get into fights, or flame wars, on these
forums.
People frequently use social networking tools to stay in touch with remote friends and
family and simply for entertainment. Some people follow updates from celebrities on social
media, and the networks have changed how politicians and entertainers communicate with
the public. Many people use them as a way to follow the news as well, following media
organizations on Facebook or even individual journalists on Twitter. Social networking sites
are generally free and supported by advertising.
Social networking tools have run into some controversy over the spread of rumors,
fake news stories, hate speech and other undesirable content, and some network operators
have taken steps to reduce such behavior.
Since the tools are still relatively young, they're likely to continue to evolve in coming years
and decades to continue to meet user needs.
9. Internet Phone Calling
Many people have switched to internet-based calling systems, using what's
called Voice over Internet Protocol (VoIP), from traditional telephones, especially in office
settings. VoIP systems can be cheaper and faster to set up than traditional phones, and they
often allow international and long-distance calling for a fraction of the cost of landline
telephones.
These systems are available through internet service providers, including many cable
and traditional phone providers, as well as through independent providers that can use your
existing internet connection.
10. Video Calls and Conferences
Video calling has also become popular for staying in touch with friends or family and
for work conference calls that, in the past, would have been audio-only. Adding video makes
it possible to see people's facial expressions, which can lead to easier communication.
Coworkers can also share presentations and files through video systems, making sure
everyone is literally on the same page during a discussion. One downside, of course, is that
people need a professional environment and attire for a call that, if audio-only, could be
placed from anywhere and in any kind of dress.
Popular video chat systems include Microsoft's Skype, Google Hangouts and Apple
FaceTime. Video chat facilities are also built into popular office messaging tools such
as Slack. It's generally possible to video chat with any modern computer or smart phone
equipped with a working camera. Many video chat programs enable people to have audio-
only chats if they prefer.
android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidnotification.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID NOTIFICATION"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Notify" />
</android.support.constraint.ConstraintLayout>
Create an activity named as activity_notification_view.xml and add the following code. This
activity will be launched on clicking the notification. TextView is used to display the
notification message.
activity_notification_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.androi
d.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.androidnotification.NotificationView">
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="your detail of notification..."
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.096"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.206"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
In the MainActivity.java class adds the following code. In this class, clicking the button
calls the addNotification() method where we implement the NotificationCompat.Builder
object to set the notification properties. The NotificationManager.notify() method is used to
display the notification. The Intent class is used to call another activity
(NotificationView.java) on taping the notification.
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b1;
@Override
NotificationView.java
The NotificationView.java class receives the notification message and is displayed in
TextView. This class is invoked while taping the notification.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
Output
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;
public class MainActivity extends AppCompatActivity
{
Button start;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start= findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startAlert();
}
});
}
public void startAlert(){
EditText text = findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Illustrate and explain Graphics and Multimedia. Describe its concept with
neat diagram and give example.
5.3 Graphics and Multimedia
Make your images look and perform their best on Android using various APIs for
bitmaps, drawables, and other types of graphics.
A Drawable is a general abstraction for something that can be drawn. The various
subclasses help with specific image scenarios, and you can extend them to define your own
drawable objects that behave in unique ways.
There are two ways to define and instantiate a Drawable besides using the class constructors:
Inflate an image resource (a bitmap file) saved in your project.
Inflate an XML resource that defines the drawable properties.
Create drawables from resource images
You can add graphics to your app by referencing an image file from your project resources.
Supported file types are PNG (preferred), JPG (acceptable), and GIF (discouraged). App
icons, logos, and other graphics, such as those used in games, are well suited for this
technique.
To use an image resource, add your file to the res/drawable/ directory of your project. Once
in your project, you can reference the image resource from your code or your XML layout.
Either way, it's referred to using a resource ID, which is the file name without the file type
extension. For example, refer to my_image.png as my_image.
The following code snippet demonstrates how to build an ImageView that uses an image
created from a drawable resource and adds it to the layout:
ConstraintLayout constraintLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<item android:drawable="@drawable/image_collapse"/>
</transition>
Then, retrieve and instantiate the object by calling Resources.getDrawable(), and passing the
resource ID of your XML file. Any Drawable subclass that supports the inflate() method can
be defined in XML and instantiated by your app. Each drawable class that supports XML
inflation utilizes specific XML attributes that help define the object properties. The following
code instantiates the TransitionDrawable and sets it as the content of an ImageView object:
Resources res = context.getResources();
TransitionDrawable transition =
(TransitionDrawable) ResourcesCompat.getDrawable(res, R.drawable.expand_collapse,
null);
ImageView image = (ImageView) findViewById(R.id.toggle_image);
image.setImageDrawable(transition);
// Description of the initial state that the drawable represents.
image.setContentDescription(getResources().getString(R.string.collapsed));
Because ShapeDrawable has its own draw() method, you can create a subclass of View that
draws the ShapeDrawable object during the onDraw() event, as shown in the following code
example:
public class CustomDrawableView extends View {
private ShapeDrawable drawable;
android:textSize="30sp"
android:background="@drawable/my_button_background"/>
Custom drawables
When you want to create some custom drawings, you can do so by extending
the Drawable class (or any of its subclasses).
The most important method to implement is draw(Canvas) because this provides
the Canvas object you must use to provide your drawing instructions.
The following code shows a simple subclass of Drawable that draws a circle:
public class MyDrawable extends Drawable {
private final Paint redPaint;
public MyDrawable() {
// Set up color and text size
redPaint = new Paint();
redPaint.setARGB(255, 255, 0, 0);
}
@Override
public void draw(Canvas canvas) {
// Get the drawable's bounds
int width = getBounds().width();
int height = getBounds().height();
float radius = Math.min(width, height) / 2;
// Draw a red circle in the center
canvas.drawCircle(width/2, height/2, radius, redPaint);
}
@Override
public void setAlpha(int alpha) {
// This method is required
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
// This method is required
}
@Override
Example XML
Here is a sample VectorDrawable XML file that renders an image of a battery in the charging
mode.
<!-- res/drawable/battery_charging.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
<!-- intrinsic size of the drawable -->
android:height="24dp"
android:width="24dp"
<!-- size of the virtual canvas -->
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<group
android:name="rotationGroup"
android:pivotX="10.0"
android:pivotY="10.0"
android:rotation="15.0" >
<path
android:name="vect"
android:fillColor="#FF000000"
android:pathData="M15.67,4H14V2h-4v2H8.33C7.6,4 7,4.6
7,5.33V9h4.93L13,7v2h4V5.33C17,4.6 16.4,4 15.67,4z"
android:fillAlpha=".3"/>
<path
android:name="draw"
android:fillColor="#FF000000"
android:pathData="M13,12.5h2L11,20v-5.5H9L11.93,9H7v11.67C7,21.4 7.6,22
8.33,22h7.33c0.74,0 1.34,-0.6 1.34,-1.33V9h-4v3.5z"/>
</group>
</vector>
android:name="root"
android:strokeWidth="2"
android:strokeLineCap="square"
android:strokeColor="?android:colorControlNormal"
android:pathData="M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7" />
</vector>
</aapt:attr>
<target android:name="root">
<aapt:attr name="android:animation">
<objectAnimator
android:propertyName="pathData"
android:valueFrom="M4.8,13.4 L9,17.6 M10.4,16.2 L19.6,7"
android:valueTo="M6.4,6.4 L17.6,17.6 M6.4,17.6 L17.6,6.4"
android:duration="300"
android:interpolator="@android:interpolator/fast_out_slow_in"
android:valueType="pathType" />
</aapt:attr>
</target>
</animated-vector>
How to handle the bitmaps. Explain it.
Handling bitmaps
Bitmaps can very easily exhaust an app's memory budget. For example, the camera on
the Pixel phone takes photos of up to 4048x3036 pixels (12 megapixels). If the bitmap
configuration used is ARGB_8888, the default for Android 2.3 (API level 9) and higher,
loading a single photo into memory takes about 48MB of memory (4048*3036*4 bytes).
Such a large memory demand can immediately use up all the memory available to the app.
Loading bitmaps on the UI thread can degrade your app's performance, causing slow
responsiveness or even ANR messages. It is therefore important to manage threading
appropriately when working with bitmaps.
If your app is loading multiple bitmaps into memory, you need to skillfully manage memory
and disk caching. Otherwise, the responsiveness and fluidity of your app's UI may suffer.
OpenGL ES
Android includes support for high performance 2D and 3D graphics with the Open Graphics
Library (OpenGL®), specifically, the OpenGL ES API. OpenGL is a cross-platform graphics
API that specifies a standard software interface for 3D graphics processing hardware.
OpenGL ES is a flavor of the OpenGL specification intended for embedded devices. Android
supports several versions of the OpenGL ES API:
OpenGL ES 1.0 and 1.1 - This API specification is supported by Android 1.0 and higher.
OpenGL ES 2.0 - This API specification is supported by Android 2.2 (API level 8) and
higher.
OpenGL ES 3.0 - This API specification is supported by Android 4.3 (API level 18) and
higher.
OpenGL ES 3.1 - This API specification is supported by Android 5.0 (API level 21) and
higher.
Displaying graphics with OpenGL ES
The Android framework provides plenty of standard tools for creating attractive, functional
graphical user interfaces. However, if you want more control of what your application draws
on screen, or are venturing into three dimensional graphics, you need to use a different tool.
The OpenGL ES APIs provided by the Android framework offers a set of tools for displaying
high-end, animated graphics that are limited only by your imagination and can also benefit
from the acceleration of graphics processing units (GPUs) provided on many Android
devices.
This class walks you through the basics of developing applications that use OpenGL,
including setup, drawing objects, moving drawn elements and responding to touch input.
The example code in this class uses the OpenGL ES 2.0 APIs, which is the recommended
API version to use with current Android devices. For more information about versions of
OpenGL ES, see the OpenGL developer guide.
Define shapes
OpenGL ES coordinate system relative to an Android device screen, the basics of defining a
shape, shape faces, as well as defining a triangle and a square.
Define a triangle
OpenGL ES allows you to define drawn objects using coordinates in three-dimensional
space. So, before you can draw a triangle, you must define its coordinates. In OpenGL, the
typical way to do this is to define a vertex array of floating point numbers for the coordinates.
For maximum efficiency, you write these coordinates into a ByteBuffer, that is passed into
the OpenGL ES graphics pipeline for processing.
public class Triangle {
private FloatBuffer vertexBuffer;
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
static float triangleCoords[] = { // in counterclockwise order:
0.0f, 0.622008459f, 0.0f, // top
-0.5f, -0.311004243f, 0.0f, // bottom left
0.5f, -0.311004243f, 0.0f // bottom right
};
// Set color with red, green, blue and alpha (opacity) values
float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };
public Triangle() {
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
triangleCoords.length * 4);
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder());
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer();
// add the coordinates to the FloatBuffer
vertexBuffer.put(triangleCoords);
// set the buffer to read the first coordinate
vertexBuffer.position(0);
}}
Define a square
Defining triangles is pretty easy in OpenGL, but what if you want to get a just a little more
complex? Say, a square? There are a number of ways to do this, but a typical path to drawing
such a shape in OpenGL ES is to use two triangles drawn together:
vertexBuffer.position(0);
// initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(
// (# of coordinate values * 2 bytes per short)
drawOrder.length * 2);
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
}}
This example gives you a peek at what it takes to create more complex shapes with OpenGL.
In general, you use collections of triangles to draw objects. In the next lesson, you learn how
to draw these shapes on screen.
Draw shapes
Initialize shapes
Before you do any drawing, you must initialize and load the shapes you plan to draw. Unless
the structure (the original coordinates) of the shapes you use in your program change during
the course of execution, you should initialize them in the onSurfaceCreated() method of your
renderer for memory and processing efficiency.
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
private Triangle mTriangle;
private Square mSquare;
Draw a shape
Drawing a defined shape using OpenGL ES 2.0 requires a significant amount of code,
because you must provide a lot of details to the graphics rendering pipeline. Specifically, you
must define the following:
Vertex Shader - OpenGL ES graphics code for rendering the vertices of a shape.
Fragment Shader - OpenGL ES code for rendering the face of a shape with colors or textures.
Program - An OpenGL ES object that contains the shaders you want to use for drawing one
or more shapes.
You need at least one vertex shader to draw a shape and one fragment shader to color that
shape. These shaders must be compiled and then added to an OpenGL ES program, which is
then used to draw the shape. Here is an example of how to define basic shaders you can use
to draw a shape in the Triangle class:
public class Triangle {
private final String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";
...
}
Shaders contain OpenGL Shading Language (GLSL) code that must be compiled prior to
using it in the OpenGL ES environment. To compile this code, create a utility method in your
renderer class:
When you run the application, it should look something like this:
when you establish your GLSurfaceView, or might change dynamically based on user actions
or your application’s function.
Add motion
OpenGL ES by learning how to add motion to a shape with rotation.
Rotate a shape
Rotating a drawing object with OpenGL ES 2.0 is relatively simple. In your renderer, create
another transformation matrix (a rotation matrix) and then combine it with your projection
and camera view transformation matrices:
private float[] rotationMatrix = new float[16];
@Override
public void onDrawFrame(GL10 gl) {
float[] scratch = new float[16];
...
// Create a rotation transformation for the triangle
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
Matrix.setRotateM(rotationMatrix, 0, angle, 0, 0, -1.0f);
// Combine the rotation matrix with the projection and camera view
// Note that the vPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
Matrix.multiplyMM(scratch, 0, vPMatrix, 0, rotationMatrix, 0);
// Draw triangle
mTriangle.draw(scratch);
}
Enable continuous rendering
If you have diligently followed along with the example code in this class to this point, make
sure you comment out the line that sets the render mode only draw when dirty, otherwise
OpenGL rotates the shape only one increment and then waits for a call
to requestRender() from the GLSurfaceView container:
public class MyGLSurfaceView(Context context) extends GLSurfaceView {
...
// Render the view only when there is a change in the drawing data.
// To allow the triangle to rotate automatically, this line is commented out:
//setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
Unless you have objects changing without any user interaction, it’s usually a good idea have
this flag turned on. Be ready to uncomment this code, because the next lesson makes this call
applicable once again.
Respond to touch events
Setup a touch listener
In order to make your OpenGL ES application respond to touch events, you must implement
the onTouchEvent() method in your GLSurfaceView class. The example implementation
below shows how to listen for MotionEvent.ACTION_MOVE events and translate them to
an angle of rotation for a shape.
private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float previousX;
private float previousY;
@Override
public boolean onTouchEvent(MotionEvent e) {
// MotionEvent reports input details from the touch screen
// and other input controls. In this case, you are only
// interested in events where the touch position changed.
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dx = x - previousX;
float dy = y - previousY;
// reverse direction of rotation above the mid-line
if (y > getHeight() / 2) {
dx = dx * -1 ;
}
// reverse direction of rotation to left of the mid-line
if (x < getWidth() / 2) {
dy = dy * -1 ;
}
renderer.setAngle(
renderer.getAngle() +
((dx + dy) * TOUCH_SCALE_FACTOR));
requestRender();
}
previousX = x;
previousY = y;
return true;
}
Expose the rotation angle
The example code above requires that you expose the rotation angle through your renderer by
adding a public member. Since the renderer code is running on a separate thread from the
main user interface thread of your application, you must declare this public variable
as volatile. Here is the code to declare the variable and expose the getter and setter pair:
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}}
Apply rotation
To apply the rotation generated by touch input, comment out the code that generates an angle
and add a variable that contains the touch input generated angle:
public void onDrawFrame(GL10 gl) {
...
float[] scratch = new float[16];
Figure 1. Triangle being rotated with touch input (circle shows touch location).
Vulkan can directly output wide color gamut content (using Display P3 and scRGB). This
capability is useful for creating apps that involve high fidelity color reproduction, such as
image and video editing apps.
Render wide color gamut content
Vulkan
The Vulkan support for wide color gamut is provided through
the VK_EXT_swapchain_colorspace extension.
Before enabling wide color support in your Vulkan code, first check that the extension is
supported via vkEnumerateInstanceExtensionProperties. If the extension is available, you
must enable it during vkCreateInstance before creating any swapchain images that use the
additional color spaces defined by the extension.
Before creating the swapchain, you need choose your desired color space, then loop through
the available physical device surfaces and choose a valid color format for that color space.
On Android devices, Vulkan supports wide color gamut with the following color spaces
and VkSurfaceFormatKHR color formats:
Vulkan wide color gamut color spaces:
VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT
VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT
Vulkan color formats with wide color gamut support:
VK_FORMAT_R16G16B16A16_SFLOAT
VK_FORMAT_A2R10G10B10_UNORM_PACK32
VK_FORMAT_R8G8B8A8_UNORM
The following code snippet shows how you can check that the device supports the Display P3
color space:
uint32_t formatCount = 0;
vkGetPhysicalDeviceSurfaceFormatsKHR(
vkPhysicalDev,
vkSurface,
&formatCount,
nullptr);
VkSurfaceFormatKHR *formats = new VkSurfaceFormatKHR[formatCount];
vkGetPhysicalDeviceSurfaceFormatsKHR(
vkPhysicalDev,
vkSurface,
&formatCount,
formats);
if (displayP3Index == formatCount) {
// Display P3 is not supported on the platform
// choose other format
}
return false;
}
This event occurs when the user clicks on an item on the screen in
onClick() touch more or focuses on an item using a trackball or navigation-
keys.
This event occurs when a user clicks on an item or screen for more
onLongClick()
than 1 second.
This event occurs when a user navigates away from an item that
onFocusChange()
was on focus.
onKey() This event occurs when a user focuses and clicks on an item.
2. Event Handlers
Event handles are the actual methods that have the action that is to be taken. After an event
has happened and event listeners are registered, event listeners call Event Handler. These are
useful to define some callback methods.
Following are some of the important Event Handlers:
onKeyUp() The system invokes this method when a new key event occurs.
onKeyDown() The system invokes this method when a key down event occurs.
onTrackballEvent() The system invokes this method when a trackball motion event occurs.
onTouchEvent() The system invokes this method when some touch event occurs.
The system invokes this method when an item gets into focus or loses
onFocusChange()
focus.
@Override
protected void onCreate(Bundle savedInstanceState) {
Touch mode
While a user interacts with the device they roll the screen over. Therefore it’s necessary to
focus on the items that are actionable. In the devices with touch functionality, and the
user begins interacting with it then it is not important to give focus on touchable items.
This mode of interaction is “Touch Mode”. Once a user touches the screen, the device
enters in touch mode and then onwards the actionable icons and buttons are kept on focus
like – navigation button or home button.
Handling Focus
The framework handles the focus movement according to user input. Handling the focus
includes adding and removing the focus according to the user input movements. Focus
changes with the help of Views. You can check if the View is set to be in focusable mode
or not using isFocusable(). And we can also change the focus mode by
using setFocusable().
We can set the focus of view in touch mode as well, using setFocusInTouchMode(). To
check if a view allows focus in touch mode use isFocusableInTouchMode().
activity_main.xml
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DataFlair "/>
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Event" />
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="See me! />
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btnClick);
tView = (TextView)findViewById(R.id.txtResult);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView = (TextView) findViewById(R.id.textView);
txtView.setText("You've Clicked \n The Event has taken place");
txtView.setTextSize(25);
txtView.setGravity(Gravity.CENTER);
txtView.setTextColor(R.color.colorAccent);
}
});
}
}
Other apps that are not selected as the default SMS app can only read the SMS Provider, but
may also be notified when a new SMS arrives by listening for
the Telephony.Sms.Intents.SMS_RECEIVED_ACTION broadcast, which is a non-abortable
broadcast that may be delivered to multiple apps. This broadcast is intended for apps that—
while not selected as the default SMS app—need to read special incoming messages such as
to perform phone number verification.
Write a brief note on Location Based Services
Location Based Services
Android location APIs make it easy for you to build location-aware applications,
without needing to focus on the details of the underlying location technology.
This becomes possible with the help of Google Play services, which facilitates
adding location awareness to your app with automated location tracking, geofencing, and
activity recognition.
1
float distanceTo(Location dest)
Returns the approximate distance in meters between this location and the given location.
2
float getAccuracy()
3
double getAltitude()
4
float getBearing()
5
double getLatitude()
6
double getLongitude()
7
float getSpeed()
8
boolean hasAccuracy()
9
boolean hasAltitude()
10
boolean hasBearing()
11
boolean hasSpeed()
12
void reset()
13
void setAccuracy(float accuracy)
14
void setAltitude(double altitude)
15
void setBearing(float bearing)
16
void setLatitude(double latitude)
17
void setLongitude(double longitude)
18
void setSpeed(float speed)
19
String toString()
To get the current location, create a location client which is LocationClient object, connect
it to Location Services using connect() method, and then call its getLastLocation() method.
This method returns the most recent location in the form of Location object that contains
latitude and longitude coordinates and other information as explained above. To have
location based functionality in your activity, you will have to implement two interfaces −
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
These interfaces provide following important callback methods, which you need to
implement in your activity class −
1
abstract void onConnected(Bundle connectionHint)
This callback method is called when location service is connected to the location client
successfully. You will use connect() method to connect to the location client.
2
abstract void onDisconnected()
This callback method is called when the client is disconnected. You will
use disconnect() method to disconnect from the location client.
3
abstract void onConnectionFailed(ConnectionResult result)
This callback method is called when there was an error connecting the client to the
service.
You should create the location client in onCreate() method of your activity class, then
connect it in onStart(), so that Location Services maintains the current location while your
activity is fully visible. You should disconnect the client in onStop() method, so that when
your app is not visible, Location Services is not maintaining the current location. This helps
in saving battery power up-to a large extent.
If you are willing to have location updates, then apart from above mentioned interfaces, you
will need to implement LocationListener interface as well. This interface provide following
callback method, which you need to implement in your activity class −
1
abstract void onLocationChanged(Location location)
This callback method is used for receiving notifications from the LocationClient when the
location has changed.
The LocationRequest object is used to request a quality of service (QoS) for location
updates from the LocationClient. There are following useful setter methods which you can
use to handle QoS. There are equivalent getter methods available which you can check in
Android official documentation.
1
setExpirationDuration(long millis)
2
setExpirationTime(long millis)
3
setFastestInterval(long millis)
4
setInterval(long millis)
5
setNumUpdates(int numUpdates)
6
setPriority(int priority)
Now for example, if your application wants high accuracy location it should create a
location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY
and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities
like PRIORITY_LOW_POWER for to request "city" level accuracy or
PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy.
Activities should strongly consider removing all location request when entering the
background (for example at onPause()), or at least swap the request to a larger interval and
lower quality to save power consumption.
Once you have Location object, you can use Geocoder.getFromLocation() method to get
an address for a given latitude and longitude. This method is synchronous, and may take a
long time to do its work, so you should call the method from the doInBackground() method
of an AsyncTask class.
Example
Following example shows you in practical how to to use Location Services in your app to
get the current location and its equivalent addresses etc.
To experiment with this example, you will need actual Mobile device equipped with latest
Android OS, otherwise you will have to struggle with emulator which may not work.
Step Description
1 You will use Android studio IDE to create an Android application and name it
as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.
3 Modify src/MainActivity.java file and add required code as shown below to take care of
getting current location and its equivalent address.
4 Modify layout XML file res/layout/activity_main.xml to add all GUI components which
include three buttons and two text views to show location/address.
7 Run the application to launch Android emulator and verify the result of the changes done in
the application.
package com.example.tutorialspoint7.myapplication;
import android.Manifest;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.test.mock.MockPackageManager;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
Button btnShowLocation;
private static final int REQUEST_CODE_PERMISSION = 2;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
// GPSTracker class
GPSTracker gps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (ActivityCompat.checkSelfPermission(this, mPermission)
!= MockPackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{mPermission},
REQUEST_CODE_PERMISSION);
// If any permission above not allowed by user, this condition will
execute every time, else your else part will work
}
} catch (Exception e) {
e.printStackTrace();
}
btnShowLocation = (Button) findViewById(R.id.button);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
package com.example.tutorialspoint7.myapplication;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} } }
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} } } } }
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
} });
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Let's try to run your Tutorialspoint application. I assume that, you have connected your
actual Android Mobile device with your computer. To run the app from Android Studio,
open one of your project's activity files and click Run icon from the toolbar. Before
starting your application, Android studio installer will display following window to select an
option where you want to run your Android application.