CSE307 Unit5
CSE307 Unit5
Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by
Google, and other companies. Android offers a unified approach to application development for
mobile devices which means developers need only develop for Android, and their applications
should be able to run on different devices powered by Android.
Features of Android
Android is a powerful operating system competing with Apple 4GS and supports great features.
Few of them are listed below −
● Beautiful UI: Android OS basic screen provides a beautiful and intuitive user interface.
● Connectivity: GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE,
NFC and WiMAX.
● Storage: SQLite, a lightweight relational database, is used for data storage purposes.
● Media support: H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC
5.1, MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.
● Messaging: Supports SMS and MMS
● Web browser: Based on the open-source WebKit layout engine, coupled with Chrome's
V8 JavaScript engine supporting HTML5 and CSS3.
● Multi-touch: Android has native support for multi-touch which was initially made
available in handsets such as the HTC Hero.
● Multi-tasking: Users can jump from one task to another and at the same time various
applications can run simultaneously.
● Resizable widgets: Widgets are resizable, so users can expand them to show more
content or shrink them to save space.
● Multi-Language: Supports single direction and bi-directional text.
● GCM: Google Cloud Messaging (GCM) is a service that lets developers send short
message data to their users on Android devices, without needing a proprietary sync
solution.
● Wi-Fi Direct: A technology that lets apps discover and pair directly, over a
high-bandwidth peer-to-peer connection.
● Android Beam: A popular NFC-based technology that lets users instantly share, just by
touching two NFC-enabled phones together.
You can start your application development by calling start a new android studio project. In a
new installation frame should ask Application name, package information and location of the
project.−
After entered application name, it going to be called select the form factors your application runs
on, here need to specify Minimum SDK such as API23: Android 6.0 (Mashmallow) −
The next level of installation should contain selecting the activity to mobile, it specifies the
default layout for Applications.
At the final stage it is going to be an open development tool to write the application code.
1. Java: This contains the .java source files for your project. By default, it includes an
MainActivity.java source file having an activity class that runs when your app is launched
using the app icon.
2. res/drawable-hdpi: This is a directory for drawable objects that are designed for
high-density screens.
3. res/layout: This is a directory for files that define your app's user interface.
4. res/values: This is a directory for other various XML files that contain a collection of
resources, such as strings and colours definitions.
5. AndroidManifest.xml: This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.
6. Build.gradle: This is an auto generated file which contains compileSdkVersion,
buildToolsVersion, applicationId, minSdkVersion, targetSdkVersion, versionCode and
versionName
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder.
The onCreate() method is one of many methods that are figured out when an activity is loaded.
2. The Layout File
The activity_main.xml is a layout file available in res/layout directory, that is referenced by
your application when building its interface. You will modify this file very frequently to change
the layout of your application. For your "Hello World!" application, this file will have following
content related to default layout −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
This is an example of a simple RelativeLayout which we will study in a separate chapter. The
TextView is an Android control used to build the GUI and it has various attributes like
android:layout_width, android:layout_height etc which are being used to set its width and height
etc.. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the strings.xml file, which is "Hello
World!".
3. The Manifest File
Whatever component you develop as a part of your application, you must declare all its
components in a manifest.xml which resides at the root of the application project directory. This
file works as an interface between Android OS and your application, so if you do not declare
your component in this file, then it will not be considered by the OS. For example, a default
manifest file will look like as following file −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here <application>...</application> tags enclosed the components related to the application.
Attribute android:icon will point to the application icon available under res/drawable-hdpi. The
application uses the image named ic_launcher.png located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies the fully
qualified class name of the Activity subclass and the android:label attributes specifies a string to
use as the label for the activity. You can specify multiple activities using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this activity
serves as the entry point for the application. The category for the intent-filter is named
android.intent.category.LAUNCHER to indicate that the application can be launched from the
device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to
the app_name string defined in the strings.xml file, which is "HelloWorld". Similar way, other
strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different Android
application components −
● <activity>elements for activities
● <service> elements for services
● <receiver> elements for broadcast receivers
● <provider> elements for content providers
4. The Strings File
The strings.xml file is located in the res/values folder and it contains all the text that your
application uses. For example, the names of buttons, labels, default text, and similar types of
strings go into this file. This file is responsible for their textual content. For example, a default
strings file will look like as following file −
<resources>
<string name="app_name">HelloWorld</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
Design User Interface with View Control Flow
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.
1. Create UI View
The basic building block for user interface is a View object which is created from the View class
and occupies a rectangular area on the screen and is responsible for drawing and event handling.
View is the base class for widgets, which are used to create interactive UI components like
buttons, text fields, etc. 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.
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>
2. 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. 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>
3. Create UI control object:
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);
}
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);
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
…
</LinearLayout>
2. Relative Layout: RelativeLayout is a view group that displays child views in relative
positions. It enables you to specify how child views are positioned relative to each other.
The position of each view can be specified as relative to sibling elements or relative to
the parent.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
…
</RelativeLayout>
3. Table Layout: TableLayout is a view that groups views into rows and columns. It will
arrange groups of views into rows and columns. You will use the <TableRow> element to
build a row in the table. Each row has zero or more cells; each cell can hold one View
object.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
…
</TableRow>
</TableLayout>
4. Absolute Layout: AbsoluteLayout enables you to specify the exact location of its
children. An Absolute Layout lets you specify exact locations (x/y coordinates) of its
children. Absolute layouts are less flexible and harder to maintain than other types of
layouts without absolute positioning.
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
…
</AbsoluteLayout>
5. Frame Layout: The FrameLayout is a placeholder on screen that you can use to display
a single view. Frame Layout is designed to block out an area on the screen to display a
single item. Generally, FrameLayout should be used to hold a single child view, because
it can be difficult to organize child views in a way that's scalable to different screen sizes
without the children overlapping each other.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
…
</FrameLayout>
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 there are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
● android:id: This is the ID which uniquely identifies the view.
● android:layout_width: This is the width of the layout.
● android:layout_height: This is the height of the layout
● android:layout_marginTop: This is the extra space on the top side of the layout.
● android:layout_marginBottom: This is the extra space on the bottom side of the layout.
● android:layout_marginLeft: This is the extra space on the left side of the layout.
● android:layout_marginRight: This is the extra space on the right side of the layout.
● android:layout_gravity: This specifies how child Views are positioned.
● android:layout_weight: This specifies how much of the extra space in the layout should
be allocated to the View.
● android:layout_x: This specifies the x-coordinate of the layout.
● android:layout_y: This specifies the y-coordinate of the layout.
● android:layout_width: This is the width of the layout.
● android:paddingLeft: This is the left padding filled for the layout.
● android:paddingRight: This is the right padding filled for the layout.
● android:paddingTop: This is the top padding filled for the layout.
● android:paddingBottom: This is the bottom padding filled for the layout.
2. Android UI Controls/Elements
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. There are a number of UI controls provided
by Android that allow you to build the graphical user interface for your app.
● Text View: A TextView displays text to the user and optionally allows them to edit it. A
TextView is a complete text editor, however the basic class is configured to not allow
editing.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txtView = (TextView) findViewById(R.id.text_id);
}
● Edit Text: A EditText is an overlay over TextView that configures itself to be editable. It
is the predefined subclass of TextView that includes rich editing capabilities.
public class MainActivity extends Activity {
EditText eText;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eText = (EditText) findViewById(R.id.edittext);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG);
msg.show();
}
});
}
}
● Button: A Button is a Push-button which can be pressed, or clicked, by the user to
perform an action.
public class MainActivity extends Activity {
EditText eText;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eText = (EditText) findViewById(R.id.edittext);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG);
msg.show();
}
});
}
}
● Image Button: 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.
public class MainActivity extends Activity {
ImageButton imgButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton =(ImageButton)findViewById(R.id.imageButton);
imgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"You download is
resumed",Toast.LENGTH_LONG).show();
}
});
}
}
● Toggle Button: A ToggleButton displays checked/unchecked states as a button. It is
basically an on/off button with a light indicator.
public class MainActivity extends ActionBarActivity {
ToggleButton tg1,tg2;
Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tg1=(ToggleButton)findViewById(R.id.toggleButton);
tg2=(ToggleButton)findViewById(R.id.toggleButton2);
b1=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("You have clicked first ON Button-:) ").append(tg1.getText());
result.append("You have clicked Second ON Button -:) ").append(tg2.getText());
Toast.makeText(MainActivity.this,
result.toString(),Toast.LENGTH_SHORT).show();
}
});
}
}
● Radio Button and Radio Group: A RadioButton has two states: either checked or
unchecked.This allows the user to select one option from a set. A RadioGroup class is
used for a set of radio buttons.
public class MainActivity extends ActionBarActivity {
RadioGroup rg1;
RadioButton rb1;
Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerRadioButton();
}
private void addListenerRadioButton() {
rg1 = (RadioGroup) findViewById(R.id.radioGroup);
b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selected=rg1.getCheckedRadioButtonId();
rb1=(RadioButton)findViewById(selected);
Toast.makeText(MainActivity.this,rb1.getText(),Toast.LENGTH_LONG).show();
}
});
}
}
● Checkbox: A CheckBox is an on/off switch that can be toggled by the user. You should
use check-boxes when presenting users with a group of selectable options that are not
mutually exclusive.
public class MainActivity extends Activity {
CheckBox ch1,ch2;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch1=(CheckBox)findViewById(R.id.checkBox1);
ch2=(CheckBox)findViewById(R.id.checkBox2);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Thanks : ").append(ch1.isChecked());
result.append("\nThanks: ").append(ch2.isChecked());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
● Progress Bar: Progress bars are used to show progress of a task. For example, when you
are uploading or downloading something from the internet, it is better to show the
progress of download/upload to the user.
ProgressDialog progress = new ProgressDialog(this);
progress.setMessage("Downloading Music :) ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
● Time and Date Picker: Android Time Picker allows you to select the time of day in
either 24 hour or AM/PM mode. The time consists of hours, minutes and clock format.
Android provides this functionality through the TimePicker class. Android Date Picker
allows you to select the date consisting of day, month and year in your custom user
interface. For this functionality Android provides DatePicker and DatePickerDialog
components.
public class MainActivity extends Activity {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
@SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca",
Toast.LENGTH_SHORT)
.show();
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
Above syntax is calling startActivity method to start an email activity and result should be as
shown below −
For example, assume that you have an Activity that needs to open a URL in a web browser on
your Android device. For this purpose, your Activity will send ACTION_WEB_SEARCH Intent
to the Android Intent Resolver to open a given URL in the web browser. The Intent Resolver
parses through a list of Activities and chooses the one that would best match your Intent, in this
case, the Web Browser Activity. The Intent Resolver then passes your web page to the web
browser and starts the Web Browser Activity.
String q = "SRM University";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
Above example will search as SRM University on android search engine and it gives the result
of tutorialspoint in your an activity
There are separate mechanisms for delivering intents to each type of component − activities,
services, and broadcast receivers.
● Context.startActivity(): The Intent object is passed to this method to launch a new
activity or get an existing activity to do something new.
● Context.startService(): The Intent object is passed to this method to initiate a service or
deliver new instructions to an ongoing service.
● Context.sendBroadcast(): The Intent object is passed to this method to deliver the
message to all interested broadcast receivers.
Activity Lifecycle
Events are a useful way to collect data about a user's interaction with interactive
components of Applications. Like button presses or screen touch etc. The Android
framework maintains an event queue as a first-in, first-out (FIFO) basis. You can capture
these events in your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −
● Event Listeners − An event listener is an interface in the View class that contains a
single callback method. These methods will be called by the Android framework when
the View to which the listener has been registered is triggered by user interaction with the
item in the UI.
● Event Listeners Registration − Event Registration is the process by which an Event
Handler gets registered with an Event Listener so that the handler is called when the
Event Listener fires the event. Event Registration is the process by which an Event
Handler gets registered with an Event Listener so that the handler is called when the
Event Listener fires the event. Though there are several tricky ways to register your event
listener for any event. There are three 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.
● Event Handlers − When an event happens and we have registered an event listener for
the event, the event listener calls the Event Handlers, which is the method that actually
handles the event.
OnClickListener()
This is called when the user either clicks or touches or focuses
onClick()
upon any widget like button, text, image etc. You will use
onClick() event handler to handle such an event.
OnLongClickListener()
This is called when the user either clicks or touches or focuses
onLongClick() upon any widget like button, text, image etc. for one or more
seconds. You will use the onLongClick() event handler to
handle such an event.
OnFocusChangeListener()
This is called when the widget loses its focus ie. user goes
onFocusChange()
away from the view item. You will use the onFocusChange()
event handler to handle such an event.
OnFocusChangeListener()
This is called when the user is focused on the item and presses
onKey()
or releases a hardware key on the device. You will use
onKey() event handler to handle such an event.
OnTouchListener()
This is called when the user presses the key, releases the key,
onTouch()
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 an event.
onCreateContextMenuItemListener()
onCreateContextMenu() This is called when the context menu is being built(as the
result of a sustained "long click)