18ai63 Module4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

lOMoAR cPSD| 27793530

18AI63- Module-4
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

➢ Android is a mobile operating system that is based on a modified version of


Linux.

➢ It was originally developed by a startup of the same name, Android, Inc.

➢ In 2005, Google purchased Android to enter into mobile space

➢ Open Source

➢ Customize Products

➢ Apple’s iPhone

➢ Motorola and Sony Ericsson

Page 1
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Because Android is open source and freely available to manufacturers for


customization, there are no fixed hardware or software configurations. However, the
base Android OS supports many features, including

➤ Storage—SQLite, a lightweight relational database, for data storage.

➤ Connectivity—GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth


(includes A2DP and AVRCP), Wi-Fi, LTE, and WiMAX.

➤ Messaging—Both SMS and MMS.

➤ Media support H.263, H.264 (in 3GP or MP4 container), MPEG-4 SP, AMR,
AMR-WB (in 3GP container), AAC, HE-AAC (in MP4 or 3GP container), MP3,
MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP.

➤ Hardware support —Accelerometer sensor, camera, digital compass,


proximity sensor, and GPS.

➤ Multi-touch —Multi-touch screens.

➤ Multi-tasking —Multi-tasking applications.

➤ Tethering —Sharing of Internet connections as a wired/wireless hotspot.

Page 2
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Android architecture contains different number of components to support any android device
needs. Android software contains an open-source Linux Kernel having collection of number of
C/C++ libraries which are exposed through an application framework services.

The main components of android architecture are following: -

• Applications
• Application Framework
• Android Runtime
• Platform Libraries
• Linux Kernel

Page 3
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Applications:
Applications is the top layer of android architecture. The pre-installed applications like home,
contacts, camera, gallery etc and third party applications downloaded from the play store like
chat applications, games etc. will be installed on this layer only.
It runs within the Android run time with the help of the classes and services provided by the
application framework.
Application framework:
Application Framework provides several important classes which are used to create an Android
application. It provides a generic abstraction for hardware access and also helps in managing the
user interface with application resources. Generally, it provides the services with the help of
which we can create a particular class and make that class helpful for the Applications creation.

It includes different types of services activity manager, notification manager, view system,
package manager etc. which are helpful for the development of our application according to the
prerequisite.

Application runtime:
Android Runtime environment is one of the most important part of Android. It contains
components like core libraries and the Dalvik virtual machine(DVM). Mainly, it provides the
base for the application framework and powers our application with the help of the core libraries.

Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based virtual
machine and specially designed and optimized for android to ensure that a device can run
multiple instances efficiently. It depends on the layer Linux kernel for threading and low-level
memory management. The core libraries enable us to implement android applications using the
standard JAVA or Kotlin programming languages.

Platform libraries:
The Platform Libraries includes various C/C++ core libraries and Java based libraries such as
Media, Graphics, Surface Manager, OpenGL etc. to provide a support for android development.

• Media library provides support to play and record an audio and video formats.
• Surface manager responsible for managing access to the display subsystem.

Page 4
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

• SGL and OpenGL both cross-language, cross-platform application program interface (API)
are used for 2D and 3D computer graphics.
• SQLite provides database support and FreeType provides font support.
• Web-Kit This open source web browser engine provides all the functionality to display web
content and to simplify page loading.
• SSL (Secure Sockets Layer) is security technology to establish an encrypted link between
a web server and a web browser.

Linux Kernel :
Linux Kernel is heart of the android architecture. It manages all the available drivers such as
display drivers, camera drivers, Bluetooth drivers, audio drivers, memory drivers, etc. which are
required during the runtime.

The Linux Kernel will provide an abstraction layer between the device hardware and the other
components of android architecture. It is responsible for management of memory, power, devices
etc.

The features of Linux kernel are:

• Security: The Linux kernel handles the security between the application and the system.
• Memory Management: It efficiently handles the memory management thereby providing
the freedom to develop our apps.
• Process Management: It manages the process well, allocates resources to processes
whenever they need them.
• Network Stack: It effectively handles the network communication.
• Driver Model: It ensures that the application works properly on the device and hardware
manufacturers responsible for building their drivers into the Linux build.

Page 5
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

An Android application can have zero or more activities. Typically, applications have one or
more activities. The main purpose of an activity is to interact with the user. From the moment
an activity appears on the screen to the moment it is hidden, it goes through anumber of stages.
These stages are known as an activity’s life cycle. Understanding the life cycle of an activity
is vital to ensuring that your application works correctly.

Understanding Activities
This section begins by showing you how to create an activity. To create an activity, you create a
Java class that extends the Activity base class:
package com.girish.chapter1;
importandroid.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Your activity class loads its user interface (UI) component using the XML file defined in your
res/ layout folder. In this example, you would load the UI from the main.xml file:
setContentView(R.layout.activity_main);

Every activity you have in your application must be declared in your AndroidManifest.xml
file, like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android
package="com.girish.chapter1helloworld">
<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>
The Activity base class defines a series of events that govern the life cycle of an activity. Below
figure shows the lifecycle of an Activity.

Page 6
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

The Activity class defines the following events:


➤ onCreate()— Called when the activity is first created

➤ onStart()— Called when the activity becomes visible to the user


➤ onResume()— Called when the activity starts interacting with the user
➤ onPause()— Called when the current activity is being paused and the previous activity is
being resumed
➤ onStop()— Called when the activity is no longer visible to the user

Page 7
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

onDestroy()— Called before the activity is destroyed by the system (either manually or by
the system to conserve memory)
➤ onRestart()— Called when the activity has been stopped and is restarting again

By default, the activity created for you contains the onCreate() event. Within this event handler
is the code that helps to display the UI elements of your screen.

1. onCreate()
It is called when the activity is first created. This is where all the static work is done like creating
views, binding data to lists, etc. This method also provides a Bundle containing its previous
frozen state, if there was one.

2. onStart()
It is invoked when the activity is visible to the user. It is followed by onResume() if the activity
is invoked from the background. It is also invoked after onCreate() when the activity is first
started.

3. onRestart()
It is invoked after the activity has been stopped and prior to its starting stage and thus is always
followed by onStart() when any activity is revived from background to on-screen.

4. onResume()
It is invoked when the activity starts interacting with the user. At this point, the activity is at the
top of the activity stack, with a user interacting with it. Always followed by onPause() when the
activity goes into the background or is closed by the user.

5. onPause()
It is invoked when an activity is going into the background but has not yet been killed. It is a
counterpart to onResume(). When an activity is launched in front of another activity, this
callback will be invoked on the top activity (currently on screen). The activity, under the active
activity, will not be created until the active activity’s onPause() returns.

6. onStop()
It is invoked when the activity is not visible to the user. It is followed by onRestart() when the
activity is revoked from the background, followed by onDestroy() when the activity is closed or
finished, and nothing when the activity remains on the background only. Note that this method

Page 8
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

may never be called, in low memory situations where the system does not have enough memory
to keep the activity’s process running after its onPause() method is called.
7. onDestroy()
The final call received before the activity is destroyed. This can happen either because the
activity is finishing (when finish() is invoked) or because the system is temporarily destroying
this instance of the activity to save space. To distinguish between these scenarios, check it
with isFinishing() method.

Understanding the life cycle of an Activity


1. Using Android Studio, create a new Android project and name it Activity101.
2. In the Activity101 Activity.java file, add the following highlighted statements. (Please
note: Throughout this example, be sure to change all references to "com.girish " to
whatever package name your project is using.)
package com.girish.activity101;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity


{
String tag = "Lifecycle Step";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(tag, "In the onCreate() event");
}

public void onStart()


{
super.onStart();
Log.d(tag, "In the onStart() event");
}

public void onRestart()


{
super.onRestart();
Log.d(tag, "In the onRestart() event");
}

public void onResume()


{
super.onResume();

Page 9
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Log.d(tag, "In the onResume() event");


}

public void onPause()


{
super.onPause();
Log.d(tag, "In the onPause() event");
}
public void onStop()
{
super.onStop();
Log.d(tag, "In the onStop() event");
}

public void onDestroy()


{
super.onDestroy();
Log.d(tag, "In the onDestroy() event");
}
}

3. Press Shift+F9 to debug the application, or select Run ➪ Debug. Then select one of your
Android Virtual Devices from the pop-up window.

4. When the activity is first loaded, you should see something very similar to the following in
the logcat console. If you do not see the logcat console, click Android Monitor at the bottom
of the Android Studio window:

11-16 06:25:59.396: D/Lifecycle Step(559): In the onCreate() event 11-16


06:25:59.396: D/Lifecycle Step(559): In the onStart() event 11-16 06:25:59.396:
D/Lifecycle Step(559): In the onResume() event

5. If you click the Back button on the Android emulator, you see the following:
11-16 06:29:26.665: D/Lifecycle Step(559): In the onPause() event 11-16
06:29:28.465: D/Lifecycle Step(559): In the onStop() event

11-16 06:29:28.465: D/Lifecycle Step(559): In the onDestroy() event

6. Click the Home button, click the Overview icon, select the Activity101 application,
and observe the following:

Page 10
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

11-16 06:31:08.905: D/Lifecycle Step(559): In the onCreate() event 11-16


06:31:08.905: D/Lifecycle Step(559): In the onStart() event 11-16
06:31:08.925: D/Lifecycle Step(559): In the onResume() event

7. Click the Home button and then click the Phone button on the Android emulator so that
the activity is pushed to the background. Observe the output in the logcat window:
11-16 06:32:00.585: D/Lifecycle Step(559): In the onPause() event 11-16
06:32:05.015: D/Lifecycle Step(559): In the onStop() event

8. Notice that the onDestroy() event is not called, indicating that the activity is still in
memory. Exit the phone dialer by clicking the Back button. The activity is now visible
again. Observe the output in the logcat window:
11-16 06:32:50.515: D/Lifecycle(559): In the onRestart() event 11-16
06:32:50.515: D/Lifecycle(559): In the onStart() event 11-16 06:32:50.515:
D/Lifecycle(559): In the onResume() event

The onRestart()event is now fired, followed by the onStart()and onResume()methods.

How It Works
As you can see from this simple example, an activity is destroyed when you click the Back
button. This is crucial to understand because whatever state the activity is currently in will be
lost. This means you need to write additional code in your activity to preserve its state when the
activity is destroyed. At this point, note that the onPause() method is called in both scenarios:
➤ When an activity is sent to the background

➤ When a user kills an activity by tapping the Back button

When an activity is started, the onStart() and onResume()methods are always called, regardless
of whether the activity is restored from the background or newly created. When an
activity is created for the first time, the onCreate() method is called.

From the preceding example, you can derive the following guidelines:

➤ Use the onCreate() method to create and instantiate the objects that you will be using
in your application.

➤ Use the onResume() method to start any services or code that needs to run while
your activity is in the foreground.
➤ Use the onPause() method to stop any services or code that does not need
to run when your activity is not in the foreground.

Page 11
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

➤ Use the onDestroy() method to free up resources before your activity is destroyed.

NOTE Even if an application has only one activity and the activity is killed, the
application is still running in memory.

Applying Styles and Themes to an Activity


By default, an activity is themed to the default Android theme. However, there has been a push
in recent years to adopt a new theme known as Material. The Material theme has a much more
modern and clean look to it.
There are two versions of the Material theme available to Android developers: Material Light and
Material Dark. Either of these themes can be applied from the AndroidManifest.xml.
To apply one of the Material themes to an activity, simply modify the <Application> element
in the AndroidManifest.xml file by changing the default android:theme attribute. (Please
be sure to change all instances of "com.girish" to whatever package name your project is
using.)
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.
girish.activity101">

<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:supportsRtl="true"
android:theme="@android:style/Theme.Material">
<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>
Changing the default theme to @android:style/Theme.Material, as in the highlighted code in the
preceding snippet, applies the Material Dark theme and gives your application a darker look as
shown below

Page 12
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Displaying a Progress Dialog


One common UI feature in an Android device is the “Please wait” dialog that you typically see
when an application is performing a long-running task. For example, the application might be
logging in to a server before the user is allowed to use it, or it might be doing a calculation before
displaying the result to the user. In such cases, it is helpful to display a dialog, known as a
progress dialog, so that the user is kept in the loop.

Android provides a ProgressDialog class you can call when you want to display a
running meter to the user. ProgressDialog is easy to call from an activity.

The following Try It Out demonstrates how to display such a dialog.

Using the Activity101 project created earlier in this chapter, make sure you are using the
Material theme in the AndroidManifest.xml file. Be sure to change all instances of
"com.girish" to whatever package name your project is using.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.girish.activity101">

<application

Page 13
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.Material">
<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>

Add the bolded statements from the following code to the MainActivity.java file:

package com.girish.activity101;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.CountDownTimer;
import android.os.Bundle;

public class MainActivity extends Activity {

ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

public void onStart()


{
super.onStart();
progressDialog = ProgressDialog.show(this,"Please Wait",
"Processing...",true);
CountDownTimer timer = new CountDownTimer(3000,1000) {
@Override
public void onTick(long millisUntilFinished) {

Page 14
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

@Override
public void onFinish() {
progressDialog.dismiss();
}
}.start();
}
}
Press Shift+F9 to debug the application on the Android emulator. You see the progress dialog,

Linking Activities Using Intents

An Android application can contain zero or more activities. When your application has more
than one activity, you often need to navigate from one to another. In Android, you navigate
between activities through what is known as an intent.

Page 15
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

1. Using Android Studio, create a new Android project with an empty Activity named
MainActivity; name the project UsingIntent.

2. Right-click your package name under the app>>app>>src>>main>>java folder in the


Project Files windows and select New ➪ Java Class

3. Name the new class SecondActivity and click OK.

4. Add the bolded statements from the following code to the AndroidManifest.xml file.
Be sure to change all instances of "com.girish" to whatever package name your project
is using.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com. girish.usingintent">

<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>

<activity android:name=".SecondActivity" >

<intent-filter >

<action android:name="com.girish.usingintent.SecondActivity" />

<category android:name="android.intent.category.DEFAULT" />

</intent-filter>

Page 16
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

</activity>

</application>

</manifest>

5. Make a copy of the activity_main.xml file (in the res/layout folder) by right-
clicking it and selecting Copy. Then right-click the res/layout folder and select Paste.
Name the file activity_second.xml.

6. Modify the activity_second.xml file as follows:


<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.girish.usingintent.SecondActivity">

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the Second Activity!" />
</RelativeLayout>

7. In the SecondActivity.java file, add the bolded statements from the following code:
package com.girish.usingintent;

import android.app.Activity;
import android.os.Bundle;

public class SecondActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Page 17
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

8. Add the bolded lines in the following code to the activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.girish.usingintent.MainActivity">

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="Main Activity!"

android:id="@+id/textView" />

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display second activity"
android:onClick="onClick"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="56dp" />
</RelativeLayout>

9. Modify the MainActivity.java file as shown in the bolded lines in the following
code:
package com.girish.usingintent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

Page 18
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

public void onClick(View view) {

startActivity(new Intent("com.girish.usingintent.SecondActivity"));

Press Shift+F9 to debug the application on the Android emulator. When the first activity is loaded,
click the button and the second activity also loads

Returning Results from an Intent


The startActivity() method invokes another activity but does not return a result to the current
activity. For example, you might have an activity that prompts the user for username and
password. The information entered by the user in that activity needs to be passed back to the
calling activity for further processing. If you need to pass data back from an activity, you should
instead use the startActivityForResult() method.

1. Using the same project from the previous section, modify the secondactivity.xml file to look

Page 19
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

like the following code. Please be sure to change all references from "com.girish" to
whatever package name your project is using:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android
" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com. girish.usingintent.SecondActivity">

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="This is the Second Activity!"


android:id="@+id/textView2" />

<TextView

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please enter your
name" android:id="@+id/textView3" />

<EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:id="@+id/txtUsername" />

<Button

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
android:onClick="onClick"
android:id="@+id/button2" />
</LinearLayout>

2. Add the bolded statements in the following code to SecondActivity.java: package

Page 20
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

com.girish.usingintent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import android.widget.EditText;

public class SecondActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

public void onClick(View view) {

Intent data = new Intent();

//---get the EditText view---


EditText txt_username = (EditText)findViewById(R.id.txtUsername);

//---set the data to pass back---

data.setData(Uri.parse(txt_username.getText().toString()));

setResult(RESULT_OK, data);

//---closes the activity---


finish();
}
}

3. Add the bolded statements in the following code to the MainActivity.java file:
package com. girish.usingintent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

Page 21
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

int request_Code = 1;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

public void onClick(View view) {

startActivityForResult(new Intent("com.girish.usingintent.

SecondActivity"),request_Code);

public void onActivityResult(int requestCode, int resultCode,


Intent data)

if (requestCode == request_Code) {

if (resultCode == RESULT_OK) {

Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_SHORT).show();
}
}
}
}

Page 22
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

4. Press Shift+F9 to debug the application on the Android emulator. When the first activity is
loaded, click the button to load SecondActivity. Enter your name and click the OK button.

Passing Data Using an Intent Object


Besides returning data from an activity, it is also common to pass data to an activity. For
example, in the previous example, you might want to set some default text in the EditText view
before the activity is displayed. In this case, you can use the Intent object to pass the data to
the target activity.

Add a new Class file to the package and name it SecondActivity. Populate the
SecondActivity.java file as follows:
package com.girish.passingdata
import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.os.Bundle;

import android.view.View;

Page 23
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

import android.widget.Toast;

public class SecondActvity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Toast.makeText(this,getIntent().getStringExtra("str1"),
Toast.LENGTH_SHORT).show();
Toast.makeText(this,Integer.toString(
getIntent().getIntExtra("age1", 0)), Toast.LENGTH_SHORT).show();

public void onClick(View view) {

Intent i = new Intent();

i.putExtra("age3", 45);

i. setData(Uri.parse("Something passed back to main activity"));

setResult(RESULT_OK, i);

finish();

}
}

Fragments
In the previous section, you learned what an activity is and how to use it. In a small-screen
device (such as a smartphone), an activity typically fills the entire screen, displaying the various
views that make up the user interface of an application. The activity is essentially a container
for views. However, when an activity is displayed in a large-screen device, such as on a tablet,
it is somewhat out of place. Because the screen is much bigger, all the views in an activity must
be arranged to make full use of the increased space, resulting in complex changes to the view
hierarchy. A better approach is to have “mini-activities,” each containing its own set of views.
During runtime, an activity can contain one or more of these mini-activities, depending on the
screen orientation in which the device is held. In Android 3.0 and later, these mini-activities are

Page 24
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

known as fragments.

Think of a fragment as another form of activity. You create fragments to contain views,
just like activities. Fragments are always embedded in an activity. For example, below figure
shows two fragments. Fragment 1 might contain a ListView showing a list of book titles.
Fragment 2 mightcontain some TextViews and ImageViews showing some text and images.

Fragment 1 Fragment 2

Now imagine the application is running on an Android tablet (or on an Android smartphone) in
portrait mode. In this case, Fragment 1 might be embedded in one activity, whereas Fragment 2
might be embedded in another activity (see below figure). When users select an item in the list
in Fragment 1, Activity 2 is started.

Activity 1 Activity 2

If the application is now displayed in a tablet in landscape mode, both fragments can be
embedded within a single activity, as shown in figure. From this discussion, it becomes apparent
that fragments present a versatile way in which you can create the user interface of an Android
application. Fragments form the atomic unit of your user interface, and they can be dynamically
added (or removed) to activities in order to create the best user experience possible for the target
device.

Page 25
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Activity 1.

1. In activity_main.xml, add the bolded lines in the following code:


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"

android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.girish.fragments.MainActivity">

<fragment

android:name="com.girish.fragments.Fragment1"
android:id="@+id/fragment1"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
<fragment
android:name="com.girish.fragments.Fragment2"
android:id="@+id/fragment2"

android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="match_parent" />

</LinearLayout>

Page 26
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

2. Under the <Your Package Name>/fragments package name, add two Java class files
and name them Fragment1.java and Fragment2.java
3. Add the following code to Fragment1.java: package com.girish.fragments;
Import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
return inflater.inflate( R.layout.fragment1, container, false);
}
}

4. Add the following code to Fragment2.java:


package com.girish.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
inflater.inflate(R.layout.fragment2, container, false);
}
}

5. Press Shift+F9 to debug the application on the Android emulator. Below figure shows the
two fragments contained within the activity.

Page 27
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Adding Fragments Dynamically


Although fragments enable you to compartmentalize your UI into various configurable
parts, the real power of fragments is realized when you add them dynamically to activities during
runtime. In the previous section, you saw how you can add fragments to an activity by modifying
the XML file during design time. In reality, it is much more useful if you create fragments and
add them to activities during runtime. This enables you to create a customizable user interface
for your application.
For example, if the application is running on a smartphone, you might fill an activity
with a single fragment; if the application is running on a tablet, you might then fill the activity
with two or more fragments, as the tablet has much more screen real estate compared to a
smartphone.

1. Add the bolded lines in the following code to the MainActivity.java file:
package com.girish.fragments;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.DisplayMetrics;

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DisplayMetrics display = this.getResources().getDisplayMetrics();

int width = display.widthPixels;


int height = display.heightPixels;
if (width> height)
{
//---landscape mode---
Fragment1 f1 = new Fragment1();
ft.replace( android.R.id.content, f1);
}
else
{
//---portrait mode---
Fragment2 f2 = new Fragment2();
ft.replace( android.R.id.content, f2);
}

Page 28
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

ft.commit();
}
}

Press Shift + F9 to run the application on the Android emulator. Observe that when the emulator
is in portrait mode, Fragment 2 is displayed. If you press Ctrl+Left to change the orientation
of the emulator to landscape, Fragment 1 is shown instead

Life Cycle of a Fragment


Like activities, fragments have their own life cycle. Understanding the life cycle of a fragment
enables you to properly save an instance of the fragment when it is destroyed, and restore it to its
previous state when it is re-created.

Page 29
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

No. Method Description

1) onAttach(Activity) it is called only once when it is attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

Page 30
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the fragment that all the saved


state of fragment view hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.

11) onDestroy() allows the fragment to do final clean up of fragment state.

12) onDetach() It is called immediately prior to the fragment no longer


being associated with its activity.

Implementation
package com.girish.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {

Page 31
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {

Log.d("Fragment 1", "onCreateView");

inflater.inflate(R.layout.fragment1, container, false);


}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d("Fragment 1", "onAttach");
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Fragment 1", "onCreate");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("Fragment 1", "onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.d("Fragment 1", "onStart");
}
@Override
public void onResume() {
super.onResume();
Log.d("Fragment 1", "onResume");
}
@Override
public void onPause() {
super.onPause();
Log.d("Fragment 1", "onPause");
}

@Override
public void onStop() {
super.onStop();
Log.d("Fragment 1", "onStop");
}
@Override
public void onDestroyView() {

Page 32
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

super.onDestroyView();
Log.d("Fragment 1", "onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("Fragment 1", "onDestroy");
}

@Override
public void onDetach() {
super.onDetach();
Log.d("Fragment 1", "onDetach");
}
}

How It Works
Like activities, fragments in Android also have their own life cycle. As you have seen, when
a fragment is being created, it goes through the following states:
➤ onAttach()
➤ onCreate()
➤ onCreateView()
➤ onActivityCreated()

When the fragment becomes visible, it goes through these states:


➤ onStart()
➤ onResume()

When the fragment goes into the background mode, it goes through these states:
➤ onPause()
➤ onStop()

When the fragment is destroyed (when the activity in which it is currently hosted is destroyed),
it goesthrough the following states:
➤ onPause()
➤ onStop()
➤ onDestroyView()
➤ onDestroy()
➤ onDetach()

Like activities, you can restore an instance of a fragment using a Bundle object, in the
following states:
➤ onCreate()
➤ onCreateView()
➤ onActivityCreated()

Page 33
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Most of the states experienced by a fragment are similar to those of activities. However, a
few new states are specific to fragments:
➤ onAttached()—Called when the fragment has been associated with the activity
➤ onCreateView() Called to create the view for the fragment

➤ onActivityCreated()—Called when the activity’s onCreate() method has been returned

Interactions(Communication) Between Fragments


Very often, an activity might contain one or more fragments working together to present a
coherent UIto the user. In this case, it is important for fragments to communicate with one another
and exchange data. For example, one fragment might contain a list of items.
Also, when the user taps on an item in that fragment, details about the selected item might
be dis- played in another fragment.
1. Modify the MainActivity.java file by commenting out the code that you added in the
earlier sections. It should look like this after modification:
public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

FragmentManager fM = getFragmentManager();

FragmentTransaction fT = fM.beginTransaction();

DisplayMetrics display = this.getResources().getDisplayMetrics();

int width = display.widthPixels;


int height = display.heightPixels;
if (width> height)
{
//---landscape mode---
Fragment1 fragment1 = new Fragment1();
fT.replace( android.R.id.content, fragment1);
}

else

//---portrait mode---

Page 34
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

Fragment2 fragment2 = new Fragment2();

fT.replace( android.R.id.content, fragment2);

fT.commit();

Understanding the Intent Object


So far, you have seen the use of the Intent object to call other activities. This is a good time
to recap and gain a more detailed understanding of how the Intent object performs its magic.

First, you learned that you can call another activity by passing its action to the constructor of an
Intent object:

startActivity(new Intent("com.girish.SecondActivity"));

The action (in this example "com.girish.SecondActivity") is also known as the


componentname. This is used to identify the target activity/application that you want to invoke.
You can also rewrite the component name by specifying the class name of the activity if it resides
in your project, like this:

startActivity(new Intent(this, SecondActivity.class));

You can also create an Intent object by passing in an action constant and data, such as the
following:

Intent i = new Intent(android.content.Intent.ACTION_VIEW,


Uri.parse("http://www.amazon.com"));

startActivity(i);

The action portion defines what you want to do, whereas the data portion contains the data for
the target activity to act upon. You can also pass the data to the Intent object using the
setData() method:

Intent i = new Intent("android.intent.action.VIEW");

Page 35
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

i. setData(Uri.parse("http://www.amazon.com"));

In this example, you indicate that you want to view a web page with the specified URL.
The Android OS will look for all activities that are able to satisfy your request. This process is
known as intent resolution. The next section discusses in more detail how your activities can be
the target of other activities.

For some intents, there is no need to specify the data. For example, to select a contact from the
Contacts application, you specify the action and then indicate the MIME type using the
setType()method:

Intent i = new Intent(android.content.Intent.ACTION_PICK);

i.setType(ContactsContract.Contacts.CONTENT_TYPE);

The setType() method explicitly specifies the MIME data type to indicate the type of data to
return. The MIME type for ContactsContract.Contacts.CONTENT_TYPE is
"vnd.android.cursor.dir/contact".

Besides specifying the action, the data, and the type, an Intent object can also specify a
category. A category groups activities into logical units so that Android can use those activities
for further filtering. The next section discusses categories in more detail.

To summarize, an Intent object can contain the following information:

➤ Action

➤ Data

➤ Type

➤ Category

Displaying Notifications

So far, you have been using the Toast class to display messages to the user. While the Toast class
is a handy way to show users alerts, it is not persistent. It flashes on the screen for a few seconds
and then disappears. If it contains important information, users may easily miss it if they are not

Page 36
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

looking at the screen.

For messages that are important, you should use a more persistent method. In this case, you
should use the NotificationManager to display a persistent message at the top of the device,
commonly known as the status bar (sometimes also referred to as the notification bar). The
following Try It Out demonstrates how.

1. Populate the NotificationView.java file as follows:


package com.girish.notifications;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
public class NotificationView extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}

2. Add the following statements in bold to the MainActivity.java file:


package com.girish.notifications;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;

public class MainActivity extends Activity {


int notificationID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
displayNotification();
}

Page 37
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

protected void displayNotification()


{

Intent i = new Intent(this, NotificationView.class);


i.putExtra("notificationID", notificationID);
PendingIntent pI = PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notifBuilder;
notifBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Meetin g
Reminder").setContentText("Reminder: Meeting starts in 5
minutes");
nm.notify(notificationID, notifBuilder.build());
}
}

3. Press Shift+F9 to debug the application on the Android emulator.

4. Click the Display Notification button and a notification ticker text (set in the constructor of
the
Notification object) displays on the status bar.

5. Click and drag the status bar down to reveal the notification details set using the
setLatestEventInfo() method of the Notification object
6. Press Shift+F9 to debug the application on the Android emulator.

7. Click the Display Notification button and a notification ticker text (set in the constructor
of the Notification object) displays on the status bar.

Page 38
lOMoAR cPSD| 27793530

JAVA for Mobile Applications – 18AI63

8. Click and drag the status bar down to reveal the notification details set using the
setLatestEventInfo() method of the Notification object

The getActivity() method retrieves a PendingIntent object and you set it using the
following arguments:
➤ context—Application context
➤ request code—Request code for the intent
➤ intent—The intent for launching the target activity
➤ flags—The flags in which the activity is to be launched

***********************END OF MODULE -4 **********************

Page 39

You might also like