0% found this document useful (0 votes)
120 views56 pages

Calling Built in

This document provides instructions for calling built-in Android applications using intents. It begins by explaining why using intents to call built-in apps is useful for developers. It then provides steps to create an Android project with buttons to launch the gallery, call log, contacts, dialer, browser, and maps apps. The code examples show how to define intent actions and URIs to start each built-in activity.

Uploaded by

ramalalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views56 pages

Calling Built in

This document provides instructions for calling built-in Android applications using intents. It begins by explaining why using intents to call built-in apps is useful for developers. It then provides steps to create an Android project with buttons to launch the gallery, call log, contacts, dialer, browser, and maps apps. The code examples show how to define intent actions and URIs to start each built-in activity.

Uploaded by

ramalalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

HomeTutorialAndroid

How to call built-in applications using intents


in Android
0 Rajeev Kumar Singh June 30, 2015
In this tutorial for developing android apps we will learn how to call built-in applications using
intents
How to check if Android Device Supports OpenGL ES 2.0
OpenGL Projects Android App available on Google Play Store
Getting Started with OpenGL ES for Android
Developing android apps specially the games required opengl for providing better graphics. We
have seen how to get started with opengl es for android, and will continue the opengl tutorial
for android programming. Today's we are going to learn an important concept in this android
development tutorial, how to call built-in applications using intents in Android. This give
advantage to developer taking in-build apps and throw user to them if required. Calling built in
applications using intents in Android is important as it give user more choices. For example in an
app you want user make a call or open a document (pdf) let you use the in-build apps, take off
the burden in developing those apps. You might have seen in previous Whatsapp, which let user
call from within the app (now they have their own voip).

Android intent example


Lets get started with how to use intent in android. The following Try It Out demonstrates how to
call some of the built-in applications commonly found on an Android device.

Prerequisite
In this android intent example you need the Android Studio or Eclipse with ADT plugin and
Android SDK tool. It is also necessary that you must know about some fundamentals of Java and
XML as well as about the Android device. We also assume here that you know hello world
program for developing android apps. This is a simple beginners tutorial, which hardly take you
half an hour to understand, and doing yourself. I am doing this in Android Studio but you may
choose Eclipse (remember google officially going to end support for ADT at the end of 2015).

Creating New Project


1. First step : Open Android Studio and Create a new project by selecting 'Start a new Android
Studio Project'. Give it a name MyIntent and a package name in.ruks. You can have your own
application package names. Click next, choose minimum SDK, in ours case it is API 14 :
Android 4.0 (IceCreamSandwich), which accounts for close to 90% of activated android devices.

Again click next, select the Blank Activity, Click next. Android will ask to name the activity, keep
the default names, click on finish. Android Studio will create the the new Android Project with
all the necessary files.

Set up Project Layout


We are going to use 6 built-in application in this android development tutorial. They are 1. Gallery
2. Call Log
3. Contact
4. Dailler
5. Browser
6. Map
2. Second step : Now the time to set up the layout of our project. We are going to call 6 built-in
applications using intents, hence we will place a button for each in activity_main.xml. You can
drag and drop 6 button on the layout or simply create by coding the activity_main.xml file. Check
out the code below and add it to activity_main.xml.

Second one
CALLING BUILD IN APPLICATION USING INTENTS
Calling Build in Application using Intents :
"Until this point, you have seen how to call activities
within your own application. One of the keyaspects of Android programming is using the intent
to call activities from other applications. In particular,your application can call the many builtin applications that are included with an Androiddevice. For example, if your application needs
to enable a user to call a particular person saved inthe Contacts application, you can simply use
an Intent object to bring up the Contacts application,from which the user can select the person
to call. This enables your application to present a consistentuser experience, and enables you to
avoid building another application to retrieve all the contacts in the Contacts application."

The following demonstrates how to call some of the built-in applications commonly
found on an Android device.
STEPS:

1.Using Eclipse, create a new Android project and name it Intents.

2. Add the following statements in bold to the main.xml file:


<?xml version=1.0 encoding=utf-8?>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:orientation=vertical
android:layout_width=fill_parent
android:layout_height=fill_parent >
<Button
android:id=@+id/btn_webbrowser
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Web Browser />
<Button
android:id=@+id/btn_makecalls
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Make Calls />
<Button
android:id=@+id/btn_showMap
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Show Map />
<Button
android:id=@+id/btn_chooseContact
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Choose Contact />
</LinearLayout>
3.Add the following statements in bold to the MainActivity.java file:
package net.learn2develop.Intents;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity


{
Button b1, b2, b3, b4;
int request_Code = 1;
// Called when the activity is first created.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.btn_webbrowser);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(http://www.amazon.com));
startActivity(i);
}
});
//Make calls button--b2 = (Button) findViewById(R.id.btn_makecalls);
b2.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_DIAL,
Uri.parse(tel:+651234567));
startActivity(i);
}
});
//Show Map button
b3 = (Button) findViewById(R.id.btn_showMap);
b3.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
Intent i = new
Intent(android.content.Intent.ACTION_VIEW,

Uri.parse(geo:37.827500,-122.481670));
startActivity(i);
}
});
//Choose Contact button
b4 = (Button) findViewById(R.id.btn_chooseContact);
b4.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0){
Intent i = new
Intent(android.content.Intent.ACTION_PICK);
i.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(i,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();
Intent i = new Intent(
android.content.Intent.ACTION_VIEW,
Uri.parse(data.getData().toString()));
startActivity(i);
}
}
}
}

4 Press F11 to debug the application on the Android Emulator.


5 Click the Web Browser button to load the Browser application on the emulator as shown in
Figure.

Home Android core app Fragment Android Fragments Example


About Katerina Zamani

Katerina has graduated from the Department of Informatics and


Telecommunications in National and Kapodistrian University of Athens (NKUA) and
she attends MSc courses in Advanced Information Systems at the same department.
Currently, her main academic interests focus on web applications, mobile
development, software engineering, databases and telecommunications.

Android Fragments Example

Posted by: Katerina Zamani in Fragment December 4th, 2013


A Fragment represents a portion of a user interface or an operation that runs within an
Activity.
A single activity can contain multiple fragments and many fragments can be reused in many,
different activities. It is not wrong if we say that a fragment is a type of sub-activity that can be
utilized again in multiple activities.
Although each fragment has each own lifecycle, it is connected with the Activity it belongs to,
so its lifecycle is directly influenced by the activitys lifecycle.
The main advantage of using fragments is due to the convenience of reusing the components in
different layouts. In this tutorial, we are going to create our own fragments, where each one will
be used when the user presses the appropriate button.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
1. JDK 1.7
2. Eclipse 4.2 Juno
3. Android SDK 4.4

Want to create a kick-ass Android App?

Subscribe to our newsletter and download the Android UI Design mini-book right
now!
With this book, you will delve into the fundamentals of Android UI design. You will
understand user input, views and layouts, as well as adapters and fragments.
Furthermore, you will learn how to add multimedia to an app and also leverage
themes and styles!

Email address:

1. Create a New Android Application Project

Open Eclipse IDE and go to File New Project Android Application Project.
Specify the name of the application, the project and the package. Then, choose in the Minimum
Required Sdk the API 11 or larger, because Android introduced fragments in Android 3.0
Honeycomb (API level 11). Finally, click Next.

In the next window, check the Create Activity option. The new activity will be the
main activity of your project. Then press Next button.

In Configure Launcher Icon window you should choose the icon you want to have
in your app. In our occasion, we will use the default icon of android, so just press
Next.

In the next window, select the Blank Activity option and press Next.

Specify a name for the new Activity and a name for the layout description of your
app. The .xml file for the layout will automatically be created in
the res/layout folder. Then press Finish

2. Create the layout of the Main Activity


For this example, we need two different Buttons. When a button is pressed, a fragment appears
below them. So we will create two different buttons within the main LinearLayout and a
fragment by using the <fragment> tag.
Open res/layout/activity_main.xml and go to the activity_main.xml tab. Then paste the
following code.
activity_main.xml:
01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment No.1"
android:onClick="selectFrag" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.2" />
<fragment
android:name="com.javacodegeeks.android.fragmentstest.FragmentOne"
android:id="@+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Please, notice the highlighted lines. When we add a <fragment> element in a layout, we have to
contain the android:name and android:id attributes. The android:name defines an object of a
Fragment Class, that we want to be instantiated and the android:id specifies the unique id of
that fragment.
We will use the FragmentOne as default.

3. Create the Fragments


We are going to make two different classes to define the fragments, that extends the Fragment
Class.
Right click on com.javacodegeeks.android.filtertstest package New Class.
To the opened window, specify the name for the new Class. We will name it FragmentOne and
we will put it in the same package as the MainActivity.java file.

Open src/com.javacodegeeks.android.filtertstest/FragmentOne.java and paste the


following.
FragmentOne.java:
package com.javacodegeeks.android.fragmentstest;
02
03
import android.app.Fragment;
04
import android.os.Build;
05
import android.os.Bundle;
06
import android.view.LayoutInflater;

07
08
09
10
11
12
13
14
15
16
17
18
19
20

import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}

With the same way, we create the second fragment.


Right click on com.javacodegeeks.android.filtertstest package New Class.
Specify the name for the new Class. We will name it FragmentTwo and we will put it in the same
package as the FragmentOne.java file.
Open src/com.javacodegeeks.android.filtertstest/FragmentTwo.java and paste the
following.
FragmentTwo.java:
package com.javacodegeeks.android.fragmentstest;
02
03
import android.app.Fragment;
04
import android.os.Build;
05
import android.os.Bundle;
06
import android.view.LayoutInflater;
07
import android.view.View;
08
import android.view.ViewGroup;
09
10
11
12
13
14
15
16
17
18
19
20
21

public class FragmentTwo extends Fragment{


@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_two, container, false);
}
}

As you can see in the code above, we use the onCreateView override method. It is
called by the Android system so that the fragment creates its user interface. Then,
it returns a View component which is placed in the <fragment> element of the layout.
Thats the reason we use the inflate method, in order to inflate a layout of an xml
file and to return its view.
4. Create the layouts of the Fragments

We are going to make a simple UI for each fragment layout, so we are going to create two
different xml files.
For FragmentOne we will create the fragment_one layout and for FragmentTwo the
fragment_two respectively.
Right click on res/layout folder New Android XML File and name the xml file. Choose
the LinearLayout as root element, as shown in the picture below, and then press Finish.

Home Android core app Fragment Android Fragments Example


About Katerina Zamani

Katerina has graduated from the Department of Informatics and


Telecommunications in National and Kapodistrian University of Athens (NKUA) and
she attends MSc courses in Advanced Information Systems at the same department.
Currently, her main academic interests focus on web applications, mobile
development, software engineering, databases and telecommunications.

Android Fragments Example

Posted by: Katerina Zamani in Fragment December 4th, 2013


A Fragment represents a portion of a user interface or an operation that runs within an
Activity.
A single activity can contain multiple fragments and many fragments can be reused in many,
different activities. It is not wrong if we say that a fragment is a type of sub-activity that can be
utilized again in multiple activities.
Although each fragment has each own lifecycle, it is connected with the Activity it belongs to,
so its lifecycle is directly influenced by the activitys lifecycle.
The main advantage of using fragments is due to the convenience of reusing the components in
different layouts. In this tutorial, we are going to create our own fragments, where each one will
be used when the user presses the appropriate button.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
1. JDK 1.7
2. Eclipse 4.2 Juno
3. Android SDK 4.4

Want to create a kick-ass Android App?


Subscribe to our newsletter and download the Android UI Design mini-book right
now!
With this book, you will delve into the fundamentals of Android UI design. You will
understand user input, views and layouts, as well as adapters and fragments.
Furthermore, you will learn how to add multimedia to an app and also leverage
themes and styles!

Email address:
1. Create a New Android Application Project

Open Eclipse IDE and go to File New Project Android Application Project.

Specify the name of the application, the project and the package. Then, choose in the Minimum
Required Sdk the API 11 or larger, because Android introduced fragments in Android 3.0
Honeycomb (API level 11). Finally, click Next.

In the next window, check the Create Activity option. The new activity will be the main
activity of your project. Then press Next button.

In Configure Launcher Icon window you should choose the icon you want to have in your app.
In our occasion, we will use the default icon of android, so just press Next.

In the next window, select the Blank Activity option and press Next.

Specify a name for the new Activity and a name for the layout description of your app. The .xml
file for the layout will automatically be created in the res/layout folder. Then press Finish.

In the image below you can see the final structure of the created project.

2. Create the layout of the Main Activity

For this example, we need two different Buttons. When a button is pressed, a fragment appears
below them. So we will create two different buttons within the main LinearLayout and a
fragment by using the <fragment> tag.
Open res/layout/activity_main.xml and go to the activity_main.xml tab. Then paste the
following code.
activity_main.xml:
01 <?xml version="1.0" encoding="utf-8"?>

02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03

android:layout_width="match_parent"

04

android:layout_height="match_parent"

05
06

android:orientation="vertical" >
<Button

07

android:id="@+id/button1"

08

android:layout_width="fill_parent"

09

android:layout_height="wrap_content"

10

android:text="Fragment No.1"

11

android:onClick="selectFrag" />

12
13
14

<Button
android:id="@+id/button2"

15

android:layout_width="fill_parent"

16

android:layout_height="wrap_content"

17

android:onClick="selectFrag"

18

android:text="Fragment No.2" />

19
20

<fragment

21

android:name="com.javacodegeeks.android.fragmentstest.FragmentOne"

22

android:id="@+id/fragment_place"

23

android:layout_width="match_parent"

24

android:layout_height="match_parent" />

25
26

</LinearLayout>

Please, notice the highlighted lines. When we add a <fragment> element in a layout, we have to
contain the android:name and android:id attributes. The android:name defines an object of a
Fragment Class, that we want to be instantiated and the android:id specifies the unique id of

that fragment.
We will use the FragmentOne as default.
3. Create the Fragments

We are going to make two different classes to define the fragments, that extends the Fragment
Class.
Right click on com.javacodegeeks.android.filtertstest package New Class.
To the opened window, specify the name for the new Class. We will name it FragmentOne and
we will put it in the same package as the MainActivity.java file.

Open src/com.javacodegeeks.android.filtertstest/FragmentOne.java and paste the


following.
FragmentOne.java:
01

package com.javacodegeeks.android.fragmentstest;

02
03

import android.app.Fragment;

04

import android.os.Build;

05

import android.os.Bundle;

06

import android.view.LayoutInflater;

07

import android.view.View;

08

import android.view.ViewGroup;

09
10

public class FragmentOne extends Fragment {

11

@Override

12

public View onCreateView(LayoutInflater inflater,

13

ViewGroup container, Bundle savedInstanceState) {

14
15

//Inflate the layout for this fragment

16
17

return inflater.inflate(

18

R.layout.fragment_one, container, false);

19

20

With the same way, we create the second fragment.


Right click on com.javacodegeeks.android.filtertstest package New Class.
Specify the name for the new Class. We will name it FragmentTwo and we will put it in the same
package as the FragmentOne.java file.
Open src/com.javacodegeeks.android.filtertstest/FragmentTwo.java and paste the
following.
FragmentTwo.java:
01

package com.javacodegeeks.android.fragmentstest;

02
03

import android.app.Fragment;

04

import android.os.Build;

05

import android.os.Bundle;

06

import android.view.LayoutInflater;

07

import android.view.View;

08

import android.view.ViewGroup;

09
10
11

public class FragmentTwo extends Fragment{

12
13

@Override
public View onCreateView(LayoutInflater inflater,

14

ViewGroup container, Bundle savedInstanceState) {

15
16

// Inflate the layout for this fragment

17
18

return inflater.inflate(

19
20

R.layout.fragment_two, container, false);


}

21

As you can see in the code above, we use the onCreateView override method. It is called by the
Android system so that the fragment creates its user interface. Then, it returns a View component
which is placed in the <fragment> element of the layout. Thats the reason we use the inflate
method, in order to inflate a layout of an xml file and to return its view.
4. Create the layouts of the Fragments

We are going to make a simple UI for each fragment layout, so we are going to create two
different xml files.
For FragmentOne we will create the fragment_one layout and for FragmentTwo the
fragment_two respectively.
Right click on res/layout folder New Android XML File and name the xml file. Choose
the LinearLayout as root element, as shown in the picture below, and then press Finish.

Open the res/layout/frament_one.xml file on the fragment_one.xml tab and paste the
following code.
fragment_one.xml:
<?xml version="1.0" encoding="utf-8"?>
02
<LinearLayout
03
xmlns:android="http://schemas.android.com/apk/res/android"
04
android:layout_width="match_parent"
05
android:layout_height="match_parent"
06
android:orientation="vertical"
07
android:background="#00ffff">
08
09
<TextView
10
android:id="@+id/textView1"

11
12
13
14
15
16
17

android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="This is fragment No.1"
android:textStyle="bold" />
</LinearLayout>

With the same way, we are going to make the layout for the second fragment.
Right click on res/layout folder New Android XML File and specify the name of the
xml file (fragment_two as we mentioned above). Choose the LinearLayout as root element and
then press Finish.
Open the res/layout/frament_two.xml file on the respective xml tab and paste the following
code.
fragment_two.xml:
<?xml version="1.0" encoding="utf-8"?>
02
<LinearLayout
03
xmlns:android="http://schemas.android.com/apk/res/android"
04
android:layout_width="match_parent"
05
android:layout_height="match_parent"
06
android:orientation="vertical"
07
android:background="#ffff00">
08
09
<TextView
10
android:id="@+id/textView2"
11
android:layout_width="match_parent"
12
android:layout_height="match_parent"
13
android:text="This is fragment No.2"
14
android:textStyle="bold" />
15
16
</LinearLayout>

Home Android core app Fragment Android Fragments Example


About Katerina Zamani

Katerina has graduated from the Department of Informatics and


Telecommunications in National and Kapodistrian University of Athens (NKUA) and
she attends MSc courses in Advanced Information Systems at the same department.

Currently, her main academic interests focus on web applications, mobile


development, software engineering, databases and telecommunications.

Android Fragments Example

Posted by: Katerina Zamani in Fragment December 4th, 2013


A Fragment represents a portion of a user interface or an operation that runs within an
Activity.
A single activity can contain multiple fragments and many fragments can be reused in many,
different activities. It is not wrong if we say that a fragment is a type of sub-activity that can be
utilized again in multiple activities.
Although each fragment has each own lifecycle, it is connected with the Activity it belongs to,
so its lifecycle is directly influenced by the activitys lifecycle.
The main advantage of using fragments is due to the convenience of reusing the components in
different layouts. In this tutorial, we are going to create our own fragments, where each one will
be used when the user presses the appropriate button.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
1. JDK 1.7
2. Eclipse 4.2 Juno
3. Android SDK 4.4

Want to create a kick-ass Android App?


Subscribe to our newsletter and download the Android UI Design mini-book right
now!
With this book, you will delve into the fundamentals of Android UI design. You will
understand user input, views and layouts, as well as adapters and fragments.
Furthermore, you will learn how to add multimedia to an app and also leverage
themes and styles!

Email address:
1. Create a New Android Application Project

Open Eclipse IDE and go to File New Project Android Application Project.
Specify the name of the application, the project and the package. Then, choose in the Minimum
Required Sdk the API 11 or larger, because Android introduced fragments in Android 3.0
Honeycomb (API level 11). Finally, click Next.

In the next window, check the Create Activity option. The new activity will be the main
activity of your project. Then press Next button.

In Configure Launcher Icon window you should choose the icon you want to have in your app.
In our occasion, we will use the default icon of android, so just press Next.

In the next window, select the Blank Activity option and press Next.

Specify a name for the new Activity and a name for the layout description of your app. The .xml
file for the layout will automatically be created in the res/layout folder. Then press Finish.

In the image below you can see the final structure of the created project.

2. Create the layout of the Main Activity

For this example, we need two different Buttons. When a button is pressed, a fragment appears
below them. So we will create two different buttons within the main LinearLayout and a
fragment by using the <fragment> tag.
Open res/layout/activity_main.xml and go to the activity_main.xml tab. Then paste the
following code.
activity_main.xml:
01 <?xml version="1.0" encoding="utf-8"?>

02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03

android:layout_width="match_parent"

04

android:layout_height="match_parent"

05
06

android:orientation="vertical" >
<Button

07

android:id="@+id/button1"

08

android:layout_width="fill_parent"

09

android:layout_height="wrap_content"

10

android:text="Fragment No.1"

11

android:onClick="selectFrag" />

12
13
14

<Button
android:id="@+id/button2"

15

android:layout_width="fill_parent"

16

android:layout_height="wrap_content"

17

android:onClick="selectFrag"

18

android:text="Fragment No.2" />

19
20

<fragment

21

android:name="com.javacodegeeks.android.fragmentstest.FragmentOne"

22

android:id="@+id/fragment_place"

23

android:layout_width="match_parent"

24

android:layout_height="match_parent" />

25
26

</LinearLayout>

Please, notice the highlighted lines. When we add a <fragment> element in a layout, we have to
contain the android:name and android:id attributes. The android:name defines an object of a
Fragment Class, that we want to be instantiated and the android:id specifies the unique id of

that fragment.
We will use the FragmentOne as default.
3. Create the Fragments

We are going to make two different classes to define the fragments, that extends the Fragment
Class.
Right click on com.javacodegeeks.android.filtertstest package New Class.
To the opened window, specify the name for the new Class. We will name it FragmentOne and
we will put it in the same package as the MainActivity.java file.

Open src/com.javacodegeeks.android.filtertstest/FragmentOne.java and paste the


following.
FragmentOne.java:
01

package com.javacodegeeks.android.fragmentstest;

02
03

import android.app.Fragment;

04

import android.os.Build;

05

import android.os.Bundle;

06

import android.view.LayoutInflater;

07

import android.view.View;

08

import android.view.ViewGroup;

09
10

public class FragmentOne extends Fragment {

11

@Override

12

public View onCreateView(LayoutInflater inflater,

13

ViewGroup container, Bundle savedInstanceState) {

14
15

//Inflate the layout for this fragment

16
17

return inflater.inflate(

18

R.layout.fragment_one, container, false);

19

20

With the same way, we create the second fragment.


Right click on com.javacodegeeks.android.filtertstest package New Class.
Specify the name for the new Class. We will name it FragmentTwo and we will put it in the same
package as the FragmentOne.java file.
Open src/com.javacodegeeks.android.filtertstest/FragmentTwo.java and paste the
following.
FragmentTwo.java:
01

package com.javacodegeeks.android.fragmentstest;

02
03

import android.app.Fragment;

04

import android.os.Build;

05

import android.os.Bundle;

06

import android.view.LayoutInflater;

07

import android.view.View;

08

import android.view.ViewGroup;

09
10
11

public class FragmentTwo extends Fragment{

12
13

@Override
public View onCreateView(LayoutInflater inflater,

14

ViewGroup container, Bundle savedInstanceState) {

15
16

// Inflate the layout for this fragment

17
18

return inflater.inflate(

19
20

R.layout.fragment_two, container, false);


}

21

As you can see in the code above, we use the onCreateView override method. It is called by the
Android system so that the fragment creates its user interface. Then, it returns a View component
which is placed in the <fragment> element of the layout. Thats the reason we use the inflate
method, in order to inflate a layout of an xml file and to return its view.
4. Create the layouts of the Fragments

We are going to make a simple UI for each fragment layout, so we are going to create two
different xml files.
For FragmentOne we will create the fragment_one layout and for FragmentTwo the
fragment_two respectively.
Right click on res/layout folder New Android XML File and name the xml file. Choose
the LinearLayout as root element, as shown in the picture below, and then press Finish.

Open the res/layout/frament_one.xml file on the fragment_one.xml tab and paste the
following code.
fragment_one.xml:
01

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

02

<LinearLayout

03

xmlns:android="http://schemas.android.com/apk/res/android"

04

android:layout_width="match_parent"

05

android:layout_height="match_parent"

06

android:orientation="vertical"

07

android:background="#00ffff">

08
09

<TextView

10

android:id="@+id/textView1"

11

android:layout_width="match_parent"

12

android:layout_height="match_parent"

13

android:layout_weight="1"

14

android:text="This is fragment No.1"

15

android:textStyle="bold" />

16
17

</LinearLayout>

With the same way, we are going to make the layout for the second fragment.
Right click on res/layout folder New Android XML File and specify the name of the
xml file (fragment_two as we mentioned above). Choose the LinearLayout as root element and
then press Finish.
Open the res/layout/frament_two.xml file on the respective xml tab and paste the following
code.
fragment_two.xml:
01

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

02

<LinearLayout

03

xmlns:android="http://schemas.android.com/apk/res/android"

04

android:layout_width="match_parent"

05

android:layout_height="match_parent"

06

android:orientation="vertical"

07

android:background="#ffff00">

08
09

<TextView

10

android:id="@+id/textView2"

11

android:layout_width="match_parent"

12

android:layout_height="match_parent"

13

android:text="This is fragment No.2"

14

android:textStyle="bold" />

15
16

</LinearLayout>

5. Code the Main Activity

In our example, we show the two buttons on the screen and when the appropriate button is
pressed, the respective fragment is displayed. By default, the layout of FragmentOne is shown, as
we declared it in the activity_main.xml file at the android:name attribute of the <fragment>
element.
Open src/com.javacodegeeks.android.filtertstest/MainActivity.java and paste the
following code.
MainActivity.java:
01

package com.javacodegeeks.android.fragmentstest;

import android.os.Bundle;
04
import android.view.View;
05
import android.app.Activity;
06
import android.app.Fragment;
07
import android.app.FragmentManager;
08
import android.app.FragmentTransaction;
09
10
11
12
13
14
15
16
17
18
19
20
21

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectFrag(View view) {
Fragment fr;

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}

6. Run the application

Now we are ready to run our application. To do this, right click on our project Run as
Android Application. The AVD will appear with the app loaded.
As we can see from the image below, there are two Buttons and FragmentOne is displayed. As
we already mentioned, that is happening because we put the FragmentOne Class at the
android:name attribute in the activity_main.xml file.

If we press the button Fragment No.1, the FragmentOne will return a View which is
placed in the <fragment> element of the layout. So the appearing screen seems like
the first picture.

Display notifications
A notification is a message you can display to the user outside of your
application's normal UI. When you tell the system to issue a notification, it first
appears as an icon in the notification area. To see the details of the notification, the
user opens the notification drawer. Both the notification area and the notification
drawer are system-controlled areas that the user can view at any time.
Android Toast class provides a handy way to show users alerts but problem is that
these alerts are not persistent which means alert flashes on the screen for a few
seconds and then disappears

To see the details of the notification, you will have to select the icon which will
display notification drawer having detail about the notification. While working with
emulator with virtual device, you will have to click and drag down the status bar to
expand it which will give you detail as follows. This will be just 64 dp tall and called
normal view.

Above expanded form can have a Big View which will have additional detail about the
notification. You can add upto six additional lines in the notification. The following screen shot
shows such notification.

Create and Send Notifications


You have simple way to create a notification. Follow the following steps in your application to
create a notification

Step 1 - Create Notification Builder


As a first step is to create a notification builder using NotificationCompat.Builder.build(). You
will use Notification Builder to set various Notification properties like its small and large icons,
title, priority etc.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

Step 2 - Setting Notification Properties


Once you have Builder object, you can set its Notification properties using Builder object as per
your requirement. But this is mandatory to set at least following

A small icon, set by setSmallIcon()

A title, set by setContentTitle()

Detail text, set by setContentText()

mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

You have plenty of optional properties which you can set for your notification. To learn more
about them, see the reference documentation for NotificationCompat.Builder.

Step 3 - Attach Actions


This is an optional part and required if you want to attach an action with the notification. An
action allows users to go directly from the notification to an Activity in your application, where
they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your
application. To associate the PendingIntent with a gesture, call the appropriate method of
NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the

notification text in the notification drawer, you add the PendingIntent by calling
setContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a
later time, without caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started
Activity. This ensures that navigating backward from the Activity leads out of your application to
the Home screen.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

Step 4 - Issue the notification


Finally, you pass the Notification object to the system by calling NotificationManager.notify() to
send your notification. Make sure you call NotificationCompat.Builder.build() method on
builder object before notifying it. This method combines all of the options that have been set and
return a new Notification object.
NotificationManager mNotificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());

The NotificationCompat.Builder Class


The NotificationCompat.Builder class allows easier control over all the flags, as well as help
constructing the typical notification layouts. Following are few important and most frequently
used methods available as a part of NotificationCompat.Builder class.
Sr.No.

Constants & Description


Notification build()

1
2

Combine all of the options that have been set and return a new Notification object.
NotificationCompat.Builder setAutoCancel (boolean autoCancel)
Setting this flag will make it so the notification is automatically canceled when the user

clicks it in the panel.


NotificationCompat.Builder setContent (RemoteViews views)
3

Supply a custom RemoteViews to use instead of the standard one.


NotificationCompat.Builder setContentInfo (CharSequence info)

Set the large text at the right-hand side of the notification.


NotificationCompat.Builder setContentIntent (PendingIntent intent)

Supply a PendingIntent to send when the notification is clicked.


NotificationCompat.Builder setContentText (CharSequence text)

Set the text (second row) of the notification, in a standard notification.


NotificationCompat.Builder setContentTitle (CharSequence title)

Set the text (first row) of the notification, in a standard notification.


NotificationCompat.Builder setDefaults (int defaults)

Set the default notification options that will be used.


NotificationCompat.Builder setLargeIcon (Bitmap icon)

Set the large icon that is shown in the ticker and notification.
NotificationCompat.Builder setNumber (int number)

10

Set the large number at the right-hand side of the notification.


NotificationCompat.Builder setOngoing (boolean ongoing)

11

Set whether this is an ongoing notification.


NotificationCompat.Builder setSmallIcon (int icon)

12
13

Set the small icon to use in the notification layouts.


NotificationCompat.Builder setStyle (NotificationCompat.Style style)

Add a rich notification style to be applied at build time.


NotificationCompat.Builder setTicker (CharSequence tickerText)
14

Set the text that is displayed in the status bar when the notification first arrives.
NotificationCompat.Builder setVibrate (long[] pattern)

15

Set the vibration pattern to use.


NotificationCompat.Builder setWhen (long when)

16

Set the time that the event occurred. Notifications in the panel are sorted by this time.

Example
Following example shows the functionality of a Android notification using a
NotificationCompat.Builder Class which has been introduced in Android 4.1.
Step
1
2
3
4
5
6
7

Description
You will use Android studio IDE to create an Android application and name it as
tutorialspoint under a package com.example.notificationdemo. While creating this project,
make sure you Target SDK and Compile With at the latest version of Android SDK to use
higher levels of APIs.
Modify src/MainActivity.java file and add the code to notify(""), if user click on the
button,it will call android notification service.
Create a new Java file src/NotificationView.java, which will be used to display new layout
as a part of new activity which will be started when user will click any of the notifications
Modify layout XML file res/layout/activity_main.xml to add Notification button in relative
layout.
Create a new layout XML file res/layout/notification.xml. This will be used as layout file
for new activity which will start when user will click any of the notifications.
No need to change default string constants. Android studio takes care of default string
constants
Run the application to launch Android emulator and verify the result of the changes done in
the application.

Following is the content of the modified main activity file


src/com.example.notificationdemo/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
package com.example.notificationdemo;

import
import
import
import
import
import
import
import
import
import

android.app.Notification;
android.app.NotificationManager;
android.app.PendingIntent;
android.content.Intent;
android.support.v7.app.ActionBarActivity;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.widget.Button;

public class MainActivity extends ActionBarActivity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Notify("You've received new message");
}
});
}
private void Notify(String notificationTitle, String notificationMessage){
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
@SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.abc,"New
Message", System.currentTimeMillis());
Intent notificationIntent = new Intent(this,NotificationView.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0,notificationIntent, 0);
notification.setLatestEventInfo(MainActivity.this,
notificationTitle,notificationMessage, pendingIntent);
notificationManager.notify(9999, notification);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);

Following will be the content of res/layout/notification.xml file:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="400dp"
android:text="Hi, Your Detailed notification view goes here...." />
</LinearLayout>

Following is the content of the modified main activity file


src/com.example.notificationdemo/NotificationView.java.
package com.example.notificationdemo;
import android.os.Bundle;
import android.app.Activity;
public class NotificationView extends Activity{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
}
}

Following will be the content of res/layout/activity_main.xml file


<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="MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:text="Notification Example"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Notification"
android:id="@+id/button"
android:layout_marginTop="62dp"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="action_settings">Settings</string>
<string name="app_name">tutorialspoint </string>
</resources>

Following is the default content of AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notificationdemo"
android:versionCode="1"
android:versionName="1.0" >
<application
android:allowBackup="true"

android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.notificationdemo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotificationView"
android:label="Details of notification"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
</application>
</manifest>

Let's try to run your tutorialspoint application. I assume you had created your AVD while doing
environment set-up. To run the APP from Android Studio, open one of your project's activity
files and click Run
icon from the toolbar. Android Studio installs the app on your AVD

and starts it and if everything is fine with your setup and application, it will display following
Emulator window

You might also like