0% found this document useful (0 votes)
113 views28 pages

Unit-5 Creating Interactive Menus and Actionbars

This document discusses creating interactive menus and action bars in Android. It describes the different types of menus including options menus, submenus, and context menus. It provides details on how to define and display options menus using XML menu resources and code. Context menus are created by registering views and inflating menu layouts. Submenus are created by nesting menu items. The document also includes an example of applying a context menu to items in a ListView.

Uploaded by

krupa522
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)
113 views28 pages

Unit-5 Creating Interactive Menus and Actionbars

This document discusses creating interactive menus and action bars in Android. It describes the different types of menus including options menus, submenus, and context menus. It provides details on how to define and display options menus using XML menu resources and code. Context menus are created by registering views and inflating menu layouts. Submenus are created by nesting menu items. The document also includes an example of applying a context menu to items in a ListView.

Uploaded by

krupa522
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/ 28

Unit-5

Unit-5
Creating Interactive Menus and ActionBars
Menus and Their Types:

 Menus display options in the form of menu items. Choosing a menu item results in the initiation of the
desired task.

 Android supports three types of menus:

1) Options menu

2) Submenu

3) Context menu

Options Menu:

 In an Options Menu, the menu items are displayed in the form of text, checkbox or radio buttons.

 Options menu also known as the Activity menu, the menu is displayed when a MENU button is clicked.

 There are two types of Options Menu:

1) Icon Menu:

 The Icon menu appears when the user presses the MENU button on the device.

 The Icon Menu shows the first six menu items of the menu in the form of large , finger friendly buttons
arranged in a grid at the bottom of the screen.

 The menu items in the Icon menu can display icons as well as text.

2) Expanded Menu:

 If the menu has more than six menu items, the first five items are displayed as an Icon Menu and the
sixth option appears as more button.

 By clicking the more button displays Expanded Menu that shows the scrollable list of the rest of the menu
items.

 The Expanded Menu can display menu items in the form of text, check box, or Radio buttons.

Dept. of C.S.E,C.B.I.T-PDTR Page 1


Unit-5

Creating an Options Menu:

 An Options Menu is the menu when the MENU button on the device is clicked.

 It shows menu items in the form of text, check boxes and radio buttons.

 An Options menu is defined through an XML file in the “res/menu” folder of the application.

 That is, the menu items of the Options Menu are defined in that XML file.

 The root node of this XML file should be <menu>

 The <item> tag can be used for adding the items to menu.

activity_menu_app.xml

<menu xmlns:android=“http://schemas.android.com/apk/res/android”>

<item android:id=“@+id/crt_db”

android:title=“Create Database”

android:icon=“@drawbale/one”/>

<item android:id=“@+id/inst_rw”

android:title=“Insert Rows”

android:icon=“@drawbale/two”/>

<item android:id=“@+id/lst_rw”

android:title=“List Rows” />

<item android:id=“@+id/srch_rw”

android:title=“search Rows” />

<item android:id=“@+id/dlt_rw”

android:title=“Delete Rows” />

<item android:id=“@+id/updt_rw”

android:title=“update Rows” />

</meu>

activity_menu_app.xml:

<LinearLayout

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

Dept. of C.S.E,C.B.I.T-PDTR Page 2


Unit-5

android:Orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/tv”/>

</LinearLayout>

MenuAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.MenuInflater;

import android.widget.TextView;

public class MenuAppActivity extends Activity

@Override

public void onCreate(Bundle savedInstanceState)

Super.onCreate(savedInstanceState) ;

setContentView(R.layout.activity_menu_app);

TextView selectedopt=(TextView)findViewById(R.id.tv);

Selectedopt.setText(“Please select Menu to display menu”);

@Override
Dept. of C.S.E,C.B.I.T-PDTR Page 3
Unit-5

public boolean onCreateOptionsMenu(Menu menu)

MenuInflater inflt=getManuInfalter();

inflt.inflate(R.menu.activity_menu_app, menu);

return true;

}}

 We use TextView for displaying an initial message.

 The onCreateOptionMenu() method of the activity is called when the user clicks the MENU button of the
device.

 To display our Icon menu, we need to inflate or merge our menu that we defined in the
activity_menu_app.xml file in the menu provided as a parameter to this method.

Adding Submenus:

 A submenu is collection of menu items invoked when a regular item is selected.

 Usually a submenu represents more detailed options for the selected menu item.

 A submenu is created by enclosing <item> nodes within the <menu> , where <item> nodes represent
the submenu options and the <menu> node act as root node for submenu.

EX: activity_menu_app.xml:

<menu xmlns:android=“http://schemas.android.com/apk/res/android”>

<item android:id=“@+id/crt_db”

android:title=“Create Database”

android:icon=“@drawbale/one”/>

<item android:id=“@+id/inst_rw”

android:title=“Insert Rows”

android:icon=“@drawbale/two”/>

<item android:id=“@+id/lst_rw”

android:title=“List Rows” />

Dept. of C.S.E,C.B.I.T-PDTR Page 4


Unit-5

<item android:id=“@+id/srch_rw”

android:title=“search Rows” >

<menu>

<group android:CheckableBehaviour=“single”>

<item android:id=“@+id/srch_cd”

android:title=“Search on code” />

<item android:id=“@+id/srch_nm”

android:title=“search by name” />

</group></menu>

</item>

<item android:id=“@+id/dlt_rw”

android:title=“Delete Rows” />

<item android:id=“@+id/updt_rw”

android:title=“update Rows” />

</menu>

Creating a Context Menu:

 A context menu appears as a floating window and is displayed when the user taps and holds on a widget ,
holds the middle D-pad button , or press the trackball.

 The difference between an options menu and a context menu is that the options menu is invoked when
the MENU button is pressed but context menu appears when we press and hold a view.

 An activity has multiple views each view can have its own context menu.

 An activity can have only a single options menu but many context menus.

 Context menus are removed from memory when closed.

Dept. of C.S.E,C.B.I.T-PDTR Page 5


Unit-5

For Example here I’m going to creating a menu.

Step-1: create a menu

mycontext_menu.xml

<menu xmlns:android=“http://schemas.android.com/apk/res/android”>

<item android:id=“@+id/cut_itm”

android:title=“Cut”/>

<item android:id=“@+id/cpy_itm”

android:title=“Copy”/>

<item android:id=“@+id/unst_itm”

android:title=“uninstall”/>

<item android:id=“@+id/rmv_itm”

android:title=“Remove”/></menu>

Step-2: Create a view

activity_menu_app.xml:

<LinearLayout

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

android:Orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:text=“ View to invoke Context menu”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/tv1”/>

<TextView

android:layout_width=“match_parent”
Dept. of C.S.E,C.B.I.T-PDTR Page 6
Unit-5

android:layout_height=“wrap_content”

android:id=“@+id/tv2”/>

</LinearLayout>

Step-3:

a) Link the context menu with the view. By using registerForContextMenu() method we can do that.

@Override

public void onCreate(Bundle savedInstanceState)

super. onCreate(savedInstanceState);

setContentView(R.layout.activity_menu_app);

TextView selectedopt=(TextView)findViewById(R.id.tv2);

selectedopt.setText(“Please select MENU button to display menu ”);

TextView contxtvw=(TextView)findViewById(R.id.tv1);

registerForContextMenu(contxtvw);

b) To display the context menu we need to override the onCreateContextMenu() method.

@Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)

super.onCreateContextMenu(menu , v, menuInfo);

if(v.getId()==R.id.tv2)

MenuInflater inflater=getMenuInflater();

inflater.inflate(R.menu.mycontext_menu , menu);

menu.setHeaderTitle(“Sample Context menu”);


Dept. of C.S.E,C.B.I.T-PDTR Page 7
Unit-5

menu.setHeaderIcon(“R.drawable.one”);

 The menu parameter receives items for contextmenu

 view parameter receives view for that contextmenu.

 ContextMenuInfo act as adapter for passing any other information about menu inflation.

Applying a Context Menu to a ListView:

 To apply context menus to ListView control let’s create a new android application called
ContextMenuApp.

 Lets add Context menu files first to menu folder.

mycontext_menu1.xml:

<menu xmlns:android=“http://schemas.android.com/apk/res/android”>

<item android:id=“@+id/cut_itm”

android:title=“Cut”/>

<item android:id=“@+id/cpy_itm”

android:title=“Copy”/></menu>

mycontext_menu2.xml:

<menu xmlns:android=“http://schemas.android.com/apk/res/android”>

<item android:id=“@+id/opn_itm”

android:title=“Open”/>

<item android:id=“@+id/cls_itm”

android:title=“Close”/></menu>

 We want to display TextView and ListView in our application.

 The TextView directs the user to take desired action and tells the user which item from the listview is
selected by user.

 The ListView control used to display different items on the screen, which the user tap and hold to invoke
the related ContextMenu.
Dept. of C.S.E,C.B.I.T-PDTR Page 8
Unit-5

activity_context_menu_app.xml:

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

android:Orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/tv”/>

<ListView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/lstvw”/>

</LinearLayout>

To add an action we need to create the activity file.

ContextMenuAppActivity.java

import android.app.Activity;

import android.os.Bundle;

import android.view.ContextMenu;

import android.view.MenuItem;

import android.view.MenuInflater;

import android.widget.TextView;

import android.view.ContextMenu.ContextMenuInfo;

import android.view.View;

import android.ListView;
Dept. of C.S.E,C.B.I.T-PDTR Page 9
Unit-5

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

public class ContextMneuAppActivity extends Activity

@Override

public void onCreate(Bundle savedInstanceState)

Super.onCreate(savedInstanceState);

setContentView(R.layout.activity_context_menu_app);

final String[] fruits={“Apple”,”Mango”,”Banana”,”Orange”,”Grapes”};

final TextView selectdOpt=(TextView)findViewById(R.id.txtv);

ListView mylstvw=(ListView)findViewById(R.id.lstvw);

selectedOpt.setText(“Tap and hold a menu item to display a context menu”);

final ArrayAdapter<String> arrayadpt=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruits);

mylistvw.setAdapter(arrayAdpt);

registerForContextMenu(Mylstvw);

@Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)

super.onCreateContextMenu(menu , v, menuInfo);

if(v.getId()==R.id.lstvw);

AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo)menuinfo;

if(fruits[info.position]==“Apple”)

{
Dept. of C.S.E,C.B.I.T-PDTR Page 10
Unit-5

menu.setHeaderTitle(fruits[info.position]);

MenuInflater inflater=getMenuInflater();

inflater.inflate(R.menu.mycontext_menu1,menu)

};

if(fruits[info.position]==“Mango”)

menu.setHeaderTitle(fruits[info.position]);

MenuInflater inflater=getMenuInflater();

inflater.inflate(R.menu.mycontext_menu2,menu);

Using ActionBar:

 The ActionBar is a widget that replaces the title bar at the top of every Activity displaying

 By default the ActionBar includes the application logo on the left side, followed by Activity title, and
menu items on the right side.

 The actionbar is commonly used to provide a quick link to an applicants home.

 The ActionBar provides the following features:

a) Customizes the title bar of an Activity.

b) Follows its own life cycle.

c) Consistently displays frequent used actions of an application.

d) We also can able to display Action Views.

 There are 3 types of ActionBars. Those are:

1) Standard ActionBar

2) Tabbed ActionBar

3) List ActionBar

Dept. of C.S.E,C.B.I.T-PDTR Page 11


Unit-5

 By using the following code we can enable(display) the action bar.

ActionBar ab=getActionBar();

ab.show(); --- displays the actionbar

ab.hide(); --- hides the actionbar

 To display action items of ActionBar we need to use the attribute called ShowAsAction. For this attribute
we can able to pass 3 values. Those are:

1) always: If we specify this values it makes the action item to appear on the ActionBar.

2) ifRoom: If we specify this values it makes the action item to appear only when there is Room
(space)available.

3) never: If we specify this values it makes the action item to appear in the Overflow menu.

4) Let’s create one application with actionbar.

activity_demo_action_bar.xml

<LinearLayout

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

android:Orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:text=“This is demo actionBar”

android:id=“@+id/tv”/>

</LinearLayout>

DemoActionBarActivity.java

import abdroid.app.ActionBar;

Dept. of C.S.E,C.B.I.T-PDTR Page 12


Unit-5

import abdroid.app.Activity;

import abdroid.Content.Intent;

import abdroid.os.Bundle;

import abdroid.view.MenuItem;

public class DemoActionBarActivity extends Activity

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_demo_action_bar);

ActionBar ab=getActionBar();

ab.display();

ab.setHomeButtonEnabled(true); /* this method is to make icon clickable*/

Creating a Tabbed ActionBar:

 Tabbed ActionBars display menu items in the form of tabs.

 In this type of ActionBars there is only one type of navigation can be enabled at a time.

 To achieve navigation between tabs we need to use the method

setNavigationMode(ActionBar.NAVIGATION_MODE_TABS)

 After we determine the navigation mode, we add the tabs to the actionbar by calling addTab() method.

actionBar.addTab(actionBar.newTab().setText(“name od the tab”).setTabListener(this));

Along with this we can also call

1) setContentDescription() : To supply more information regarding tab.

2) setIcon(): To define an image for the tab.


Dept. of C.S.E,C.B.I.T-PDTR Page 13
Unit-5

3) Lets create an TabbedActionBarApp.

activity_demo_action_bar.xml

<LinearLayout

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

android:Orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:text=“This is demo of Tabbed actionBar”

android:id=“@+id/tv”/>

</LinearLayout>

DemoTabbedActionBarActivity.java

import abdroid.app.ActionBar.Tab;

import abdroid.app.Activity;

import abdroid.os.Bundle;

public class DemoTabbedActionBarActivity extends Activity

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_demo_action_bar);

ActionBar ab=getActionBar();

ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Dept. of C.S.E,C.B.I.T-PDTR Page 14
Unit-5

ab.addTab(actionBar.newTab().setText(“Create”).setTabListener(this));

ab.addTab(actionBar.newTab().setText(“Update”).setTabListener(this));

ab.addTab(actionBar.newTab().setText(“Delete”).setTabListener(this));

Creating a Drop-Down List ActionBar:

 In a drop-down list ActionBar, the menu items are displayed in the form of a drop-down list.

 It is popularly used for displaying the content within an Activity on the basis of the selection made by
user.

 To display a drop-down list in an ActionBar, its setNavigationMode() method is called by passing the
value ActionBar.NAVIGATION_MODE_LIST as a parameter.

 The drop-down list appears like a spinner, displaying a list of available options, allowing us to select one
of them.

 For displaying list of items we need to implement ARRAYADAPTER

 To assign the ArrayAdapter to the ActionBar and to attach the event listener to the drop-down items that
are displayed, the setListNAvigationCallbacks() method is called.

The below shown code can be used for Creating a Drop-down list ActionBar:

String[ ] items={“Create” , ”Insert” ,”Update” ,”Search”};

final ArrayAdapter<String> arrayadpt=new ArrayAdapter<String> (this,


android.R.layout.simple_spinner_dropdown_item, Items);

ActionBar ab=getActionBar();

ab.setNavigationMode(ab.NAVIGATION_MODE_LIST);

ab.setListNavigationCallbacks(arrayadpt, onNavigationItemSelected);

 In the above code items is defined , consisting of the Strings that we want to display in the drop-down
List ActionBar.

 An ArrayAdapter called arrayadpt is created for comprising the string array items to spinner.

Dept. of C.S.E,C.B.I.T-PDTR Page 15


Unit-5

 An ActionBar object ab is created and its navigation mode is set to ab.NAVIGATION_MODE_LIST for
getting the navigation between items.

 setListNavigationCallbacks() method is called on the ActionBar for passing the ArrayAdapter and
eventListener .

Using Databases:

 User entered Data needs to be saved somewhere so that it can be accessed at a later time.

 Android offers the SQLite relational database library for data management.

 SQLite is an open source , lightweight, and powerful database available in the form of a C library.

 It uses SQL(structured Query Language) for storing and retrieving information and performing database
maintenance.

Using the SQLiteOpenHelper Class:

 Android databases are stored in the /data/data/<package-name>/database folder on devices or


emulators.

 To create an Android application that stores, accesses, and manipulates user information we need to use
SQLiteOpenHelper class.

 This is an abstract class that used to create ,open , and update database.

 It provides methods like getWritableDatabase(), getReadableDatabase(), and close() methods which


used for reading, writing, and closing database.

 SQLiteDatabase class also provides methods including insert(), and query() which are used for inserting
rows in table and to execute different SQLite queries .

Creating a Data Entry Form:

activity_database_app.xml

<LinearLayout

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

android:Orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<TextView

Dept. of C.S.E,C.B.I.T-PDTR Page 16


Unit-5

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/response”/>

<TextView

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/prodrec”/>

<TableLayout

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/add_tab”>

<TableRow>

<TextView

android:text= “Product code:”/>

<EditText

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/prod_code”/>

</TableRow>

<TableRow>

<TextView

android:text= “Product Name:”/>

<EditText

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/prod_name”/>
Dept. of C.S.E,C.B.I.T-PDTR Page 17
Unit-5

</TableRow>

<TableRow>

<TextView

android:text= “Product Price:”/>

<EditText

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/prod_price”/>

</TableRow>

<TableRow>

<Button

android:text=“Add Product”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/add_button”/>

<Button

android:text=“Cancel”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:id=“@+id/canel_button”/>

</TableRow></TableLayout></LinearLayout>

DatabaseManager.java

import android.database.sqlite.SQLiteDatabase;

import android.database.Cursor;

import android.database.sqlite.SQLiteOpenHelper;
Dept. of C.S.E,C.B.I.T-PDTR Page 18
Unit-5

import android.content.Content;

import androi.content.ContentValues.

import android.util.log;

public class DatabaseManager

public static final String DB_NAME= “shopping”;

public static final string DB_TABLE=“products”;

public static final int DB_VERSION=1;

private static final string CREATE_TABLE= “CREATE TABLE”+DB_TABLE+(code INTEGER PRIMARY KEY,
product_name TEXT, price FLOAT);”;

private SQLHelper helper;

private SQLiteDatabase db;

private Context context;

public DatabaseManager(Context c)

this.context=c;

helper=new SQLHelper(c);

this.db= helper.getWritableDatabase();

public DatabaseManager openReadable()

helper=new SQLHelper(context);

db=helper.getReadableDatabase();

return this;

public void close()

Dept. of C.S.E,C.B.I.T-PDTR Page 19


Unit-5

helper.close();

public boolean addRow(int c, String n, float p)

ContentValues newprod=new ContentValues();

newprod.put(“code”,c);

newprod.put(“product_name”,n);

newprod.put(“price”,p);

try

db.insert(DB_TABLE, null, newprod);

catch(Exception e)

Log.e(“Error in inserting rows”,e.tostring());

return false;

db.close();

return true;

public String retriveRows()

String [ ] columns=new String[ ] {“code”,”Product_name”,”price”};

Cursor cu=db.query(DB_TABLE, columns);

}
Dept. of C.S.E,C.B.I.T-PDTR Page 20
Unit-5

public class SQLHelper extends SQLiteOpenHelper

public SQLHelper(Context c);

super(c,DB_NAME,DB_VERSION);

@Override

public void onCreate(SQLiteDatabase db)

db.execSQL(CREATE_TABLE);

Understanding Broadcast Receivers:

 All three communication mediums- SMS , email and voice calls –use the concept of Broadcast Receivers.

 BroadCast receiver is a component that responds to different messages that are broadcast by the system
or other applications.

 Messages like download complete, battery low, image captured, require attention.

 Such messages are broadcast as an Intent , intent is an object that is waiting for broadcast receivers to
respond and such broadcasted intents and take the necessary actions.

 There are two aspects of broadcast receivers:

1) Broadcasting an Intent

2) Receiving the broadcast Intent.

Broadcasting an Intent:

 To broadcast an Intent, we first create an Intent object and assign a specific action to it.

 If you want to put additional data we can use putExtra().

Dept. of C.S.E,C.B.I.T-PDTR Page 21


Unit-5

• he following code broadcast an intent:

public static String BROADCAST_STRING=“com.android.testingBroadCast”;

Intent broadint=new Intent();

broadint.putExtra(“message”,”New e-mail arrived”);

broadint.setAction(BROADCAST_STRING);

sendBroadcast(broadint);

Receive the Broadcast Intent:

 A broadcast receiver is a class that extends the BroadcastReceiver.

 It also needs to be registered as a receiver in an Android application via AndroidManifest.xml or through


code at runtime.

 The broadcast receiver class needs to implement the onReceive() method.

public void onReceive(Context cont,Intent inte)

String actionName=inte.getAction();

if(actionName != null && actionName.equals(“com.android.testingBroadcast))

String msg=inte.getStringExtra(“message”);

}}

Using Notification system:

 The android notification system provides us with several ways of alerting users.

 Notifications are usually displayed on the status bar at the top of the screen.

Dept. of C.S.E,C.B.I.T-PDTR Page 22


Unit-5

Notification via the Status Bar:

 The simplest type of notification is status, which appears in the status bar as an icon along with some
optional ticker text.

 Users can pull down the status bar to see the notification list and clear the notification by clicking the
Clear button.

 After tapping the notification, the user navigates to the Intent defined by the notification.

 For creating notifications, the following two classes are used:

1) Notification:

The object that defines the information to be displayed, which can be text to be displayed on thestatus/expended
status bar and an icon , and the no of times the notification triggered and so on.

2) NotificationManager:

The base object with which notifications are handled. It displays the information encapsulated in the Notification
object, which is displayed via the notify() method.

The following code represent how to create notification:

Notification notif=new Notification();

notif.icon=R.drawable.one;

notif.ticketText=“There is a new notification”;

notif.when=System.CurrentTimeMillis();

notif.flags |=Notification.FLAG_AUTO_CANCEL;

 icon: Assigns the notification icon

 tickerText: Assigns the small notification text.

 when: Assigns the time when the notification occurred.

 flag: Assigns the constant that determines the subsequent action when the notification is selected from
the notification window.

We can also assign a notification icon , ticker text, and time of occurrence through the Notification object
constructor, as shown below:

Dept. of C.S.E,C.B.I.T-PDTR Page 23


Unit-5

Notification notif=new Notification(“R.drawable.one”,”There is a new notification”, system.CurrentTimeMillis());

Sending SMS Message with Java Code:

 To implement the SMS Messaging facility in our application, Android provides a built-in class known as
SmsManager , which we use to send and receive SMS messages.

 To send and receive SMS messages in an application we need to use permissions first. All the permissions
were define under AndroidManifest.xml

 We need to write the below lines for sending and receiving SMS.

For sending:

<uses-permission android:name=“android.permission.SEND_SMS”/>

For Receiving:

<uses-permission android.name=“android.permission.RECEIVE_SMS”/>

For receving sms along with the above permissions we need to write the below code in Manifest.xml

<receiver android:name=“.ReceiverSMS”>

<intent-filter>

<action android:name=“android.provider.Telephony.SMS_RECEIVED”/>

</intent-filter>

</receiver>

 To send an sms messgae with java code we use the SmsManager class. And then we can access the
sendTextMessage() method of that class as shown below:

SmsManager sms=SmsManager.getDefault();

sms.sendTextMessage(receipent_phoneno, service_centadd, sms_msg,


sent_intent, delivery_intent);

1) receipent_phoneno: represent the phone number of receiver

2) Service_centadd: represent the Service center address. we use value null for default

3) sms_msg: the text message what we want to send.

4) sent_intent: is the pending Intent to invoke when the message is sent.

Dept. of C.S.E,C.B.I.T-PDTR Page 24


Unit-5

5) delivery_intent: is the pending intent to invoke when the message delivered.

 We also can create and register two BraodcastReceivers, which listen for Intents that match sent and
delivered as shown by the following code:

registerReceiver(sentReceiver, new IntentFilter(SENT));

registerReceiver(deliveredReceiver, new IntentFilter(DELIVERED));

 For Receiving sms we need to write the following code in java program:

 First we need to give permission from the manifest file by using the below code:

<uses-permission android:name=“android.permission.RECEIVE_SMS”/>

 To listen incoming messages we need to register our Broadcast Receiver class using an Intent filter by
using the following code in manifest file :

<receiver android:name=“.ReceiverSMS”>

<intent-filter>

<action android:name=“android.provider.Telephony.SMS_RECEIVED”/>

</intent-filter> </receiver>

 In java program we can use the below methods for code for Receiving the sms:

1) getOriginatingAddress(): Gives the phone number of the SMS Recipient

2) getTimestampMillis(): Gives the time at which the SMS is received.

3) getMessageBody(): Gives the message body.

public void onReceive(context conte,Intent inte)

Bundle bund=inte.getExtras();

SmsMessage[ ] msg=null;

if(bund!=null)

Object[ ] pdus=(Object[ ])bundle.get(“pdus”);

Dept. of C.S.E,C.B.I.T-PDTR Page 25


Unit-5

msg=new SmsMessage[pdus.length];

for(int i=0; i<msg.length;i++)

msg[i]=SmsMessage.createFromPdu((byte[ ])pdus[i]);

Str +=“SMS Received from:”+msg[i].getOriginatingAddress();

Str+=msg[i].getMessageBody().toString();

}}

 The information exists in the bundle in the form of an array of SMS PDUs.

 PDU stands for Protocol Data Unit and is used to encapsulate the SMS message.

 The array of SMS PDUs is thereafter converted into an array of SmsMessage objects.

 To convert each PDU byte array into an SMS Message object, the SmsMessage.createFromPdu() method
is called.

Sending e-mail:

 To send an e-mail with Android, we need to use the following Intent:

Intent.ACTION_SEND

 This intent calls an existing email account to send an email.

 First we need to configure the email account. For that follow the below steps:

1) Start the emulator and then click on the Menu button.

2) Click on System settings option

3) Then go to Accounts section, and click on Add account button.

4) And give the required details.

 Once the e-mail account configured then by using ACTION_SEND we can send messages.

 Then we need to set the type of data what we are sending for that:

emailIntent.setType(“plain/text”)

 Then we call startActivity() with the CreateChooser() method. This one allows the user to handle the
Intent by selecting the application as shown below:

Dept. of C.S.E,C.B.I.T-PDTR Page 26


Unit-5

startActivity(Intent.createChooser(emailIntent, “sending e-mail”));

 To supply data for the email message fields, we set certain standard extras for the Intent. like:

1) EXTRA_EMAIL: sets the To address

2) EXTRA_cc: sets the Cc: address

3) EXTRA_BCC- Sets the Bcc: address

4) EXTRA_SUBJECT- Sets the subject of the email.

5) EXTRA_TEXT- Sets the body of the email.

 After setting up the all Intent’s extras, launch the activity to initiate the sending email task.

Working with Telephony Manager:

 The android telephony APIs include the Telephony Manager that access the telephony services on the
device and enables us to

1) Provide a user interface for entering or modifying the phone number to dial.

2) Implement call handling in the application

3) Register and monitor telephony state changes

4) Get subscriber information

Making the Outgoing Call:

 The simplest way to make an outgoing call is to invoke the Dialer application by using the
Intent.ACTION_CALL action.

 The below code performs the same:

Intent callintent=new Intent(Intent.ACTION_CALL);

callIntent.setData(uri.parse(“tel:1111122222”));

startActivity(callIntent);

 The above code initiates a phone call to 1111122222 using the system in-call Activity.

 For making phone call we need to give permission to invoke the Dailer application. For that in Manifest
file we need to write the below code:

<uses-permission android:name=“android.permission.CALL_PHONE”/>

Dept. of C.S.E,C.B.I.T-PDTR Page 27


Unit-5

Listening for Phone state changes:

 A Phone is having states like: idle, ringing , off-hook,

 To see these states we need to use a broadcast receiver called

android.intent.action.PHONE-STATE

 There we implement a PhoneStateListener and listen() method of TelephonyManager to receive


notification whenever there is a change in phone state.

 The phone state is represented by the constants shown here:

1) CALL_STATE_IDLE: The phone is an idle state.

2) CALL-STATE-RINGING: A phone call has arrived.

3) CALL_STATE_OFFHOOK: The phone is off-hook.

 To access phone state information we need to get permissions for that we need to write the below code
in manifest file:

<uses-permission android:name=“android.permission.READ_PHONE_STATE”/>

Dept. of C.S.E,C.B.I.T-PDTR Page 28

You might also like