Thông tin tài liệu
11/1/2009
1
AndroidAndroid
19
Android
Android
IntentFiltersIntentFilters
VictorMatos
Cleveland State University
Cleveland
State
University
Notesarebasedon:
AndroidDevelopers
http://developer.android.com/index.html
19.Android–IntentFilters
IntentFiltersIntentFilters
AnAnalogy:RequestingActionsUsingHTTPandAndroid
1. TheHPPT
1
protocolusesanumberof<Action,resource>pairsto
accomplish its work
accomplish
its
work
.
2. SomeoftheHTTP actionsarethewellknown(andlesserknown)
operations:POST,GET,PUT,DELETE,CONNECT,HEAD,OPTIONS.
3. AndroidusesamechanismquitesimilartoHTTPforthein vocationof
worktobedone.
2222
4. INTENT istheAndroid’snamefortheabstractionrequestingactions.
5. UnlikeHTTPagivenAndroid’sINTENTcouldberesolvedinmorethan
onepotentialway(forinstance,wemayhaveseveralSMSappswanting
toprocessanincomingtext‐message).
____
1. Source:HypertextTransferProtocol‐‐ HTTP/1.1(1999).http://www.w3.org/Protocols/rfc2616/rfc2616‐sec9.html
11/1/2009
2
19.Android–IntentFilters
IntentFiltersIntentFilters
INTENTS
• Anintentisan abstractdescriptionofanoperationtobeperformed.
• Itsmostsignificantuseisinthelaunchingofactivities.
•
The primary pieces of information in an intent are
action
&
data
•
The
primary
pieces
of
information
in
an
inten t
are
:
action
&
data
.
ACTION DATA Misc
Thegeneralactiontobe
performed,suchas:
ACTION
_
EDIT
,
Thedatatooperateon,suchasaperson
recordinthecontactsdatabase,
expressedasa URI.
Iam
g
ood
f
oreditin
g
adocument
3333
Source:http://developer.android.com/reference/android/content/Intent.html
_,
ACTION_VIEW,
ACTION_MAIN,
ACTION_LAUNCHER
etc.
g f g
Iamgoodforviewingadocument
Iamthefirstexec.Activ.ofApplication
Putmeonthephone’sMenu_Pad
19.Android–IntentFilters
IntentFiltersIntentFilters
PartsofaTypicalIntent
ACTION DATA MISC
Standard
URI
Category
Standard
URI
Category
CATEGORY_DEFAULT
CATEGORY_BROWSABLE
CATEGORY_TAB
CATEGORY_ALTERNATIVE
CATEGORY_SELECTED_ALTERNATIVE
CATEGORY_LAUNCHER
CATEGORY_INFO
CATEGORY_HOME
CATEGORY_PREFERENCE
CATEGORY_TEST
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_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED
ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_RESTARTED
ACTION_PACKAGE_DATA_CLEARED
ACTION_UID_REMOVED
ACTION_BATTERY_CHANGED
ACTION_POWER_CONNECTED
ACTION_POWER_DISCONNECTED
ACTION_SHUTDOWN
CONTENTS suchas:
content://contacts/
content://contacts/1
SCHEME suchas:
tel:123
http://aaa.bbb.ccc
mailto:
//
aa
@
bbb.ccc
MIME
Explicittype(aMIMEtype)of
theintentdata.
C
4444
ACTION_SYNC
ACTION_PICK_ACTIVITY
ACTION_SEARCH
ACTION_WEB_SEARCH
ACTION_FACTORY_TEST
// @
ftp://aaa.bbb.ccc
.
pop://
smtp://
ssl://
C
omponent
Explicitnameofacomponent
classtousefortheintent.
Extras
putExtra(String,Bundle)
Flags
11/1/2009
3
19.Android–IntentFilters
IntentFiltersIntentFilters
Aside:MIME
“…Thissetofdocuments,collectivelycalledthe
M lti It tMilEt i MIME dfi th
M
u
lti
purpose
I
n
t
erne
tM
a
ilE
x
t
ens
i
ons,
or
MIME
,
re
d
e
fi
nes
th
e
formatofmessagestoallowfor
(1) textualmessagebodiesincharactersetsotherthan
US‐ASCII,
(1) anextensiblesetofdifferentformatsfornon‐textual
messagebodies,
5555
(2) multi‐partmessagebodies,and
(3) textualheaderinformationincharactersetsotherthan
US‐ASCII.”
____
Source:MultipurposeInternetMailExtensions.(MIME)PartTwo:MediaTypes.
Availableat:http://tools.ietf.org/html/rfc2046
NOTE:
CurrentusageofMIMEdescribes
contenttypeingeneral.
19.Android–IntentFilters
IntentFiltersIntentFilters
IntentResolution
WhenIntentsareissued,Androidlooksforthemostappropriatedwayof
respondingtotherequest.
Thedecisionofwhattoexecuteisbasedonhowdescriptivethecallis:
ExplicitIntents specifyaparticularcomponent
(viasetComponent(ComponentName)
orsetClass(Context,Class) ),
whichprovidestheexactclasstoberun.Thisisatypicalwayforan
applicationtolaunchvariousinternal activitiesithasastheuserinteracts
with the application
66666
with
the
application
.
ImplicitIntents donotspecifiedaparticularcomponent.Howeverthey
includeenoughinformationforthesystemtodeterminewhichofthe
availablecomponentsareintheisbestcategorytorunforthatintent.
11/1/2009
4
19.Android–IntentFilters
IntentFiltersIntentFilters
IntentResolution
“Theintentresolutionmechanismbasicallyrevolvesaround
thi It t itll f th
it t
filt
ma
t
c
hi
ngan
I
n
t
en
t
aga
i
ns
t
a
ll
o
f
th
e<
i
n
t
en
t
‐
filt
er>
descriptionsintheinstalledapplicationpackages
.”
777777
19.Android–IntentFilters
IntentFiltersIntentFilters
IntentResolution
88888
11/1/2009
5
19.Android–IntentFilters
IntentFiltersIntentFilters
IntentResolution
Asshowninthepreviousillustration.Activity3hasissueageneric requestfor
helpprocessinganincomingtext‐message.
Assumetheuserhasinstalleda“FancySMS”applicationto(perhaps)replace
thestandard“HUMBLESMS”apporiginallyincludedinAndroid.
UponthearrivaloftheimplicitIntent,Androidwill(somehow)telltheuser:
Youhavegotanewtext‐message.IhaveaFANCYandaHUMBLESMS
application–which
oneyouwantmetoexecute?Makeitadefault?
99999
Choosingcandidates: Foranactivitytobeeligibleforexecutionitmust:
1.Supportthespecifiedaction
2.SupporttheindicatedMIMEtype(ifsupplied)
3.Supportallofthecategories namedintheintent.
_____________
RULEOFTHUMB:YourIntentsshouldbeasspecificaspossible
19.Android–IntentFilters
IntentFiltersIntentFilters
Example:IntentFilters
TheManifesttellstheapplication(FancySms)isabletointerceptincomingSMS
datausingitsSMSReceiver (potentialalternativetothedefaultSMSapp.)
<?xmlversion="1.0"encoding="utf‐8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.intentfilters"android:versionCode="1"android:versionName="1.0.0">
<uses‐permissionandroid:name="android.permission.RECEIVE_SMS"/>
<applicationandroid:icon="@drawable/icon">
<activityandroid:name=".FancySms">
<intent‐filter>
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
/
1010101010
<
/
intent‐filter>
</activity>
<receiverandroid:name="SMSReceiver"android:enabled="true">
<intent‐filter>
<actionandroid:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent‐filter>
</receiver>
</application>
</manifest>
11/1/2009
6
19.Android–IntentFilters
IntentFiltersIntentFilters
Commentsontheexample:
• Theapplicationconsistsoftwocomponents:
1
a common Activity called
FancySms
(acting as the main routine) and
1
.
a
common
Activity
called
FancySms
(acting
as
the
main
routine)
and
2. abackgroundService(BroadcastReceiver)calledSMSService.
• TheclausebelowindicatestheapplicationisallowedtoreceiveSMS
<uses‐permissionandroid:name="an droid.permission.RECEIVE_SMS"/>
• ThecomponentSMSService hasthefilter
<intent
‐
filter>
1111111111
<intent
filter>
<actionandroid:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent‐filter>
thattriggersitsexecutionwheneveranewSMSisreceived
• OtherapplicationswiththesamefiltercanbealsocalledbyAndroidwhen
newSMSarrives(untilaDEFAULTischosen)
19.Android–IntentFilters
IntentFiltersIntentFilters
Example:InterceptingIncomingSMS
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/mainLayout"
android:layout width
=
"
fill parent
“
android:layout height
=
"
fill parent
"
android:layout_width
=
fill_parent
android:layout_height
=
fill_parent
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textSize="20px" android:textStyle="bold“ ndroid:background="#ff0000ff"
android:text="Intercepting SMS messages"
/>
<ScrollView
android:id="@+id/myScroller1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
1212121212
>
<TextView
android:id="@+id/theMessage"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="#ffffffff" android:padding="4px"
android:textSize="14px" android:textColor="#ff000000"
/>
</ScrollView>
</LinearLayout>
11/1/2009
7
19.Android–IntentFilters
IntentFiltersIntentFilters
Example:InterceptingIncomingSMS
Note:
Testthefollowingapplication
fromtheEclipse’sDDMS
perspective.Select“Emulator
Control”>“TelephonyActions”.
Setphoneno.to5554,typea
message,clickonSend.
Alternativelyyoumaystart
anotheremulatorandsend
1313131313
SMSto5554
19.Android–IntentFilters
IntentFiltersIntentFilters
Example:InterceptingIncomingSMS
// FancySms: main screen - displays intercepted SMS
package cis493.intentfilters;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class FancySms extends Activity {
static TextView txtMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
1414141414
setContentView(R.layout.main);
txtMsg = (TextView)findViewById(R.id.theMessage);
}
}// class FancySms
11/1/2009
8
19.Android–IntentFilters
IntentFiltersIntentFilters
Example:InterceptingIncomingSMS
// SMSReceiver: listens to broadcasted SMS_RECEIVED signals
package cis493.intentfilters;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
1515151515
@Override
public void onReceive(Context context, Intent intent) {
// Android saves in a bundle the current text-message
// under name "pdus" and type: Object[]. Later we cast to
// SmsMessage[]. Jargon pdu stands for "protocol data unit"
Bundle bundle = intent.getExtras();
19.Android–IntentFilters
IntentFiltersIntentFilters
Example:InterceptingIncomingSMS
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
// Note: long sms are broken and transmitted into various pieces
String msg = "";
int smsPieces = messages.length;
for (int n = 0; n < smsPieces; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
// grab all pieces of the intercepted sms
msg += "\n" + (n + 1) + " -of- " + smsPieces + "\n"
+ "Sender:\t" + smsMessage[n].getOriginatingAddress() + "\n"
+ "Body: \n " + smsMessage[n].getMessageBody();
}
1616161616
}
// show first part of intercepted (current) message
Toast toast = Toast.makeText(context, "FANCY >>> Received SMS: "
+ smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
cis493.intentfilters.FancySms.txtMsg.setText(msg);
}
}// class SMSReceiver
11/1/2009
9
19.Android–IntentFilters
IntentFiltersIntentFilters
QuestionsQuestions
171717
19.Android–IntentFilters
IntentFiltersIntentFilters
JARGON:
PDU
i htf "
Pt lDt Uit
" Thi t t f if ti
i
ss
h
or
t
f
or
"
P
ro
t
oco
l
D
a
t
a
U
n
it
"
.
Thi
srepresen
t
sanamoun
t
o
f
i
n
f
orma
ti
on
deliveredthroughanetworklayer.
VND
virtualnetworkdata (todaytypicallyrepresentsabusinesscardwithname,
phone,email,etc).OriginallyregisteredasMIME vnd.abcintendedfor
transmissionofabc folkmelodiesinemails
see:http://www.iana.org/assignments/media‐types/text/vnd.abc
181818
Ngày đăng: 16/03/2014, 23:41
Xem thêm: Android chapter19 intent filters