Unit Ii
Unit Ii
Page 1
Mobile Application Development Unit-II
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.
Page 2
Mobile Application Development Unit-II
Q 10.0 29
Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc. Let's understand the project structure of android application.
Page 3
Mobile Application Development Unit-II
UNDERSTANDING ACTIVITIES
An activity is the single screen in android. It is like window or frame of Java.
Every unique screen the user interacts with in an application is displayed through an Activity—one
Activity for each screen. Users can interact with an application by performing different actions with
the visual controls found in the Activity. A simple application may consist of just one Activity,
whereas large applications contain several Activities. Each Activity of an application operates
independently of the others. A stack of Activities is maintained while running an application and
the Activity at the top of the stack is the one currently being displayed.
Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android
Activity is the subclass of ContextThemeWrapper class.
By the help of activity, you can place all your UI components or widgets in a single screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.
Android Activity Lifecycle methods
Let's see the 7 lifecycle methods of android activity.
Method Description
onResume() called when activity will start interacting with the user.
Page 4
Mobile Application Development Unit-II
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/
apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.activitylifecycle.MainActivity">
Page 5
Mobile Application Development Unit-II
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="#00ffff"
android:textColor="#ff0000"
android:textStyle="bold"
android:typeface="monospace"
android:textSize="35dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
It provides the details about the invocation of life cycle methods of activity. In this example, we are
displaying the content on the logcat.
File: MainActivity.java
package example.javatpoint.com.activitylifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart()
{
Page 6
Mobile Application Development Unit-II
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume()
{
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause()
{
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop()
{
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart()
{
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
Page 7
Mobile Application Development Unit-II
Output:
You will not see any output on the emulator or device. You need to open logcat.
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Now click on the HOME Button. You will see onPause method is invoked.
Page 8
Mobile Application Development Unit-II
Now see on the emulator. It is on the home. Now click on the center button to launch the app again.
Page 9
Mobile Application Development Unit-II
Now see on the logcat: onRestart, onStart and onResume methods are invoked.
Now click on the back button. Now you will see onPause methods is invoked.
Page
10
Mobile Application Development Unit-II
After a while, you will see onStop and onDestroy methods are invoked.
Note:The onCreate() and onDestroy() methods are called only once throughout the activity
lifecycle.
This is the required xml file for all the android application and located inside the root directory.
Page
11
Mobile Application Development Unit-II
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The <manifest> tag, is the root element of this XML document and contains several attributes:
android—Identifies the Android namespace used to provide several system attributes used
within the application.
package—Its value is set to the application’s Java package. The name of the application
package acts as the unique identifier for the application in the Android device.
versionCode/versionName—The versionCode attribute is used to define the current
application version. The version is used internally to compare application versions.
The versionName attribute is used to specify a version number that is displayed to users.
<uses-sdk>—This tag is optional and is used to specify the maximum, minimum, and
preferred API level required for the application to operate. Three attributes are used with
this tag as follows:
android:minSdkVersion—Used to specify the minimum API level required for this
application to run. The default value is “1.” For example, the following attribute says that
the minimum API level required by the application is 15:
android:minSdkVersion="15"
Hence, the application will run on API Level 15 and above, but will not run on API Level 14 or
below.
Page
12
Mobile Application Development Unit-II
Page
13
Mobile Application Development Unit-II
<provider> tags—Used for declaring content providers. Content providers provide content,
that is, data to applications. They help in handling, storing, and sharing data such as audio,
images, video, and contact lists with other applications. Android ships with a number of
content providers that the applications can use to access and share data with other
applications.
<uses-permission> tags—Used for declaring the permissions that the application needs.
Example:
<uses-permission android:name="android.permission.CAMERA" /> —Used for the
application that needs to use the camera.
<uses-permission android:name="android.permission.INTERNET"/> —Used for the
application that needs to access the Internet
Note
The <uses-permission> tags are nested within <manifest> tags. They appear at the same level
as the <application> tag.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="#00ffff"
android:textColor="#ff0000"
android:textStyle="bold"
android:typeface="monospace"
android:textSize="35dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Page
15
Mobile Application Development Unit-II
the FrameLayout overlaps the previous view; that is, each view stacks on top of the previous
one.
TableLayout—In this layout, the screen is assumed to be divided in table rows, and each of
the child elements is arranged in a specific row and column.
GridLayout—In this layout, child views are arranged in a grid format, that is, in the rows
and columns pattern. The views can be placed at the specified row and column location.
Also, more than one view can be placed at the given row and column position.
A brief description of Controls follows:
The following list highlights some of the controls commonly used in Android applications:
TextView—A read-only text label. It supports multiline display, string formatting, and
automatic word wrapping.
EditText—An editable text box that also accepts multiline entry and word-wrapping.
ListView—A ViewGroup that creates and manages a vertical list of views, displaying them
as rows within the list.
Spinner—A TextView and an associated list of items that allows us to select an item from
the list to display in the text box.
Button—A standard command button.
CheckBox—A button allowing a user to select (check) or unselect (uncheck).
RadioButton—A mutually exclusive button, which, when selected, unselects all other
buttons in the group.
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
Page
16
Mobile Application Development Unit-II
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.
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.
EVENT HANDLING
In our sample application, you want the user to enter a name in the EditText control. After the user
has entered the name and clicks the Button control, a welcome message displays on the screen. The
action of clicking a Button, pressing the Enter key, or performing any action on any control is
considered an event. The reaction to the event, that is, the action to be taken when the event
occurs, is called event handling.
To handle an event, you use the listeners that wait for an event occurrence. When an event occurs,
the listeners detect it and direct the program to the appropriate routine.
Page
17
Mobile Application Development Unit-II
An event listener is an interface in the View class that contains a single callback method,
called an event occurrence.
For example the callback method onClick() is called when the user clicks on a button. For event
handling, the event listener is either implemented in the Activity class or is defined as
an anonymous class. Thereafter, an instance of the implementation is passed to the respective
control through the setOnClickListener() method.
Note:Click is just one type of an event.
Drag the component or write the code for UI in activity_main.xml
First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets
palette as shown in the following figure.
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.eventhandling.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Page
18
Mobile Application Development Unit-II
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#00ffff"
android:gravity="center"
android:text="Enter First Num"
android:textColor="#ff0000"
android:textSize="15dp"
android:textStyle="bold"
android:typeface="monospace"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="63dp"
android:layout_toEndOf="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="53dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
Page
19
Mobile Application Development Unit-II
android:background="#00ffff"
android:gravity="center"
android:text="Enter Second Num"
android:textColor="#ff0000"
android:textSize="15dp"
android:textStyle="bold"
android:typeface="monospace"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignStart="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="28dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="127dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="109dp"
android:text="ADD"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
</RelativeLayout>
Page
20
Mobile Application Development Unit-II
Activity class
Now write the code to display the sum of two numbers.
File: MainActivity.java
package in.kvsw.eventhandling;
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 MainActivityextends AppCompatActivity
{
private EditTextedittext1, edittext2;
private Button buttonSum;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton()
{
edittext1 = (EditText) findViewById(R.id.editText1);
edittext2 = (EditText) findViewById(R.id.editText2);
buttonSum= (Button) findViewById(R.id.button);
buttonSum.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String value1=edittext1.getText().toString();
String value2=edittext2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);
Page
21
Mobile Application Development Unit-II
int sum=a+b;
Toast.makeText(getApplicationContext(),String.valueOf(sum),
Toast.LENGTH_LONG).show();
}
});
}
}
Output:
Page
23
Mobile Application Development Unit-II
Page
24
Mobile Application Development Unit-II
android:password—When set to true, the attribute converts the typed characters into dots
to hide entered text.
android:minWidth—Used to specify the minimum width of the control.
android:maxWidth—Used to specify the maximum width of the control. Text typed
beyond the maximum width scrolls if the android:scrollHorizontally attribute is set to true;
otherwise, it moves onto the next line.
android:minHeight—Used to specify the minimum height of the control.
android:maxHeight—Used to specify the maximum height of the control.
android:scrollHorizontally—When set to true, makes the text scroll horizontally if typed
beyond the specified width of the control.
android:inputType—Specifies the type of data that will be typed in the EditText control.
This attribute configures the onscreen keyboard too. There are many possible values that
include number, phone, text, textCapCharacters, textCapWords, textEmailAddress, datetime
, date, time, textAutoCorrect, textMultiLine, and textPassword.
The following keypads show how the onscreen keyboard changes when the
values number, phone, text, textCap Characters, and textEmailAddress are assigned to this
attribute, respectively.
This single attribute actually replaces many attributes such as
android:number, android:phoneNumber, android:text, android:capitalize,
and android: textEmailAddress.
Page
25
Mobile Application Development Unit-II
Page
26
Mobile Application Development Unit-II
There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:
Method Description
activity_main.xml
Drag one TextView, three checkboxes and one button for the layout. Now the activity_main.xml
file will look like this:
File: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android
.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.kvsw.checkbox.MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="370dp"
android:layout_height="42dp"
android:background="#00ffff"
android:gravity="center"
android:text="Select the Items you want"
android:textColor="#ff0000"
android:textSize="25dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="17dp"
tools:layout_editor_absoluteY="18dp" />
Page
27
Mobile Application Development Unit-II
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="68dp"
android:text="Pizza"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Coffee"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Burger"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
Page
28
Mobile Application Development Unit-II
android:layout_marginTop="184dp"
android:text="Order"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
</android.support.constraint.ConstraintLayout>
Activity class
Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java
package in.kvsw.checkbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivityextends AppCompatActivity
{
CheckBoxpizza,coffe,burger;
Button buttonOrder;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick()
{ //Getting instance of CheckBoxes and Button from the activty_main.xml file
pizza=(CheckBox)findViewById(R.id.checkBox);
coffe=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button);
//Applying the Listener on the Button click
Page
29
Mobile Application Development Unit-II
buttonOrder.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
int totalamount=0;
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked())
{
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked())
{
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked())
{
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(),
Toast.LENGTH_LONG).show();
}
});
}
}
Page
30
Mobile Application Development Unit-II
Output:
RadioButton is a two states button which is either checked or unchecked. If a single radio
button is unchecked, we can click it to make checked radio button. Once a radio button is checked,
it cannot be marked as unchecked by user.
The difference between check boxes and radio buttons is that you can select more than one
check box in a set, whereas radio buttons are mutually exclusive—only one radio button can be
selected in a group.
Selecting a radio button automatically deselects other radio buttons in the group.
To make them mutually exclusive, RadioButton controls are grouped together into
the RadioGroupelement so that no more than one can be selected at a time.
To create a group of radio buttons, first create a RadioGroup and then populate the group
with few RadioButton controls.
In Java, the following methods can be applied to RadioButtons:
isChecked()—Detects whether the RadioButton control is selected.
toggle()—Toggles the state of the RadioButton from selected to unselected and vice versa.
check()—Checks a specific RadioButton whose ID is supplied in the method.
getCheckedRadioButtonId()—Gets the ID of the currently selected RadioButton control.
It returns –1 if no RadioButton control is checked.
Page
31
Mobile Application Development Unit-II
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="20dp"
android:background="#B8B894" />
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:background="#00ffff"
android:textColor="#ff0000"
android:textStyle="bold"
android:textSize="22dp"
android:text="Select Gender of the Student" />
<!-- Customized RadioButtons -->
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroup">
Page
32
Mobile Application Development Unit-II
<RadioButton
android:id="@+id/radioMale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Male"
android:layout_marginTop="10dp"
android:checked="false"
android:textSize="20dp" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Female"
android:layout_marginTop="20dp"
android:checked="false"
android:textSize="20dp" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected"
android:id="@+id/button"
android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Activity class
File: MainActivity.java
package in.kvsw.radiobuttons;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
Page
33
Mobile Application Development Unit-II
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivityextends AppCompatActivity
{
Button button;
RadioButtongenderradioButton;
RadioGroupradioGroup;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View v)
{
int selectedId = radioGroup.getCheckedRadioButtonId();
genderradioButton= (RadioButton) findViewById(selectedId);
if(selectedId==-1)
{
Toast.makeText(MainActivity.this,"Nothing selected",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
}
Page
34
Mobile Application Development Unit-II
Output
Page
35