Ch 6: Intents and Broadcast Receivers Flashcards
Definition:
Intent
Intent
A message passing mechanism that can be used within an application, between applications, between the system and an application.
Intents are a fundamental part of the Android OS and are unique to Android.
Common Uses for Intents
- Explicitly start a particular Service, Broadcast Receiver, Activity or sub-Activity using its class name
- Start an Activity, sub-Activity or Service to perform an action with(or on) a particular piece of data
- Return information from a sub-Activity
- Broadcast that an event has occurred
Starting Activities
Explicitly
vs
Implicitly
- An Activity is started Explicitly using an Intent that specifies the name of the Activity class
- The Activity class must be within the calling application
- An Activity is started Implicitly when an Intent requests that a specific action be performed on a piece of data
- Android will dynamically choose an Activity or Service through the process of “Intent Resolution”
Explicitly Starting New Activities:
Steps
- Construct an Intent, specifying the current activity as context and the class of the Activity to be started
- Intent intent = new Intent( MyActivity.this, MyOtherActivity.class)
- Use the “startActivity()” method, with the Intent as a parameter, to submit a request to create, start and resume the Activity
- startActivity( intent )
Explicitly Starting New Activities:
How the Activity is Managed on the Activity Stack
- After “startActivity()” is called, the new Activity is created, started and resumed
- It is placed on top of the Activity stack
- Calling “finish()” on the new Activity, or pressing the hardware back button will close the Activity and remove it from the stack
- It may also navigate to other Activities using “startActivity()”
- Each call to “startActivity()” will create a new Instance of the Activity and add it to the stack
- If an Activity is closed without a call to finish, it might remain in the Activity Stack
- Multiple instances of the same Activity can exist in the Activity stack
Implicit Intent:
Definition
Implicit Intent
Used to ask the system to find and start an Activity that can perform a particular action, without you knowing exactly which application, or Activity, will be started.
Implicit Intent:
Constructing the Intent
- Uses an different constructor for Intent
- new Intent( Action , URI )
- Specify an Action
- There are several predefined Actions in the Intent class, ( Intent.ACTION_* )
- Specify the URI of the data on which the action should be performed
- After construction, may add additional primitive values to the Intent, called “Extras”
- Use the “putExtra()” method
- intent.putExtra(“STRING_EXTRA”, “My String”);
What is
“intent resolution” ?
When an Intent specifies a particular action to perform, rather than an Activity,
the run time will dynamically choose an Activity that is able to perform that action.
- This allows an app to use Activities from other applications, such as the dialer
- Some Activities have “Intent Filters” that help determine the Intent Resolution
How to recieve feedback/results
from launching a sub-activity
- Start the activity by passing the Intent to “startActivityForResult()” instead of “startActivity()”
- StartActivity does not provide any feedback
What are Broadcast Intents?
Intents that are used to broadcast messages across the system.
Applications can register Broadcast Receivers to listen for, and react to, the broadcast intents.
This enables event-driven applications.
The Android system uses Broadcast Intents to announce system events, such as changes in Internet Connectivity or Battery Level
Implicit Intents:
Extras
Extras
- A mechanism used to attach primitive values to an Intent
- Can use the overloaded “putExtra()” method on any Intent to attach a name-value pair
- Extras are stored within the Intent as Bundle objects
- Extract values from the bundle using the get[type]extra( name ) method
How to check at run time
if an Intent will be resolved?
- Use PackageManager to query which, if any, Activity would be launched:
- Get the Package Manager:
- PackageManager pm = getPackageManager();
- Pass it to the “resolveActivity()” method of the Intent Instance, which will return a ComponentName object
- ComponentName cn = intent.resolveActivity(pm)
- It will return null if no Activity is found
- This should be checked before passing the Intent to StartActivity()
Using a Sub-Activity:
Steps
- Launch:
- startActivityForResult( Intent , RequestCode)
- Preparing to Return:
- call setResult( ResultCode, ResultData)
- Call finish() to indicate that the sub-activity has completed
- Handle Results:
- onActivityResult() handler is triggered, with parameters:
- Request Code, Result Code, Data
Sub-Activities:
Important Methods and Parameters
Methods
- startActivityForResult()
- setResult()
- finish()
- onActivityResult() - event handler
- intent.resolveActivity()
Parameters/Values
- Request Code
- Result Code
- Data
Platform-Native Actions:
What are they?
A set of common Actions on the Android platform.
The Intent class has a set of static string constants used to represent the actions, these can be used when creating Implicit Intents to start Activities and sub-Activities.
- Example: ACTION_DIAL brings up the phone dialer Activity
Platform-Native Actions:
List of Common Action strings
defined in the Intent class
(10)
*Note: this is NOT comprehensive
- ACTION_DELETE
- ACTION_EDIT
- ACTION_INSERT
- ACTION_DIAL
- ACTION_PICK
- ACTION_SEARCH
- ACTION_SENDTO
- ACTION_SEND
- ACTION_VIEW
- ACTION_WEB_SEARCH
Platform-Native Actions:
ACTION_DELETE
Starts an Activity that lets you delete the data specified at the Intent’s data URI
Platform-Native Actions:
ACTION_DIAL
Brings up a dialer application.
With the number to dial pre-populated from the Intent’s data URI.
- By default this is handled by the native Android phone dialer
Platform-Native Actions:
ACTION_EDIT
Requests an Activity that can edit the data at the Intent’s data URI
Platform-Native Actions:
ACTION_INSERT
Opens an Activity capable of inserting new items into the Cursor specified in the Intent’s data URI
When called as a sub-Activity, it should return a URI to the newly inserted item.
Platform-Native Actions:
ACTION_PICK
Launches a sub-Activity that lets you pick an item from the Content Provider specified by the Intent’s data URI.
When closed, it should return a URI to the item that was picked.
The Activity launched depends on the data being picked.
Ex:
content://contacts/people will invoke the native contacts list
Platform-Native Actions:
ACTION_SEARCH
Typically used to launch a specific search Activity.
When it’s fired without a specific Activity, the user will be prompted to select from all applications that support search.
Supply the search term as a string in the Intent’s extras, using “SearchManager.QUERY” as the key.
Platform-Native Actions:
ACTION_SENDTO
Launches an Activity to send data to the contact specified by the Intent’s data URI.
Platform-Native Actions:
ACTION_SEND
Launches an Activity that sends the data specified by the Intent.
- The recipient contact needs to be selected by the resolved Activity.
- Use only to send data to a remote recipient ( not to another app on the device)
- Use “setType” to set the MIME type of the transmitted data
- The data itself should be stored as an extra by means of the key “EXTRA_TEXT” or “EXTRA_STREAM”, depending on the type
- In the case of email, the native Android applications will also accept extras via several other keys
Platform-Native Actions:
ACTION_VIEW
- Asks that the data supplied in the Intent’s data URI be viewed in the most reasonable manner
- This is the most common generic action
- Different applications will handle view requests depending on the URI schema of the data supplied:
- “http:” addresses open in the browser
- “tel:” addresses will open the dialer to call the number
- “geo:” addresses will be displayed in Google Maps
- “contact” content will be displayed in Contact Manager
Platform-Native Actions:
ACTION_WEB_SEARCH
Opens the Browser to perform a web search based on the query supplied using the SearchManager.QUERY key
Intent Filter:
Basic Idea
An Intent Filter is a declaration that a particular Activity is capable of performing an action on a type of data.
They are also used by Broadcast Recievers to indicate the broadcast actions that will be recieved
Intent Filters:
Defining an Intent Filter
- Must add an <intent-filter> tag to the desired Activity's manifest node</intent-filter>
- The tag must included the following tags:
- <action> (at least one)</action>
- <category> (can be multiple)</category>
- <data> (can be multiple)</data>
Intent Filters:
action tag
Uses the android:name attribute to specify the name of the action to be performed.
- Each Intent Filter must have at least one action tag
- Actions should be unique strings that are self describing.
- You can define your own actions, or use one of the system actions
Intent Filters:
category tag
- Uses the android:name attribute to specify under which circumstances the action can be performed.
- Each Intent Filter tag can include multiple category tags.
- You can specify your own categories or use one of the standard values provided by Android
Intent Filters:
data tag
- Enables you to specify which data types your component can act on
- You can include several data tags as appropriate
- You can use any combination of the following attributes to specify the data the component supports:
- android:host
- android:mimetype
- android:path
- android:port
- android:scheme
Intent Filters:
data tag attributes:
android:host
android:host
Specifies a valid hostname
for example: google.com
Intent Filters:
data tag attributes:
android:mimetype
android:mimetype
Specifies the type of data your component is capable of handling.
For example:
vnd.android.cursor.dir/* would match any Android Cursor
Intent Filters:
data tag attributes:
android:path
android:path
Specifies valid path values for the URI
For example:
/transport/boats/
Intent Filters:
data tag attributes:
android:port
android:port
Specifies valid ports for the specified host
Intent Filters:
data tag attributes:
android:scheme
android:scheme
Requires a particular scheme
(for example “content” or “http”)
Intent Resolution:
Basic steps Android uses to resolve Intents using Intent Filters
- List all available Intent Filters
- Remove Intent Filters that do not match the Action or Category associated with the Intent being resolved
- Compares the Intent’s data URI to the Intent Filter’s data tag. Mismatches are removed from list
- If the list contains more than one viable component, all matching possibilities are presented to the user to decide
Intent Resolution:
Action Matching criteria
Action matches are made only if the Intent Filter includes the action specified by the Intent.
An Intent Filter will fail the action match check if NONE of its actions matches.
Intent Resolution:
Category Matching criteria
For a category match, Intent filters must include ALL of the categories defined in the resolving Intent.
The Intent Filter can include additional categories that are not included in the Intent.
An Intent Filter with no categories specified matches only Intents with no categories
Intent Resolution:
Data match criteria
Each part of the Intent’s data URI is compared to the Intent Filter’s data tag.
- If the Intent Filter specifies a scheme, host/authority, path, or MIME type, these values are compared to the Intent’s URI
- Any mismatch removes the Intent Filter from the list
- Specifying no data values in an Intent Filter will result in a match with ALL Intent data values
Intent Resolution:
Parts of an Intent’s
URI Data tag
- MIME type of the data to be matched
- Wildcards can be used for matching
- Scheme
- the “protocol” part of the URI
- ex: “http:”, “mailto:”, “tel:”
- the “protocol” part of the URI
- Hostname or Data Authority
- Section between the scheme and the path
- ex: developer.android.com
- Path
- The data path, comes after the authority
- A path can match only if the scheme and hostname parts of the data tag
How an Activity can
access the Intent that started it
Intent intent = getIntent()
This returns the Intent that started the Activity
- Use intent.getAction()
- to find the Action the Activity should perform
- Use intent.getData()
- to get a URI data object from the Intent
- Use intent.get<type>Extra</type> methods
- to get any extra data stored in the extras bundle
Code snippet:
Updating an Activity’s Intent
Use setIntent( newIntent )
in the handler responding to a new Intent
Using Intent Filters
for
Plug-Ins and Extensibility:
To advertise an Activity’s available Actions,
what tag and value on the Intent Filters is required?
For each action,
the Intent Filter must have a <category> tag with a value of either </category>
ALTERNATIVE or SELECTED_ALTERNATIVE
ex:
<category></category>
Using Intent Filters
for
Plug-Ins and Extensibility:
Difference between the category values
ALTERNATIVE
and
SELECTED_ALTERNATIVE
ALTERNATIVE
Used to indicate that the action is an alternative to what the user may currently be viewing.
Displayed in a set of Alternative Actions, usually as part of an Options menu
SELECTED_ALTERNATIVE
Similar, but indicates an action that is typically performed on a selected item displayed within a list
Using Intent Filters
for
Plug-Ins and Extensibility:
Basic Steps of Discovering Available Actions
- Create an Intent to search for actions
- Use addCategory() to give the Intent a Category of action it will accept, either
- Intent.CATEGORY_ALTERNATIVE or
- Intent.CATEGORY_SELECTED_ALTERNATIVE
- Use addCategory() to give the Intent a Category of action it will accept, either
- Query the PackageManager by passing the Intent and a Flags value to PackageManager.queryIntentActivityOptions()
- It will return a list of “ResolveInfo” items representing the matching available actions
Linkify:
Basic Overview
Linkify
- A helper class
- Creates hyperlinks within Text View classes through RegEx pattern matching
- Text matching a specific pattern will be turned into a clickable hyperlink with the matched text as it’s URI
- Has preset string patterns that can match:
- web URLs
- email addresses
- map addresses
- phone numbers
Linkify:
How matching text
is turned into a link
- A text View instance is passed to LInkfiy using the static “addLinks()” method:
- Linkify.addLinks( textView , Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES)
- Can include several patterns OR’d together
- Linkify generates a URI from the matching pattern
- A click handler is added to the Link ,
- Fires: startActivity(new Intent( Intent.ACTION_VIEW, uri) )
Linkify:
Create Custom Link Strings
- Create a RegEx pattern
- Do this with the Pattern class
- Linkify the target Text View by calling Linkify.addLinks()
- Pass in your pattern
- May also pass in a prefix that will be prepended to the target URI
- May also pass in filters
Linkify:
What are Filters?
Filters offer additional control over:
- the target URI structure
- and the definition of matching string
Filters
- Defined as interfaces that must be implemented by you
- Match Filters apply extra criteria for matches
- Transform Filters make changes to the uri
Broadcast Intents:
Overview
- Intents are a system-level message passing mechanism
- Can cross process boundaries
- Implement Broadcast Receivers to listen for, and respond to, Broadcast Intents
- Can respond to Broadcast Intents from your own App, from other apps, or from the system itself
- Android broadcasts events extensively using Intents
How to Broadcast an Intent
- Construct your Intent
- Same as a normal Intent
- If Implicit, specify an action string to identify the type of intent being broadcast
- Add data and extras
- Broadcast using
- sendBroadcast(myIntent)
Broadcasting an Intent:
What is the Action string?
The Action string is used to identify the type of event being broadcast.
Used to help resolve implicit Intents by matching a particular action that should be performed.
By Convention, Action strings are constructed with the same form as Java package names:
“com.mycompany.derp.action.MY_ACTION”
Broadcast Intents:
Broadcast Receivers Overview
- A class that is able to listen and respond to broadcast Intents
- commonly just called “Receivers”
- Extend the BroadcastReceiver class
- Must be registered to receive broadcasts
- Either in code or in the application manifest
- Override the onReceive() event handler
Broadcast Intents:
Handling the Broadcast Intent with a Receiver
- The Receiver class should extend BroadcastReceiver
- Override the onReceive method:
- Will be executed on the main application Thread
- All processing in the Broadcast Receiver must finish within 10 seconds to avoid an ANR event
- Any non-trivial work should be performed asynchronously:
- Schedule a background job
- Launch a bound Service
- call goAsync()
Broadcast Intents:
Registering Broadcast Receivers:
in Code
Typically done for responding to broadcasts sent from your own application.
Best Practice: Register within the onStart() handler, unregister during onStop()
- Register with the registerReceiver() method
- May pass an IntentFilter as well
- Unregister with the unregisterReceiver() method
Broadcast Intents:
Registering a Broadcast Receiver:
In Application Manifest
BRs registered statically in the Application Manifest are always active.
They receive Broadcast Intents even when app is not active. Application will be started automatically when a matching Intent is broadcast.
- Add a <receiver> tag to the application node in the Manifest
</receiver><ul>
<li>Specify the class name of the receiver</li>
</ul></receiver> - Limited number of supported actions
Broadcast Intents:
How to Manage
Manifest Receivers at Run Time
Can Enable/Disable any of your app’s manifest Receivers at run time through the
Package Manager
- Use the setComponentEnabledSetting() method, parameters:
- Component Name(Receiver)
- State to set it in
- Option to kill app
- Enabled/Disabled states are defined in Package Manager:
- PackageManager.COMPONENT_ENABLED_STATE_ENABLED
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED
Broadcast Intents:
Common System Service
Broadcast Events
- Completion of device booting
- Time-Zone changes
- Changes to Dock state
- Battery Status
Broadcast Intents:
Dock Change event
Intent.ACTION_DOCK_EVENT
Broadcast Intents:
Battery Status Event
and
Associated Action strings
Intent.ACTION_BATTERY_CHANGED
Action Strings
(Appended to android.intent.action.):
- ACTION_BATTERY_LOW
- ACTION_BATTERY_OKAY
- ACTION_POWER_CONNECTED
- ACTION_POWER_DISCONNECTED
Broadcast Intents:
Event for changes in Network Connectivity
ConnectivityManager.CONNECTIVITY_ACTION
- Note: Apps targeting Android 7.0+ will not receive this broadcast if they declare Receiver in the Manifest
Local Broadcast Manager:
Overview
- Simplifies the process of registering for, sending and receiving Intents broadcast only within the application
- More efficient than sending a global Broadcast
- More secure
- Part of the Android Support Library
Local Broadcast Manager:
Getting an Instance of the Local Broadcast Manager
Use the static getInstance() method:
LocalBroadcastManager lbm =
LocalBroadcastManager.getInstance(this)
Local Broadcast Manager:
Register/Unregister Broadcast Receivers
- First, get an instance of the LocalBroadcastManager
- Register:
- Just like a global receiver, use the registerReceiver() method, passing in a Broadcast Receiver and Intent Filter
- lbm.registerReceiver( receiver, filter)
- Unregister:
- lbm.unregisterReceiver(receiver)
Pending Intents:
Overview
- Class: PendingIntent
- Provides a mechanism for creating Intents that can be fired later
- Fired by the system, or another application, at a later time
- Commonly used to package Intents that will be fired in response to a future event, like touching a notification
- Provides static methods to “package” a normal intent
Pending Intents:
Common constructing methods
in the PendingIntent class
-
Start an Activity
- PendingIntent.getActivity()
-
Start a Service
- PendingIntent.getService()
-
Start a Foreground Service
- PendingIntent.getForegroundService()
-
Broadcast an Intent to explicit Receiver
- PendingIntent.getBroadcast()
-
Broadcast an implicit Intent
- also PendingIntent.getBroadcast()
- Just pass an implicit Intent