0% found this document useful (0 votes)
20 views35 pages

I3350 - Chapter 7-8 - en

1. Android supports 3 types of menus: option menus, context menus, and popup menus. 2. Menus can be declared in XML files and inflated in Java code. The XML declaration contains items and attributes like title, icon, and order. 3. In Java, menus are inflated from XML and displayed. When an item is selected, the onOptionsItemSelected method indicates which item was chosen so the appropriate action can be performed.

Uploaded by

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

I3350 - Chapter 7-8 - en

1. Android supports 3 types of menus: option menus, context menus, and popup menus. 2. Menus can be declared in XML files and inflated in Java code. The XML declaration contains items and attributes like title, icon, and order. 3. In Java, menus are inflated from XML and displayed. When an item is selected, the onOptionsItemSelected method indicates which item was chosen so the appropriate action can be performed.

Uploaded by

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

I3350

Chapter 7

The menus

171

1. Introduction
Android supports 3 types of menu
• Option menu
• Context menu
• Popup menu

An option menu opens


• when the Menu key is pressed
A context menu opens
• when we press a Widget for a long time
A popup menu opens
• when we press a Widget

Menus can be made


• by Java programming only
• or by declaration in an XML file and Java (preferred method) 172

Dr. Ziad EL BALAA 1


I3350

1. Introduction
The menus are declared
• in an XML file located in res/menu
Create a file for each type of menu
Example: option.xml or context.xml

The XML file is as follows:


• the root menu contains the tag
– item for a menu item
• the item tag contains menu (for a submenu)
– 2 levels maximum

173

1. Introduction
The main attributes of the tag item
• title: the item's title
• icon: a reference to a drawable to use as the item's icon
• orderInCategory: re-order the menu items
– by default, the order in the XML file
– to change the order, define its value (begin by 0)
• enable: to enable or disable items
– by default the item is enable
– inactive items appear in the menu but can’t be selected
• visible: to show or hide the items

174

Dr. Ziad EL BALAA 2


I3350

1. Introduction
Example of a menu declaration: res/menu/option.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/add"
android:title="Add" />
<item android:id="@+id/reset"
android:title="Reset">
<menu>
<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
</menu>
</item>
</menu>

175

1. Introduction
Example of a menu declaration: res/menu/context.xml

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


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/rename"
android:title=“Rename" />
<item android:id="@+id/remove"
android:title="Remove" />
</menu>

176

Dr. Ziad EL BALAA 3


I3350

1. Introduction
In Java:

Add the imports


• import android.view.Menu;
• import android.view.MenuInflater;
• import android.view.MenuItem;
• import android.view.ContextMenu;

177

1. Introduction
It is necessary to transform the XML file in the instance of Menu
• use the method getMenuInflater
Menu menu = new Menu();
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);

menu: the name of the file that is in the menu directory


Example: R.menu.option (res/menu/option.xml)
ou R.menu.context (res/menu/context.xml)

MenuInflater provides
– the menu items of the resource (ex: R.menu.option)
– to the object Menu or ContextMenu passed as a parameter
178

Dr. Ziad EL BALAA 4


I3350

1.1- Option menu


The option menu is created by
• the method onCreateOptionsMenu

This method must


• contain the instance of Menu
• return true to allow the display of the menu

public boolean onCreateOptionsMenu(Menu menu) {


MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}

179

1.1- Option menu


To know which item was selected, we use
• onOptionsItemSelected with the parameter MenuItem item

We can use
• the switch() function with the identifier of menu item.getItemId()
• to execute an action on the selected item

This method
• Returns true if the action is done, false otherwise

180

Dr. Ziad EL BALAA 5


I3350

1.1- Option menu


N.B: onOptionsItemSelected contains all options of the basic menu
and of the submenu
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
// do something
return(true);

case R.id.reset:
// do something
return(true);

case R.id.item1:
// do something
return(true);

case R.id.item2:
// do something
return(true);
}

return(super.onOptionsItemSelected(item));
}
181

1.2- Context menu


To link the context menu to a widget or to a list
• we must call the method registerForContextMenu after
setContentView

This method has a parameter


• a widget (an object View)
• or a list (ListView, GridView)

If the class is extends Activity:


• we must define the widget by findViewByID or by an AdapterList
If the class is extends ListActivity:
• simply use the method getListView()
182

Dr. Ziad EL BALAA 6


I3350

1.2- Context menu


Example:
public class MenuContextuelActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View v = findViewById(R.id.layout);
registerForContextMenu(v);
}
}

or
public class MenuContextuelActivity extends ListActivity {
private static final String[] items={“item1”, “item2”, … }
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
….
registerForContextMenu(getListView());
}
} 183

1.2- Context menu


The Context menu is created by
• the method onCreateContextMenu

This method has the following parameters:


• the ContextMenu menu
• View v: The View for which the context menu is being built
• the object ContextMenu.ContextMenuInfo menuInfo extra
information about the item for which the context menu should
be shown
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
new MenuInflater(this).inflate(R.menu.context, menu);}

184

Dr. Ziad EL BALAA 7


I3350

1.2- Context menu


We can link the Context menu to several different widgets
public class MenuContextuelActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) findViewById(R.id.text1);
textView2 = (TextView) findViewById(R.id.text2);
registerForContextMenu(textView1 );
registerForContextMenu(textView2 );
}

public void onCreateContextMenu(ContextMenu menu, View v,


ContextMenu.ContextMenuInfo menuInfo) {

new MenuInflater(this).inflate(R.menu.context, menu);


}

} 185

1.2- Context menu


We can link several widgets to the different Context menu
public class MenuContextuelActivity extends Activity {
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView) findViewById(R.id.text1);
textView2 = (TextView) findViewById(R.id.text2);
registerForContextMenu(textView1 );
registerForContextMenu(textView2 );
}

public void onCreateContextMenu(ContextMenu menu, View v,


ContextMenu.ContextMenuInfo menuInfo) {
if(v.equals(textView1)==true) {
new MenuInflater(this).inflate(R.menu.context1, menu);}
if(v.equals(textView2)==true) {
new MenuInflater(this).inflate(R.menu.context2, menu);}
}
186

Dr. Ziad EL BALAA 8


I3350

Chapter 8

Activities - Intent

187

1. Introduction
An application = set of activities
An activity = a screen

When an application is launched, it is placed at the top


• of what is called the stack of activities  summit
A stack is a "LIFO" data structure
• it is possible to have access to only one element of the stack

188

Dr. Ziad EL BALAA 9


I3350

1. Introduction
Example:
When a call arrives
• it is placed at the top of the stack
• and it is it that is displayed in place of the application, which
becomes in second place

The activity will return at the end of the call

Principle
• we can only have one visible application on the terminal
• and what is visible is the graphical interface of the activity that
is at the top of the stack
189

1. Introduction
Android has a particular system:
• Anytime an application can leave place for another application
– that has a higher priority
• If an application uses too much system resources, then it will
prevent the system from working properly
– Android will stop it without warning
• An activity will exist in several states during his life
– for example an active state when used
– and a pause state when we receive a call

190

Dr. Ziad EL BALAA 10


I3350

1. Introduction
In the AndroidManifest.xml file
• The activity is declared by the Activity element child of the application
element

Activity contains the following attributes:


• name: specify the class of the activity
• label: name of the activity, if not specified the label of the application is used
• icon: icon of the activity, if not specified the icon of the application is used
• etc.

<activity
android:name=".HelloActivity"
android:label="@string/app_name">
</activity>

191

1. Introduction
Example of AndroidManifest.xml file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.antislashn.android.activity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" > activity called first
<activity
android:label="@string/app_name"
android:name=".AppelactivityActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity> activity can only be called by an explicit
<activity Intent
android:label="explicit"
android:name=".ExplicitActivity" >
</activity>
</application>
</manifest>

192

Dr. Ziad EL BALAA 11


I3350

1. Introduction
An application contains several independent activities
One of these activities is launched automatically
• when the user launches the application  Launcher

Other activities should be accessible


 navigate between them

There is a mechanism that allows


• to execute these actions
• and send messages
– between applications
– or inside the same application
193
This mechanism of exchange is called intent

1. Introduction
An intent is a message sent to Android
• To tell him « I want you to do … something »

This « something » depends on the situation


• sometimes we know what it is (open one of the activities)
 the explicit intents
• but at other times we don’t know
 the implicit intents

194

Dr. Ziad EL BALAA 12


I3350

2. Explicit Intents
The explicit intents are used in the same application

In the explicit intents


• the component to be activated is designated by its name

Example:
• in the folder src, create a 2nd activity "Child1.java"
import android.app.Activity;
import android.os.Bundle;

public class Child1 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
195
}

2. Explicit Intents
This activity must be declared in the AndroidManifest.xml file

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

<application android:icon="@drawable/cw"
android:label="@string/app_name">

<activity android:label="@string/app_name"
android:name=".Principale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity android:name=".Child1" />

</application>
</manifest>

196

Dr. Ziad EL BALAA 13


I3350

2. Explicit Intents
To call the activity "Child1" from the activity "Principale"
• we will create an instance of an object of type "Intent"
new Intent (this, Child1.class);

This instruction indicates that you want to launch Child1

Its parameters are:


• the place where the intent is created (the current instance, ie "this")
• The destination of the "intent" object, the activity "Child1.class"

As the intent is a kind of messenger, to which we give


• the sender's address ("this")
• and the recipient’s address ("Child1.class")

We need a method to "send" the messenger to its destination 197

2. Explicit Intents
2 choices are possible:

1. The method startActivity() with parameter the intent


• Android searches for the corresponding activity and passes the intent on
it to process it
• The activity "parent" isn’t notified of the end of the activity "child"

2. The method startActivityForResult() with parameters the intent and an


identifier (unique for the calling activity)
• Android searches for the corresponding activity and passes the intent
• Activity is notified of the end of the activity "child" by the method
OnActivityResult()

198

Dr. Ziad EL BALAA 14


I3350

2.1- startActivity()
In the Principale.java file
import android.app.Activity;
import android.content.Intent; //Package to indicate
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Principale extends Activity {
Button bouton_1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bouton_1=(Button)findViewById(R.id.bouton);
bouton_1.setOnClickListener(new OnClickListener(){
public void onClick (View view){
Intent intent=new Intent(Principale.this, Child1.class);
startActivity(intent);
}
});
}
} 199

2.1- startActivity()
Intent intent=new Intent(Principale.this, Child1.class);
creates an object "intent" of type "Intent"
• The 1st parameter corresponds to the current instance of the
"Principale" activity from where the "Principale.this"
• The 2nd parameter corresponds to the target of "intent" ie the
activity "Child1.class"

startActivity(intent);
sends the intent to its recipient with
• the single parameter the instance "intent“

200

Dr. Ziad EL BALAA 15


I3350

2.1- startActivity()
In the Child1.java file

import android.app.Activity;
import android.os.Bundle;
public class Child1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
}

main1: is the interface of the activity Child1

201

2.2- startActivityForResult()
To start the "Child1" activity from the "Principale" activity
• with notification of the end of the execution of "Child1"

We must use
• the method "startActivityForResult" instead of "StartActivity"

202

Dr. Ziad EL BALAA 16


I3350

2.2- startActivityForResult()
The method "startActivityForResult" contians 2 parameters:
• intent and identifier

This identifier called "requestCode" is a number


• sent by the activity "parent" to the activity "child1"

The activity "child1", after its execution


• returns the previously received "requestCode“
• towards the activity "parent"

The "requestCode" will have made


• a round trip

203

2.2- startActivityForResult()
This method is used to identify the activity "child1" that has just ended

By imagining, for example, that there are several activities "child",


• how to identify the activity "child" that just ended?
 thanks to its "requestCode"

When the activity "child1" ends, it returns


• a "requestCode "
• a "resultCode"

This "resultCode" can take one of two values:


• "RESULT_OK" if the activity "child1" goes to the end of its execution
• "RESULT_CANCELED" if the activity "child1" has been interrupted
– by the button "Cancel"
– or by the return Key of the mobile 204

Dr. Ziad EL BALAA 17


I3350

2.2- startActivityForResult()
In the activity "child1", it is the method "setResult“
• which has as parameter the value of "resultCode“
• and which returns to the activity "parent" this value

On the "parent" side, this is the method


• "onActivityResult" which allows to process the "requestCode" and the
"resultCode"

This method has 3 parameters:


• the "requestCode"
• the "resultCode"
• an object of type "Intent" which will be responsible for "transporting"
additional information

205

2.2- startActivityForResult()
Example: we have 3 interfaces
• An interface main.xml for the activity Principale
• An interface main1.xml for the activity Child1
• An interface main2.xml for the activity Child2

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:text="Call activity Child1"
android:id="@+id/bouton1"
/>
<Button
android:text="Call activity Child2"
android:id="@+id/bouton2"
/>
</LinearLayout> 206

Dr. Ziad EL BALAA 18


I3350

2.2- startActivityForResult()
main1.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Welcome to the activity Child1"
/>
<Button
android:id="@+id/boutonOK1"
android:text="OK"
/>
<Button
android:id="@+id/boutonCANCEL1"
android:text="CANCEL"
/>

</LinearLayout>
207

2.2- startActivityForResult()
main2.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:text="Welcome to the activity Child2"
/>
<Button
android:id="@+id/boutonOK2"
android:text="OK"
/>
<Button
android:id="@+id/boutonCANCEL2"
android:text="CANCEL"
/>

</LinearLayout>
208

Dr. Ziad EL BALAA 19


I3350

2.2- startActivityForResult()
Principale.java
public class Principale extends Activity { Button bouton_1; Button bouton_2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bouton_1=(Button)findViewById(R.id.bouton1);
bouton_2=(Button)findViewById(R.id.bouton2);

bouton_1.setOnClickListener(new OnClickListener(){
public void onClick (View view){
Intent intent=new Intent(Principale.this, Child1.class);
startActivityForResult(intent,1); } });
bouton_2.setOnClickListener(new OnClickListener(){
public void onClick (View view){
Intent intent=new Intent(Principale.this,Child2.class);
startActivityForResult(intent,2);

} });} 209

2.2- startActivityForResult()
Principale.java
public void onActivityResult (int requestCode, int resultCode, Intent data){
switch (requestCode){
case (1):
switch (resultCode){
case RESULT_OK:
Toast.makeText(this,"Child1 OK", Toast.LENGTH_SHORT).show();
return;
case RESULT_CANCELED:
Toast.makeText(this,"Child1 Canceled", Toast.LENGTH_SHORT).show();
return; }
case (2):
switch (resultCode){
case RESULT_OK:
Toast.makeText(this," Child2 OK", Toast.LENGTH_SHORT).show();
return;
case RESULT_CANCELED:
Toast.makeText(this,"Child2 Canceled", Toast.LENGTH_SHORT).show();
return; }
210
} } }

Dr. Ziad EL BALAA 20


I3350

2.2- startActivityForResult()
Child1.java
public class Child1 extends Activity { Button B_OK; Button B_CA;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
B_OK=(Button)findViewById(R.id.boutonOK1);
B_CA=(Button)findViewById(R.id.boutonCANCEL1);

B_OK.setOnClickListener (new OnClickListener () {


public void onClick (View view) {
setResult(RESULT_OK);
finish(); } });
B_CA.setOnClickListener (new OnClickListener () {
public void onClick (View view) {
setResult(RESULT_CANCELED);
finish(); } });

} } 211

2.2- startActivityForResult()
Child2.java
public class Child2 extends Activity { Button B_OK; Button B_CA;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
B_OK=(Button)findViewById(R.id.boutonOK2);
B_CA=(Button)findViewById(R.id.boutonCANCEL2);

B_OK.setOnClickListener (new OnClickListener () {


public void onClick (View view) {
setResult(RESULT_OK);
finish(); } });
B_CA.setOnClickListener (new OnClickListener () {
public void onClick (View view) {
setResult(RESULT_CANCELED);
finish(); } });

}} 212

Dr. Ziad EL BALAA 21


I3350

2.2- startActivityForResult()
We have 2 buttons:
• one button "Call Activity Child1"
• and one button "Call Activity Child2"

If we click on the 1st button


• we create an "intent" whith the parameter "Child1.class"
• then the activity "Child1" is started using the method "startActivityForResult"
(with "1" as "requestCode")

Once the activity "Child1" is launched


• a text and 2 buttons (OK and CANCEL) are displayed
If we click on "OK"
• the "RESULT_OK" ("resultCode") is sent to the activity "Principale"
– using the method "setResult(RESULT_OK)"
– finaly, the activité "Child1" ends with the method "finish()" 213

2.2- startActivityForResult()
If we click on "CANCEL"
• the "RESULT_CANCELED" ("resultCode") is sent to activity "Principale"
– using the method "setResult(RESULT_CANCELED)"
– "Child1" ends with the method "finish()"

It is the same sequence with the activity "Child2"


• if in the method "Principale" we click on the button "Call Activity Child2"

Once back in the activity "Principale"


• the method "onActivityResult" is executed

We have 2 "switch/case" nested one within the other


• one that manages the "requestCode"
• and the other that manages the "resultCode"
214

Dr. Ziad EL BALAA 22


I3350

2.3- putExtra()
The intents also allow to "transport" data
• using the method "putExtra()"

The method "putExtra()" is applied


• to an object of type "Intent"

intent.putExtra (key,value)

Each "value" corresponds to "key"

215

2.3- putExtra()
To extract the value of the intent, it is necessary
to use an object of type "Bundle“
• Bundle objet_Bundle = this.getIntent().getExtras()

then to place the transported value in a variable


• we apply the method "getXXX" ("XXX" is the type of transported value) to
objet_Bundle
The method "getXXX" accepts a parameter
• the key associated with the transported value
variable = objet_Bundle.getString("key")

Example
• getString if the transported value is of type String
• getInt if the transported value is of type Integer
• etc. 216

Dr. Ziad EL BALAA 23


I3350

2.3- putExtra()
Example: main.xml

<?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">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Input your name"
android:id="@+id/editT"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Validate"
android:id="@+id/bouton"
/>
</LinearLayout>
217

2.3- putExtra()
main1.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textV"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/boutonOK"
android:text="OK"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/boutonCANCEL"
android:text="CANCEL"
/> 218
</LinearLayout>

Dr. Ziad EL BALAA 24


I3350

2.3- putExtra()
Principale.java
public class Principale extends Activity {Button bouton; EditText texte_name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bouton=(Button)findViewById(R.id.bouton);
bouton.setOnClickListener(new OnClickListener(){
public void onClick (View view){
texte_name=(EditText)findViewById(R.id.editT);
String name = texte_name.getText().toString();
Intent intent=new Intent(Principale.this,Child1.class);
intent.putExtra("myName", name);
startActivityForResult(intent,1); } }); }
public void onActivityResult (int requestCode, int resultCode, Intent data){
switch (resultCode){
case RESULT_OK:
Toast.makeText(this,"Child1 OK", Toast.LENGTH_SHORT).show();
return;
case RESULT_CANCELED:
Toast.makeText(this,"Child1 Canceled", Toast.LENGTH_SHORT).show();
219
return; } } }

2.3- putExtra()
Child1.java
public class Child1 extends Activity { Button B_OK; Button B_CA; TextView textV; private String name;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Bundle infoName = this.getIntent().getExtras();
if(infoName != null){
name=infoName.getString("myName"); }
textV=(TextView)findViewById(R.id.textV);
textV.setText("Hello "+name+" Welcome to activity Child1");
B_OK=(Button)findViewById(R.id.boutonOK);
B_CA=(Button)findViewById(R.id.boutonCANCEL);
B_OK.setOnClickListener (new OnClickListener () {
public void onClick (View view) {
setResult(RESULT_OK);
finish(); } });
B_CA.setOnClickListener (new OnClickListener () {
public void onClick (View view) {
setResult(RESULT_CANCELED);
finish(); } }); }
220
}

Dr. Ziad EL BALAA 25


I3350

2.3- putExtra()
The activity "Principale" contains
• a "EditText" to enter the user’s name
• and a button to launch the activity "Child1"

The activity "Child1" contains


• an empty "TextView"
• a button "OK"
• and a button "CANCEL"

These 2 buttons have the same functions as in the previous example

221

2.3- putExtra()
String name = texte_name.getText().toString();
• allows to retrieve the text entered by the user

Intent intent=new Intent(Principale.this,Child1.class);


• defines the intent

intent.putExtra("myName", name);
• add an information to the intent
• key= "myName", value = name the variable of type String defined above

222

Dr. Ziad EL BALAA 26


I3350

2.3- putExtra()
Bundle infoName = this.getIntent().getExtras();
• creates a "Bundle" object that extracts information from the intent

if(infoName != null)
• verifies that the object of type "Bundle" ("infoName") is not empty

name=infoName.getString("myName");
• the method "getString" (having as parameter the key "myName")
• allows to give a value to the variable of type String "name"

223

2.3- putExtra()
It is also possible to pass information
• from the activity "child1" to the activity "parent"

Just
• create an object of type Intent "empty" in the activity "child1"
• use the method "putExtra" to "fill" the Intent object with the information to be
transmitted

The "setResult" method will then have 2 parameters:


• the "requestCode"
• and the object Intent just created

The activity "parent" use


• the method "getXXXExtra" of the object data (XXX is the type of transported
value, String, Int,....)
224

Dr. Ziad EL BALAA 27


I3350

2.3- putExtra()
Example: Child1.java
public class Child1 extends Activity { Button B_OK; Button B_CA; EditText votre_age; private String age;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
B_OK=(Button)findViewById(R.id.boutonOK);
B_CA=(Button)findViewById(R.id.boutonCANCEL);
votre_age=(EditText)findViewById(R.id.editT);
B_OK.setOnClickListener (new OnClickListener () {
public void onClick (View view) {
age=votre_age.getText().toString();
Intent result= new Intent ();
result.putExtra("mykey",age);
setResult(RESULT_OK, result);
finish(); } });
B_CA.setOnClickListener (new OnClickListener () {
public void onClick (View view) {
setResult(RESULT_CANCELED);
finish(); } });
}
225
}

2.3- putExtra()
Principale.java
public class Principale extends Activity { Button bouton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bouton=(Button)findViewById(R.id.bouton);
bouton.setOnClickListener(new OnClickListener(){
public void onClick (View view){
Intent intent=new Intent(Principale.this,child1.class);
startActivityForResult(intent,1); } }); }
public void onActivityResult (int requestCode, int resultCode, Intent data){
switch (resultCode){
case RESULT_OK:
String age=data.getStringExtra("mykey");
Toast.makeText(this,"Vous avez "+age+" ans", Toast.LENGTH_SHORT).show();
return;
case RESULT_CANCELED:
Toast.makeText(this,"Vous ne voulez pas donner votre age",
Toast.LENGTH_SHORT).show();
return; } }
226
}

Dr. Ziad EL BALAA 28


I3350

2.3- putExtra()
Intent result= new Intent ();
• creates an instance of type "Intent" (with empty parenthesis)
– no "target" activity and no "requestCode"
– This intent will only serve us to "transport" information

result.putExtra("mykey",age);
• allows to add a data of type "String" to the intent "result"

setResult(RESULT_OK, result);
• returns the data in the intent to the activity "Principale"

String age=data.getStringExtra("mykey");
• allows to retrieve the string corresponding to the key "mykey"

227

3. Intent implicites
These intents allow to launch other applications

In the intent implicites


• the name of the component to be activated is not known

With these intents


• we don’t need to know the name of the application
• nor to specify the application to be launched

For example
• if we click on a phone number and we want to call it
• it is the system that finds the application that can call it
228

Dr. Ziad EL BALAA 29


I3350

3. Intent implicites
The Intent takes 2 parameters
• a constant
• and an object of type "Uri"

You can use the method "putExtra"

229

3. Intent implicites
The constant
The Android system offers several native actions
• each action is represented by a static constant of the class "Intent"

Examples (see the documentation for a more exhaustive list):


• ACTION_DIAL: show the dialing interface
• ACTION_CALL: call the number automatically
• ACTION_SENDTO: send a message to someone specified by the data
• ACTION_VIEW: display the element identified by the uri
This is the most common action performed on data

230

Dr. Ziad EL BALAA 30


I3350

3. Intent implicites
L'uri

The syntax of an URI is as follows:


<schema>: <information>

• The schema describes the nature of the information


– tel: it is a telephone number
– http: it is a web site
– geo: it is the GPS coordinates
– smsto: it is a sms to a number
• The information is the data, It has a syntax that depends on the schema
– for the phone number  tel:0606060606
– for the GPS  geo:123.456789,-12.345678 (the latitude and longitude
are separated by a comma)
231

3. Intent implicites
To transform a character string
• into "uri" that can be used by an object of type "Intent"
we must use
• the method parse(String uri)

In Android the "uri" are


• an objects of type "Uri"

To create an instance
• of type "uri"
we must use
Uri uri = Uri.parse(String uri)
232

Dr. Ziad EL BALAA 31


I3350

3. Intent implicites
Example with url as uri

main.xml

<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/bouton"
android:text="Go to Google"
/>
</LinearLayout>

233

3. Intent implicites
Principale.java

public class Principale extends Activity { Button bouton;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bouton=(Button)findViewById(R.id.bouton);
bouton.setOnClickListener(new OnClickListener () {
public void onClick (View view) {
Uri uri=Uri.parse("http://www.google.fr/");
Intent intent = new Intent (Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}

234

Dr. Ziad EL BALAA 32


I3350

3. Intent implicites
"uri" is an instance
• of the class "Uri"

The method "parse" transforms the string into uri


• Uri uri=Uri.parse("http://www.google.fr/");

We then create an intent with parameters


• the constant ACTION_VIEW
• and the l'uri
Intent intent = new Intent (Intent.ACTION_VIEW, uri);

235

3. Intent implicites
Example with a phone number as uri

main.xml

<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/bouton"
android:text="Call"
/>
</LinearLayout>

236

Dr. Ziad EL BALAA 33


I3350

3. Intent implicites
Principale.java

public class Principale extends Activity { Button bouton;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bouton=(Button)findViewById(R.id.bouton);
bouton.setOnClickListener(new OnClickListener () {
public void onClick (View view) {
Uri uri=Uri.parse("tel:065674453");
//l'uri doit être de la forme "tel:XXXXXX"
Intent intent = new Intent (Intent.ACTION_CALL,uri);
startActivity(intent);
}
});
}
}
237

3. Intent implicites
If we launch the application as is, it will not work!

For safety reasons, by default


• The OS prohibits certain actions to applications
• such as telephone calls from a third-party application

To "allow" an application "to call a number"


• we must modify the file "AndroidManifest.xml"

238

Dr. Ziad EL BALAA 34


I3350

3. Intent implicites
AndroidManifest.xml

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

<uses-permission android:name="android.permission.CALL_PHONE"/>
<application android:icon="@drawable/cw"
android:label="@string/app_name">

<activity android:label="@string/app_name"
android:name=".Principale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity android:name=".Child1" />

<activity android:name=".Child2" />

</application>
</manifest> 239

Dr. Ziad EL BALAA 35

You might also like