18ai63 Module4
18ai63 Module4
18ai63 Module4
18AI63- Module-4
lOMoAR cPSD| 27793530
➢ Open Source
➢ Customize Products
➢ Apple’s iPhone
Page 1
lOMoAR cPSD| 27793530
➤ 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.
Page 2
lOMoAR cPSD| 27793530
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.
• Applications
• Application Framework
• Android Runtime
• Platform Libraries
• Linux Kernel
Page 3
lOMoAR cPSD| 27793530
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
• 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.
• 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
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" />
Page 6
lOMoAR cPSD| 27793530
Page 7
lOMoAR cPSD| 27793530
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
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.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
Page 9
lOMoAR cPSD| 27793530
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:
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
6. Click the Home button, click the Overview icon, select the Activity101 application,
and observe the following:
Page 10
lOMoAR cPSD| 27793530
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
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 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
➤ 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.
<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
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.
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.
<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
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" />
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;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Page 14
lOMoAR cPSD| 27793530
@Override
public void onFinish() {
progressDialog.dismiss();
}
}.start();
}
}
Press Shift+F9 to debug the application on the Android emulator. You see the progress dialog,
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
1. Using Android Studio, create a new Android project with an empty Activity named
MainActivity; name the project UsingIntent.
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.
<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>
</intent-filter>
</activity>
<intent-filter >
</intent-filter>
Page 16
lOMoAR cPSD| 27793530
</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.
<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;
Page 17
lOMoAR cPSD| 27793530
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
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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
1. Using the same project from the previous section, modify the secondactivity.xml file to look
Page 19
lOMoAR cPSD| 27793530
like the following code. Please be sure to change all references from "com.girish" to
whatever package name your project is using:
<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"
<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>
Page 20
lOMoAR cPSD| 27793530
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;
data.setData(Uri.parse(txt_username.getText().toString()));
setResult(RESULT_OK, data);
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;
Page 21
lOMoAR cPSD| 27793530
int request_Code = 1;
@Override
setContentView(R.layout.activity_main);
startActivityForResult(new Intent("com.girish.usingintent.
SecondActivity"),request_Code);
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),
Toast.LENGTH_SHORT).show();
}
}
}
}
Page 22
lOMoAR cPSD| 27793530
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.
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
import android.widget.Toast;
@Override
Toast.makeText(this,getIntent().getStringExtra("str1"),
Toast.LENGTH_SHORT).show();
Toast.makeText(this,Integer.toString(
getIntent().getIntExtra("age1", 0)), Toast.LENGTH_SHORT).show();
i.putExtra("age3", 45);
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
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
Activity 1.
<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
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);
}
}
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
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;
Page 28
lOMoAR cPSD| 27793530
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
Page 29
lOMoAR cPSD| 27793530
Page 30
lOMoAR cPSD| 27793530
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
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
@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
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 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
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
@Override
FragmentManager fM = getFragmentManager();
FragmentTransaction fT = fM.beginTransaction();
else
//---portrait mode---
Page 34
lOMoAR cPSD| 27793530
fT.commit();
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"));
You can also create an Intent object by passing in an action constant and data, such as the
following:
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:
Page 35
lOMoAR cPSD| 27793530
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:
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.
➤ 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
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.
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}
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;
Page 37
lOMoAR cPSD| 27793530
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
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
Page 39