Download Android Menus (basics)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Basic UI elements:
Android Menus (basics)
Marco Ronchetti
Università degli Studi di Trento
Menu types
Traditional menus are awkward on a small screen.
⇒  Three stages menus:
  Option Menu (< 3.0) / Action Bar (>=3.0)
  Context Menu (< 3.0) / Contextual Action mode(>=3.0)
  Popup Menu
2
Option Menu
The primary collection of menu items for an activity.
•  actions that have a global impact on the app,
e.g."Search," "Compose email," and "Settings."
On Android 2.3 or lower (API level 10), the options
menu is called by pressing the Menu button.
From Android 3.0, the Menu button is deprecated
(some devices don't have it).
On Android 3.0 and higher, items from the options
menu are presented by the action bar as a combination
of on-screen action items and overflow options.
3
Option Menu - overflow
The first visible portion is the icon menu,
which holds up to six menu items.
If your menu includes more than six
items, Android places the sixth item and
the rest into the overflow menu, which
the user can open by selecting More.
From 3.0: By default, the system places all items
in the action overflow, but you can ask to show
them in the action bar.
Overflow
You can support older versions of Android with an action bar.
Source code of an example is here:
4
http://developer.android.com/resources/samples/ActionBarCompat/index.html
SimpleMenu
5
Layout & Strings
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/tf1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/output" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">This is Activity A1</string>
<string name="app_name">SimpleMenu</string>
<string name="output">no results yet...</string>
</resources>
6
add(int groupId, int itemId, int order, CharSequence title)
Method of the Menu class.
Adds a new item to the menu. This item displays the
given title for its label.
• 
• 
• 
• 
7
groupId The group identifier that this item should
be part of. This can be used to define groups of
items for batch state changes. Normally use NONE
if an item should not be in a group.
itemId
Unique item ID. Use NONE if you do not
need a unique ID.
order
The order for the item. Use NONE if you
do not care about the order. See getOrder().
title
The text to display for the item.
package it.unitn.science.latemar;
SimpleMenu – A1
8
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class A1 extends Activity {
int nClicks=0;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.layout1);
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
Menu is created
int base=Menu.FIRST;
MenuItem item1=menu.add(base,1,1,"Increase");
MenuItem item2=menu.add(base,2,2,"Decrease");
return true;
Respond to a
}
Menu event
public boolean onOptionsItemSelected(MenuItem item) {
TextView tf = (TextView) findViewById(R.id.tf1);
if (item.getItemId()==1) increase();
private void increase() {
else if (item.getItemId()==2) decrease();
nClicks++;
else return super.onOptionsItemSelected(item);
}
tf.setText("Clicks :"+nClicks);
private void decrease() {
nClicks--;
return true;
}
}
}
9
Calling Activities in other
apps: Android Intents
Marco Ronchetti
Università degli Studi di Trento
Re-using activities
When you create an application, you can assemble it
from
•  activities that you create
•  activities you re-use from other applications.
An app can incorporate activities from other apps.
Yes, but how? By means of Intents
These activities are bound at runtime: newly installed
applications can take advantage of already installed
activities
10
Compare…
public static invokeMyApplication(Activity parentActivity) {
String actionName= "com.myCompany.myApp.intent.action.MY_APP";
Intent intent = new Intent(actionName);
parentActivity.startActivity(intent);
}
IMPLICIT
new Intent(String s)
A symbolic reference
(name)
instead of
ESPLICIT new Intent(Context c, Class c); An actual class
11
Data
IMPLICIT
new Intent(String s, URI uri)
name
Pointer to the data
to work on
EXAMPLES
new Intent(Intent.ACTION_CALL, Uri.parse(“tel:0461-881500”);
new Intent(Intent.ACTION_VIEW, Uri.parse(“http://latemar.science.unitn.it”);
new Intent(Intent.ACTION_VIEW, Uri.parse("geo:50.123,7.1434?z=19"));
12
Our code – IntentUtils - 1
package it.unitn.science.latemar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
public class IntentUtils {
A string
public static void invokeWebBrowser(Activity activity) {
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://latemar.science.unitn.it"));
activity.startActivity(intent);
}
public static void invokeWebSearch(Activity activity) {
Intent intent=new Intent(Intent.ACTION_WEB_SEARCH,
Uri.parse("http://www.google.com"));
activity.startActivity(intent);
}
13
Our code – IntentUtils - 2
public static void dial(Activity activity) {
Intent intent=new Intent(Intent.ACTION_DIAL);
activity.startActivity(intent);
}
public static void showDirections(Activity activity){
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps? saddr=Bolzano&daddr=Trento")
activity.startActivity(intent);
}
}
14
Our Code: IntentsActivity -1
package it.unitn.science.latemar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class IntentsActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
tv.setText("Push the menu button!");
setContentView(tv);
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
int base=Menu.FIRST;
MenuItem item1=menu.add(base,1,1,"invokeWebBrowser-VIEW");
MenuItem item2=menu.add(base,2,2,"invokeWebBrowser-SEARCH");
MenuItem item3=menu.add(base,3,3,"showDirections");
MenuItem item5=menu.add(base,4,4,"dial");
return true;
}
15
Our Code: IntentsActivity -2
public boolean onOptionsItemSelected(MenuItem item) {
System.err.println("item="+item.getItemId());
if (item.getItemId()==1)
IntentUtils.invokeWebBrowser(this);
else if (item.getItemId()==2)
IntentUtils.invokeWebSearch(this);
else if (item.getItemId()==3)
IntentUtils.showDirections(this);
else if (item.getItemId()==4)
IntentUtils.dial(this);
else
return super.onOptionsItemSelected(item);
return true;
}
}
16
Our App
17
Our activities
18
Google’s published intents
19
See http://developer.android.com/guide/appendix/g-app-intents.html
20
Intent structure
Marco Ronchetti
Università degli Studi di Trento
The full Intent structure
Who will perform the action?
•  Component name (can be unnamed)
Which action should be performed?
•  Action identifier (a string)
Which data should the action act on ?
•  Data The URI of the data to be acted on
How we classify the action to be performed?
•  Category A (usually codified) string.
How do we directly pass data?
•  Extras Key-value pairs for additional information that
should be delivered to the component handling the
intent
How do we specify behavior modification?
•  Flags Flags of various sorts.
21
Examples of action/data pairs
ACTION_VIEW content://contacts/people/1
• 
Display information about the person whose identifier is "1".
ACTION_DIAL content://contacts/people/1
• 
Display the phone dialer with the person filled in.
ACTION_VIEW tel:123
• 
Display the phone dialer with the given number filled in. Note how
the VIEW action does what what is considered the most reasonable
thing for a particular URI.
ACTION_DIAL tel:123
• 
Display the phone dialer with the given number filled in.
ACTION_EDIT content://contacts/people/1
• 
Edit information about the person whose identifier is "1".
ACTION_VIEW content://contacts/people/
• 
Display a list of people, which the user can browse through.
22
Standard Actions Identifiers
ACTION_MAIN
ACTION_VIEW
ACTION_ATTACH_DATA
ACTION_EDIT
ACTION_PICK
ACTION_CHOOSER
ACTION_GET_CONTENT
ACTION_DIAL
ACTION_CALL
ACTION_SEND
ACTION_SENDTO
ACTION_ANSWER
ACTION_INSERT
ACTION_DELETE
ACTION_RUN
ACTION_SYNC
ACTION_PICK_ACTIVITY
ACTION_SEARCH
ACTION_WEB_SEARCH
ACTION_FACTORY_TEST
23
24
Publishing Activities:
Intent Filters and resolution
Marco Ronchetti
Università degli Studi di Trento
intent-filter
If we have an activity called MyActivity, using intents
we can publish it, so that other apps can call it.
<activity android:name="MyActivity"
In the manifest
android:label="@string/my_application_label">
<intent-filter>
<action
android:name=”com.myCompany.myApp.intent.action.MY_APP”
/>
</intent-filter>
</activity>
Other apps can call it like this:
public static invokeMyApplication(Activity parentActivity) {
String actionName= "com.myCompany.myApp.intent.action.MY_APP";
Intent intent = new Intent(actionName);
parentActivity.startActivity(intent);
}
25
Implicit intents and intent resolution
In the absence of a designated target, the Android system
must find the best component (or components) to handle
the intent.
It does so by comparing the contents of the Intent object to
intent filters, structures associated with components that can
potentially receive intents.
Filters advertise the capabilities of a component and
delimit the intents it can handle.
If a component does not have any intent filters, it can
receive only explicit intents.
A component with filters can receive both explicit and
implicit intents.
26
Late binding
Implicit intent messaging is a facility for
late run-time binding
between components in the same or different
applications.
27
10
Intents and Intent Filters
Resolution
Intent Filters
Only
threeintents
aspects
an Intent
object
> Description
of what
an of
activity
can handle
are consulted when the object is tested
> Activitiesagainst
publish their
intentfilter:
filters in a manifest file
an intent
•  actionandroid:priority="0">
<intent-filter
•  data
(both URI and data type)
<action
android:name="android.intent.action.VIEW"/>
<category
android:name="android.intent.category.DEFAULT"/>
•  category
<category android:name="android.intent.category.BROWSABLE"/>
<data
Theandroid:scheme="geo"/>
extras and flags play no part in
</intent-filter>
resolving which component receives
an intent.
> Upon invocation of startActivity(intent) the
Then,atifthe
theintent
resolution
doesn’t
provide a
filters of
all
system looks
result, the user is requested to
installed unique
applications
make the final choice.
28
How is resolution performed?
Intent x=new Intent("com.ex. SHOW_RECENT" );
x.setData(Uri.parse(“mailto:pippo@gmail.com”));
x.addCategory(“CATEGORY_DEFAULT”);
1) the filter must list the name specified for the Intent,
or it should define NO action at all.
<activity android:name=".EmailManagingActivity”>
<intent-filter . . . >
<action android:name="com.ex. SHOW_CURRENT" />
<action android:name="com.ex. SHOW_RECENT" />
<action android:name="com.ex. SHOW_PENDING" />
...
</intent-filter>
</activity>
29
How is resolution performed?
Intent x=new Intent("com.ex. SHOW_RECENT" );
x.setData(Uri.parse(“mailto:pippo@gmail.com”));
x.addCategory(“CATEGORY_DEFAULT”);
2) For an intent to pass the category test, every
category in the Intent object must match a category in
the filter. .
<activity android:name=".EmailManagingActivity”>
<intent-filter . . . >
<action android:name="com.ex. SHOW_CURRENT" />
<action android:name="com.ex. SHOW_RECENT" />
<action android:name="com.ex. SHOW_PENDING" />
<category android:name="android.intent.category.DEFAULT" /> ...
</intent-filter>
</activity>
NOTE: Android treats all implicit intents passed to startActivity() as if
they contained at least one category: CATEGORY_DEFAULT.
30
For details see http://developer.android.com/reference/android/content/Intent.html#CATEGORY_ALTERNATIVE
Standard Categories
31
How is resolution performed?
Intent x=new Intent("com.ex. SHOW_RECENT" );
x.setData(Uri.parse(“mailto:pippo@gmail.com”));
x.addCategory(“CATEGORY_DEFAULT”);
3) The data is compared.
<activity android:name=".EmailManagingActivity”>
<intent-filter . . . >
<action android:name="com.ex. SHOW_RECENT" />
<data android:mimeType="video/mpeg"
android:scheme="http" . . . />
...
</intent-filter>
</activity>
32
Data resolution rules
An Intent passes a Filter if:
FILTER
INTENT
Contains URI
Has Data type
Contains URI
Has Data type
NO
NO
NO
NO
YES
NO
Matches URI
NO (*)
NO
YES
NO
Matches D.T.
NO
YES
has a content: Matches D.T.
or file: URI
YES
YES
Matches URI
Matches D.T. (**)
(*) and the data type cannot be inferred from the URI
(**) or a matching data type can be inferred from the URI
33
Finding out if an Intent can be resolved
public boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfo.size() > 0) {
return true;
}
return false;
}
34
Other uses of Intents: services
An Intent object is passed to Context.startService() to
•  initiate a service
•  deliver new instructions to an ongoing service.
An intent can be passed to Context.bindService() to
•  establish a connection between with a target
service.
35
Other uses of Intents: broadcast receivers
Intent objects passed to any of the broadcast methods
(methods of the class Context) are delivered to all
interested broadcast receivers.
Android finds the appropriate activity, service, or set of
broadcast receivers to respond to the intent, instantiating
them if necessary.
There is no overlap within these messaging systems:
•  Broadcast intents are delivered only to broadcast
receivers, never to activities or services.
•  An intent passed to startActivity() is delivered only to an
activity, never to a service or broadcast receiver, etc.
36
37
Android Java packages
Marco Ronchetti
Università degli Studi di Trento
Basic components
android.app
  implements
the Application model for Android
android.content
  implements
the concept of Content providers
android content.pm
  Package
manager: permissions, installed {packages,
services, provider, applications, components}
android.content.res
  Access
to resources
android.provider
  Contacts,
38
MediaStore, Browser, Setting
GUI basics
android.view
  Menu,
View, ViewGroup + listeners
android.view.animation
android.view.inputmethod
  Input
methods framework
android.widget
  UI
controls derived from View (Button, Checkbox…)
android.gesture
  create,
39
recognize, load and save gestures
Graphics
android.graphics
 
 
low level graphics tools such as canvases, color filters, points, and rectangles
that let you handle drawing to the screen directly.
Bitmap, Canvas, Camera (3D transformation, not the camera!) , Color, Matrix,
Movie, Paint, Path, Rasterizer, Shader, SweepGradient, Typeface
android.graphics.drawable
 
variety of visual elements that are intended for display only, such as bitmaps
and gradients
android.graphics.drawable.shapes
android.opengl
 
opengl-related utility classes, not the opengl!
javax.microedition.khronos.opengles
javax.microedition.khronos.egl
javax.microedition.khronos.nio
android.renderscript
 
40
low-level, high performance means of carrying out mathematical calculations
and 3D graphics rendering
Text rendering
android.text
  classes
used to render or track text and text spans on
the screen
android.text.method
  Classes
that monitor or modify keypad input.
android.text.style
  Text
styling mechanisms
android.service.textservice
  Provides
classes that allow you to create spell checkers
android.view.textservice
  Use
41
spelling checkers
Database, Web and location
android.database
 
classes to explore data returned through a content provider.
android.datebase.sqlite
 
the SQLite database management classes that an application
would use to manage its own private database. Applications
use these classes to manage private databases.
android.webkit
 
tools for browsing the web.
android.location
 
Address, Geocoder, Location, LocationManager,
LocationProvider
com.google.android.maps
42
Network and telephony
android.net
 
Socket-level network API - help with network access, beyond the normal
java.net.* APIs.
android.net.wifi
android.bluetooth
android.nfc
 
Near Field Communication (NFC) is a set of short-range wireless technologies,
typically requiring a distance of 4cm or less to initiate a connection. NFC allows
you to share small payloads of data between an NFC tag and an Androidpowered device, or between two Android-powered devices.
android.telephony
 
 
monitoring the basic phone information, plus utilities for manipulating phone
number strings, SMS
CellLocation, PhoneNumberUtils, TelephonyManager
android.telephony.gsm
 
Obtain Cell location of GSM
android.telephony.cdma
 
43
Obtain Cell location of CDMA - CDMA2000 is a family of 3G mobile technology
standards
Media and speech
android.media
 
 
manage various media interfaces in audio and video
MediaPlayer, MediaRecorder, Ringtone, AudioManager, FaceDetector.
android.media.effect
 
apply a variety of visual effects to images and videos
android.hardware
 
support for hardware features, such as the camera and other sensors
android.drm
 
Digital right management
android.mtp
 
interact directly with connected cameras and other devices, using the
PTP (Picture Transfer Protocol)
android.speech
 
base class for recognition service implementations
android.speech.tts
 
44
Text to Speech
General utilities
android.utils
 
date/time manipulation, base64 encoders and decoders, string and number
conversion methods, and XML utilities.
android.sax
 
XML parsing
android.test
 
A framework for writing Android test cases and suites
android.preference
 
manage application preferences and implement the preferences UI. Using these
ensures that all the preferences within each application are maintained in the
same manner and the user experience is consistent with that of the system and
other applications
android.os
 
 
45
basic operating system services, message passing, and inter-process
communication
Binder (ipc), FileObserver (changes in files) Handler e Looper (for dealing with
message threads), BatteryManager, PowerManager
Still useful java packages
java.lang (e subpackages)
java.math
java.net + javax.net
java.io
java.nio
java.sql+javax.sql
  (android.database
java.util
46
preferable if possible)
Other still useful packages
javax.crypto
javax.security
javax.xml
org.w3c.dom
org.xml.sax
org.apache.http (e subpackages)
47