Android Data Management and Networking
Challenge 9
1. How do preferences, files, and databases differ? Under what circumstances would each be appropriate?
Shared Preferences store key-value pairs in an XML file. This file can be read by other apps only if the MODE_WORLD_READABLE
or MODE_WORLD_WRITEABLE
mode is specified. Files are useful for writing larger amounts of information that might not be suited for shared preferences. Files can be stored in Internal Storage or External Storage (SD card). Databases are ideal for repeating or structured data.
2. What is the concept of a key-value set?
A key-value pair is an identifying name (key), which always corresponds to a set value associated with that name.
3. What are the data types supported by preferences?
Boolean, float, int, long, string.
Why are only these types supported?
It would be more challenging to store anything more complex than a primitive type within an XML file, let alone edit it.
Does this imply that instances of complex classes cannot be saved in preferences?
Yes.
4. What are the two methods for creating or accessing an existing shared preference file?
getSharedPreferences()
and getPreferences()
When would you use one versus the other?
Use getSharedPreferences()
if you need multiple shared preference files identified by a name. Use getPreferences()
if you use only one shared preference file for the activity; this retrieves a default shared preference file that belongs to the activity.
5. How are preferences read?
To read a preference, you must get the preference by using a PreferenceManager
and its getDefaultSharedPreferences()
function to get the preference’s shared preference file. After this, you can use the appropriate get
methods on the shared preference. For example:
SharedPreference pref = PreferenceManger.getDefaultSharedPreferences(this)
OR:
SharedPreferences pref = context.getSharedPreferences(filename, 0);
String test = pref.getString("name", "value");
6. What are the steps necessary to write a preference?
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Why is the mechanism of an “editor” necessary for writing preferences?
Editors are used so that users outside of the application can’t manipulate data.
7. What other applications can access a particular app’s preferences?
It depends on the specified mode:
MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
MODE_MULTI_PROCESS
8. How are one activity’s preferences shared with another activity?
You can pass the name of the sharedPreference file through an intent, or you can hardcode the name in the other activities.
9. What is PreferenceActivity? How does it simplify the handling of preferences? What are the pieces of information that are needed to make an instance of PreferenceActivity work?
PreferenceActivity is an extension of Activity
that automatically displays a list of settings based on the hierarchy of Preference objects. The activity automatically persists the settings associated with each preference when the user makes a change. A bare minimum of an XML file to hold all preferences is required in the onCreate()
method of a preference activity.
10. How are preferences stored on the device?
In XML files.
11. Why would a file be chosen over a preference?
A file can support larger data types than a preference.
12. How are files read and written?
With the java.io.reader
and java.io.writer
classes.
13. What file types can the file system handle?
XML, txt, binary
14. Where are files stored on the device?
Data/data//files
In what format?
XML or binary.
15. What should a developer keep in mind when writing files to a mobile device that has limited storage capabilities?
To be careful not to store too much data.
16. Can a file be shared among apps?
Yes, as long as the appropriate permissions are set.
Are access permissions enforced?
Yes.
If so, how does an app specify permissions?
On file creation.
17. How are files packaged with apps?
Files are stored in the data/data
directory. These files can be read but most cannot be changed.
18. What are the built-in features for dealing with XML files? What is the difference between handling an XML file as a DOM model versus a SAX model?
XMLPullParser, DOM, level 2 Core Support
19. What is SQLite?
SQLite is a single-file database that uses a subset of SQL, designed for high performance and ease of use.
What are the advantages of using it over, say, a “normal” relational database system such as MySQL?
It is more lightweight than a”norma” relational database, therefore gives higher performance.
Disadvantages?
You are limited to only a subset of SQL, also data type integrity is not maintained in SQLite as it is in SQL.
20. Where does Android place an application’s databases?
Data/data//databases/
21. What is the role of the following classes in working with databases: SQLiteDatabase, SQLiteOpenHelper, SQLiteQueryBuilder, Cursor, ContentValues?
SQLiteDatabase
encapsulates all of the methods associated with managing databases. SQLiteOpenHelper
manages database creation and version management. SQLiteQueryBuilder
is a convenience class that helps build SQL queries to be sent to the SQLiteDatabase
object. Cursor
provides random read-write access to the result set returned by a database query. ContentValues
is used to store a set of values.
22. How do you create an SQLite database?
Using the SQL statement CREATE TABLE
using execSQL(string)
Delete it?
Using the SQL statement DELETE TABLE
using execSQL(string)
23. How do you open and close a database?
With the SQLiteOpenHelper.getReadableDatabase
and getWriteableDatabase
methods.
24. How do you create a table within a database?
Create a static final String
with the correct SQL syntax to create the table, then pass the string to the .execSQL()
function.
25. How do you create (a.k.a. “insert”), update, and delete records in a database?
database.insert()
//function is used to build the proper INSERT statementdatabase.update()
//function is used to build the proper UPDATE statementdatabase.delete()
//function is used to build the proper DELETE statement
26. What is the purpose of the “WHERE” parameter to update()
and delete()
?
Used to filter the results of the query to the desired entry in the database.
27. How do you read (a.k.a. “query”) records from a database?
You can use the .query()
function, which will return a cursor, or .rawQuery()
.
28. Why does the lifecycle of instances of Cursor have to be managed? How is this accomplished?
The cursor needs to be managed with the application’s lifecycle. Use deactivate()
, requery()
, and close()
.
29. How do you iterate through a Cursor?
These functions can be used to iterate through the returned rows: .moveToNext()
, .moveToFirst()
, .moveToPrevious()
, .moveToLast()
.
30. Does SQLiteQueryBuilder have the expressive power of raw SQL statements? If no, what is it missing?
No, it doesn’t. It is missing the rawQuery()
function.
31. How can you execute raw SQL commands?
.rawQuery()
function.
32. What is the purpose of the BaseColumns interface?
It provides names for very common ID and COUNT columns.
33. What SQLiteOpenHelper methods can be used to manage the lifecycle of a database?
onCreate
, onUpgrade
, onOpen
, onDowngrade
34. What is the procedure for binding database data to a UI control?
Bind the data from the database to a control by using an adapter to populate the control’s data.
Challenge 10
1. What is the purpose of a content provider? What role does a content provider play in the Android environment?
Content providers manage access to a structured set of data. They encapsulate the data and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process. Android itself includes content providers that manage data such as audio, video, images, and personal contact information.
2. How do content providers present data to external applications? How does this compare/contrast with data presented by a relational database?
A content provider presents data to external applications as one or more tables that are similar to the tables found in a relational database. A row represents an instance of some type of data the provider collects, and each column in the row represents an individual piece of data collected for an instance.
3. What methods of ContentProvider must be implemented? These methods should account for what issues?
The abstract class ContentProvider
defines six abstract methods that you must implement as part of your own concrete subclass. All of these methods except onCreate()
are called by a client application that is attempting to access your content provider:
query()
: Retrieve data from your provider. Use the arguments to select the table to query, the rows and columns to return, and the sort order of the result. Return the data as aCursor
object.insert()
: Insert a new row into your provider. Use the arguments to select the destination table and to get the column values to use. Return a content URI for the newly-inserted row.update()
: Update existing rows in your provider. Use the arguments to select the table and rows to update and to get the updated column values. Return the number of rows updated.delete()
: Delete rows from your provider. Use the arguments to select the table and the rows to delete. Return the number of rows deleted.getType()
: Return the MIME type corresponding to a content URI.onCreate()
: Initialize your provider. The Android system calls this method immediately after it creates your provider. Notice that your provider is not created until aContentResolver
object tries to access it.
They should account for:
- All of these methods except
onCreate()
can be called by multiple threads at once, so they must be thread-safe. - Avoid doing lengthy operations in
onCreate()
. Defer initialization tasks until they are actually needed. - Although you must implement these methods, your code does not have to do anything except return the expected data type. For example, you may want to prevent other applications from inserting data into some tables. To do this, you can ignore the call to
insert()
and return 0.
4. What is the relationship between ContentProvider and ContentResolver?
An application accesses the data from a content provider with a ContentResolver
client object. This object has methods that call identically-named methods in the provider object, an instance of one of the concrete subclasses of ContentProvider
.
5. What basic functions does ContentResolver supply?
The ContentResolver
methods provide the basic”CRU” (create, retrieve, update, and delete) functions of persistent storage.
6. How does a content provider act as an abstraction layer between its data and the application manipulating the data?
ContentProvider
also acts as an abstraction layer between its repository of data and the external appearance of data as tables.
7. What must appear in the manifest of an application that requires an external content provider?
To get the permissions needed to access a provider, an application requests them with a <uses-permission>
element in its manifest file.
8. What is the purpose and function of a contract class?
A contract class defines constants that help applications work with the content URIs, column names, intent actions, and other features of a content provider.
9. What is a content URI? What is meant by the content URI scheme? The authority? The path? How does the content URI relate to a content provider? What is a content URI pattern and how is it used?
A content URI is a URI that identifies data in a provider. Content URIs include the symbolic name of the entire provider (its authority) and a name that points to a table (a path). When you call a client method to access a table in a provider, the content URI for the table is one of the arguments. The string content://
(the scheme) is always present and identifies this as a content URI. To help you choose which action to take for an incoming content URI, the provider API includes the convenience class UriMatcher
, which maps content URI”pattern” to integer values. You can use the integer values in a switch
statement that chooses the desired action for the content URI or URIs that match a particular pattern.
10. Why should code that retrieves information from a content provider be on its own thread and not the UI thread?
Your application may be blocked and become unresponsive.
11. What is a projection?
The set of columns that the query should return is called a projection.
12. What is the function of the Cursor class?
This interface provides random read-write access to the result set returned by a database query. Cursor
implementations are not required to be synchronized so code using a Cursor
from multiple threads should perform its own synchronization when using the Cursor
.
13. What is the purpose of the ContentValues class? How is it used?
This class is used to store a set of values that the ContentResolver
can process. To update a row, you use a ContentValues
object with the updated values just as you do with an insertion, and selection criteria just as you do with a query. The data for the new row goes into a single ContentValues
object, which is similar in form to a one-row cursor.
14. How is information retrieved from a content provider? Inserted? Updated? Deleted?
In the same way that you retrieve data from a provider, you also use the interaction between a provider client and the provider’s ContentProvider
to modify data. You call a method of ContentResolver
with arguments that are passed to the corresponding method of ContentProvider
. The provider and provider client automatically handle security and inter-process communication.
15. How do you request data based on specific criteria?
The ContentResolver.query()
client method always returns a Cursor
containing the columns specified by the query’s projection for the rows that match the query’s selection criteria. You use mSelectionClause
and mSelectionArgs
as arguments in the query()
call.
16. What is the purpose of the _ID column?
The column headers are column names that are stored in the provider. To refer to a row’s locale, you refer to its locale
column. For this provider, the _ID
column serves as a”primary ke” column that the provider automatically maintains.
17. How can you protect a content provider against malicious information retrieval requests?
To avoid this problem, use a selection clause that uses ?
as a replaceable parameter and a separate array of selection arguments. When you do this, the user input is bound directly to the query rather than being interpreted as part of an SQL statement. Because it’s not treated as SQL, the user input can’t inject malicious SQL.
18. What is a MIME type? How are MIME types used with content providers?
Providers also maintain MIME data type information for each content URI they define. You can use the MIME type information to find out if your application can handle data that the provider offers, or to choose a type of handling based on the MIME type. You usually need the MIME type when you are working with a provider that contains complex data structures or files.
Challenge 11
1. What are the following: TCP, IP, port, socket, HTTP, URL, client, server?
- TCP: The Transmission Control Protocol (TCP) is one of the two original core protocols of the Internet protocol suite (IP), and is so common that the entire suite is often called TCP/IP. TCP provides reliable, ordered, error-checked delivery of a stream of octets between programs running on computers connected to an intranet or the public Internet.
- IP: The Internet protocol suite is the set of communications protocols used for the Internet and similar networks, and generally the most popular protocol stack for wide area networks.
- Port: In computer networking, a port is an application-specific or process-specific software construct serving as a communications endpoint in a computer’s host operating system. A port is associated with an IP address of the host, as well as the type of protocol used for communication.
- Socket: A network socket is a network interface – an endpoint of an inter-process communication flow across a computer network.
- HTTP: The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. Hypertext is a multi-linear set of objects, building a network by using logical links (the so-called hyperlinks) between the nodes (e.g., text or words). HTTP is the protocol to exchange or transfer hypertext.
- URL: A uniform resource locator, abbreviated URL, also known as a web address, is a specific character string that constitutes a reference to a resource.
- Client: A client is a piece of computer hardware or software that accesses a service made available by a server.
- Server: In most common use, a server is a physical computer (a computer hardware system) dedicated to run one or more services (as a host) to serve the needs of the users of other computers on a network.
2. How does I/O via a network differ, conceptually, from I/O via a file?
You have to first create an HTTP connection before you can get the InputStream
, and also you must handle drops in network service.
3. What special provisions need to be made to access a network when installing an app to the mobile device?
You have to allow internet permissions and intent filters in the manifest.
4. What is the importance of offloading network I/O from the UI thread?
Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI.
5. Describe the role of a Thread in network communication. When is the thread started? What takes place while the thread is running? How does the thread signal that it has carried out its intended function?
A thread allows network communication to take place outside of the main UI thread to prevent the application from becoming unresponsive. The thread is started right before network communication takes place, and the actual communication takes place during the thread. The thread cannot signal that it is complete without a handler, or other method of dealing with output.
6. How does the AsyncTask class differ from the Thread class? What do the following AsyncTask methods do: onPreExecute()
, onPostExecute()
, doInBackground()
, onCancelled()
, onProgressUpdate()
?
AsyncTask
allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute()
: Invoked on the UI thread before the task is executed. This step is normally used to set up the task, for instance by showing a progress bar in the user interface.doInBackground(Params...)
: Invoked on the background thread immediately afteronPreExecute()
finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also usepublishProgress(Progress...)
to publish one or more units of progress. These values are published on the UI thread, in theonProgressUpdate(Progress...)
step.onProgressUpdate(Progress...)
: Invoked on the UI thread after a call topublishProgress(Progress...)
. The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.onPostExecute(Result)
: Invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
A task can be canceled at any time by invoking cancel(boolean)
. Invoking this method will cause subsequent calls to isCancelled()
to return true
. After invoking this method, onCancelled(Object)
, instead of onPostExecute(Object)
will be invoked after doInBackground(Object[])
returns.
7. How does a socket work? What role does the port play?
A socket is instantiated to listen for information being sent to a specified port. It acts as an entry point for information from the network.
8. Explain how to use the Socket and ServerSocket classes.
The ServerSocket
class is used on the server to create a socket bound to a given port on the server to receive and transmit data, and the Socket
class is used on the client side to do the same.
9. What is the role of the following URL components: protocol, authority, host, port, file, path, query, ref? Which components are case-sensitive?
Protocol | http | scheme |
Authority | username:password@host:8080 | |
User Info | username:password | |
Host | host | |
Port | 8080 | |
File | /directory/file?query | |
Path | /directory/file | |
Query | query | |
Ref | ref |
10. How can data be read from the web as an input stream using the URL class? Can data be written using an output stream?
You can initialize a new InputStream
to a new instance of the URL
class with the desired URL as a parameter and then call the url.openStream()
function.
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
11. What is the purpose of the HttpUrlConnection class? What information does an instance of HttpUrlConnection yield? How can HttpUrlConnection be used to reduce network access?
The HttpUrlConnection
class is used to send and receive data over the web. An instance of this class contains information regarding HTTP status and header information, length of the content, content type, and datetime information so that you can check to see if the data changed since the last time you accessed the URL. It can be used to check to see if the URL content is appropriate, and can also be used to approximate how long it will take to load a page based on page size (useful for loading bars).
12. POX (Plain Old XML) is a communication pattern in which a client pulls information in the form of XML from a server. Describe how to use an XML pull parser to retrieve POX data.
First, you must decide which fields you’re interested in, and the parser extracts data for those fields. Then you must instantiate a parser and kick off the parsing process. Start with a call to nextTag()
and read with readFeed()
, which recursively parses through the tags in the XML and builds a list containing all of the entries.
13. How are non-primitive types (such as bitmaps) read via the network?
(Not covered in the provided text.)
14. How can an app query the device’s network status?
Using getActiveNetworkInfo()
and isConnected()
.
Challenge 12
1. Compare and contrast toast notifications, status bar notifications, and dialog notifications.
Toast: Brief messages that come from the background. A message that pops up on the surface of the window. It only fills the amount of space required for the message and the user’s current activity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events.
Status bar notifications: Persistent reminders that come from the background and request the user’s response. Adds an icon to the system’s status bar (with an optional ticker-text message) and an expanded message in the “Notifications” window.
Dialog notifications: Activity-related notifications. Usually, a small window that appears in front of the current activity. The underlying activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications and short activities that directly relate to the application in progress.
Under what circumstances might each be used?
A toast would be used to provide information to the user in which no response is required. A status bar notification would be used to inform the user of something that requires their attention. A dialog notification would be used to focus the user’s attention on something that would require immediate acknowledgment and possibly a yes/no style response.
2. How can notifications get the user’s attention?
They can use textual information, graphical indicators, sound indicators, vibration, and control over the indicator light.
3. How can you test via the emulator a notification that vibrates the phone or blinks the device indicator light?
The emulator has no functionality to test these indicators.
4. What is a notification?
A way of making the user aware of something.
What is it typically used for?
Making the user aware of something.
5. What are the two notification views?
Normal View and Big View.
Under what circumstances would you choose one over the other?
You might choose a Big View if you need to display multiple lines of information.
6. What are the components of a notification?
Icon/Photo, Title/Name, Timestamp, Secondary Icon, Message.
7. How is a notification created?
Create a notification builder, assign it a unique ID, define the notification’s action, its click behavior, and then issue the notification using a notification manager.
Updated?
Use a notification builder, assign it the ID of the notification you would like to update, change its values and re-issue the notification using a notification manager.
Cleared?
Using a notification manager, call cancel
on the notification’s ID or cancelAll
. You can also use setAutoCancel()
before issuing the notification, which will cause it to be cleared when a user touches it.
8. What is the difference between a regular activity and a special activity with regard to notifications?
A special activity is only seen if it’s started from a notification. There’s no need to create a back stack because the special activity isn’t part of the application’s activity flow. A regular activity is part of an application’s normal workflow, so it is necessary for a coder to create a back stack to provide proper navigation away from the launched activity.
What roles do the back stack and the android.support.PARENT_ACTIVITY play in a regular notification?
It provides a proper activity flow for the launched activity to back out of.
9. What is the difference between an intent and a pending intent?
A pending intent is a token given to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code. If a foreign application launches an intent, it launches it with its own permissions.
What is the role of each in notifications?
(Not covered in the provided text.)
10. What is a dialog?
A dialog is a small window that prompts the user to make a decision or enter additional information.
What is it typically used for?
They are used for prompting the user for decisions or additional information required by the app to continue a task.
11. What are some of the most common dialogs?
Alert Dialog, ProgressDialog, DatePickerDialog, TimePickerDialog.
12. How is a dialog notification shown?
A dialog is always created and displayed as part of an Activity
. You should normally create dialogs from within your Activity
’s onCreateDialog(int)
callback method. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity
, effectively making it the “owner” of each dialog.
Dismissed?
When you’re ready to close your dialog, you can dismiss it by calling dismiss()
on the Dialog
object. If necessary, you can also call dismissDialog(int)
from the Activity
.
13. What types of UI controls can appear on, say, an Alert Dialog?
Title, Text, 1-3 Buttons, List of checkboxes/radio buttons.
How are they defined?
set...Button()
methods, setItems()
method, setMultiChoiceItems()
, and setSingleChoiceItems()
.
14. How can you customize a dialog layout?
You can use layout and widget elements. After you’ve defined your layout, pass the root View
object or layout resource ID to setContentView(View)
.
15. How is information passed from a dialog back to its host?
Define an interface with a method for each type of click event. Then implement that interface in the host component that will receive the action events from the dialog.
16. What is a toast notification? What is it typically used for?
A toast provides simple feedback about an operation in a small popup.
17. Where is the placement of the toast on the screen?
Near the bottom of the screen, centered horizontally.
18. Can an application that is not in the foreground issue a toast?
Yes.
19. How can you display your own customized toast?
Define a View
layout, in XML or in your application code, and pass the root View
object to the setView(View)
method.
20. Under what circumstances would an app that issues a notification, dialog, or toast have to have supporting information in the manifest?
If you want to display a dialog as an activity instead of using the dialog APIs, you could declare a theme in the manifest for that dialog.
Challenge 13
1. What manifest permissions are necessary to access phone state information?
The READ_PHONE_STATE
permission is required to retrieve information such as the call state, handset phone number, and device identifiers or serial numbers.
Make calls?
One way is to launch the dialer with a phone number already entered, which requires the user to press the Send button. The second way is to place the call using the ACTION_CALL
intent. To do this, create the intent, set the phone number with intent.setData
, and call startActivity(intent)
. This requires the CALL_PHONE
permission.
Abort calls?
(Not covered in the provided text.)
2. How do you determine if the device’s cell technology is CDMA or GSM?
By calling the TelephonyManager
’s getPhoneType()
function. It will return PHONE_TYPE_GSM
or PHONE_TYPE_CDMA
if the phone radio is GSM or CDMA.
How do you determine the device’s phone number?
By calling the TelephonyManager
’s getLine1Number()
function.
Network operator?
TelephonyManager
‘s getNetworkType()
function returns a constant indicating the network type currently in use.
SIM card presence?
TelephonyManager
’s getSimState()
function returns a constant indicating the state of the SIM card, including SIM_STATE_UNKNOWN
, or SIM_STATE_ABSENT
.
Changes in service?
TelephonyManager
’s getSimOperatorName()
function returns the Service Provider Name. The SIM state must be SIM_STATE_READY
.
Signal strength?
The Telephony.CellSignalStrength
class provides functions such as getAsLevel()
, getDbm()
, and getLevel()
.
3. What states can the phone be in? How can the state be determined?
States: CALL_STATE_IDLE
, CALL_STATE_OFFHOOK
, CALL_STATE_RINGING
. Create a new PhoneStateListener
and override its onCallStateChanged
method. Then just register the listener with your TelephonyManager
.
4. How do you make a call using the tel: URI?
Create a new ACTION_CALL
intent, and
set the phone number to call by using the intents setData function, and passing it the teluri – intent.setData(Uri.parse(tel:123456789)); and then start the activity.
How do you make a call using Intent.ACTION_DIAL?
This shows a UI with the number being dialed, allowing the user to explicitly initiate the call. If there is no input then an empty dialer is started. Otherwise, getData() is URI of phone number to be dialed or a tel: URI of an explicit phone number.
5. What is the difference between ACTION_DIAL and ACTION_CALL?
ACTION_CALL has more restrictions on which apps can use it. It brings up the dialer and calls, and requires a permission in the manifest.
Action dial only brings up the dialer.
6. How do you convert a string to a phone number?
??Refer to format phone numbers?
Format phone numbers?
You can pass a string to PhoneNumberUtils.formatNumber() to return a String that is a formatted
Compare phone numbers?
PhoneNumberUtils.compare() method on two strings. àPhoneNumberUtils.compare(String a, String b)
Determine if a phone number is global?
PhoneNumberUtils.isGlobalPhoneNumber(String phoneNumber) function
Determine if a number represents an emergency call?
PhoneNumberUtils.isEmergencyNumber(String number) function
7. How do you intercept inbound calls? Outbound calls?
Create a new PhoneStateListener and override it’sonCallStateChanged method. Then just register the listener with your TelephonyManager. Is the only way I’ve found.
8. What is the role of the BroadcastReceiver class in working with calls?
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active. BrodcastReceiver can be used to perform actions on certain phone events, and can also stop phone calls in earlier API’s.
9. What is SMS?
Stands for Short Message Service, commonly known as text messages.
10. What permissions are needed to send and receive SMS messages?
SEND_SMS and RECEIVE_SMS
11. How do you send an SMS message?
Get the default SmsManager and call it’s sendTextMessage() function
What information does SmsManager’ssendTextMessage() require?
The destination phone number, the source phone number, the message, the pending sent intent, and pending delivered intent.
12. What is the role of the PendingIntent class in working with SMS messages?
Used to check to see fi the text message was sent and checks to see if it was delivered.
13. How do you receive an SMS message?
You register a BroadcastReceiver to listen for the intent action associated with receiving an SMS using a filter SMS_RECEIVED.
14. What is the role of the BroadcastReceiver class in working with SMS messages?
Listen for the intent action associated with receiving an SMS
15. What is the SmsMessage class and what information does it provide?
A short message service message class used to get certain parts of a SMS message.
16. What is a PDU? What role does it play in SMS messages?
Protocol Description Unit – contains the message, and meta-information about the sender such as his SMS service center, the time stamp, etc. It is the data format that is customarily used by wireless messaging protocols.