Mad Module 5
Mad Module 5
Objective:
import android.app.Activity;
import android.widget.*; // for TextView, EditView and Button
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
We want the user-entered website URL loaded into webView when either of the following events
occurs:
• When the user presses the Enter key in the EditText control
• When the user clicks the Go button after entering the URL in the EditText control
To accomplish this, we need to associate a KeyListener with the EditText control and
a ClickListener with the Button control so that the onKey() callback method is called when any
key is pressed in the EditText control and the onClick() callback method is called when
a Click event occurs on the Button control. In the onKey() method, we check for two things:
• Whether the event that has occurred is connected to a keypress
• Whether the code of the pressed key matches that of the Enter key
The onKey() method checks for the occurrence of the Enter key in the EditText control. If
the Enter key is pressed, the URL of the site entered in the url EditText control is loaded and
displayed in the WebView control using the loadUrl() method.
----------------------------------------------------------------------------------------------
You need to sign up for the Google Maps API. Open the browser and go
to http://code.google.com/android/maps-api-signup.html. Follow the instructions on the page and
supply the extracted MD5 fingerprint to complete the signup process and obtain the Google Maps
key. After successful completion of the signup process, the Google Maps API key is displayed as
shown below.
Your key is:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This key is good for all apps signed with your certificate whose fingerprint is:
XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
Here is an example xml layout to get you started on your way to mapping glory:
<com.google.android.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
<com.google.android.maps.MapView
android:id="@+id/mapvw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"/>
To run the Google Maps-based Android application, we need an AVD that targets the Google API
platform, Before creating and running the application we ned to create an AVD that targets it.
The GoogleAppAVD is created and displayed in the list of existing AVDs in the Android SDK and AVD
dialog box. Click the Refresh button if the newly created AVD doesn’t show up in the list. Close the
Android SDK and AVD dialog.
Launch the Eclipse IDE and select the File, New, Android Project option to create a new Android
application. Name the project GoogleMapApp and select Google APIs (Google Inc.) (API
16) from the Build SDK drop-down list. Select API 16: Android 4.1 from the Minimum Required
SDK and click Finish after supplying all the pertinent information for the new project, as shown
in Figure 10.6.
Figure 10.6. The dialog box used to specify the information for the new Android project
To access Google Maps in our application, we have to add the following two statements to the
AndroidManifest.xml file:
• The first statement asks for permission to access the Internet:
<uses-permission android:name="android.permission.INTERNET" />
After we add these two code lines, the AndroidManifest.xml file appears as shown in Listing 10.6.
Only the code in bold is newly added; the rest is the default code.
After running the application, we see the output shown in Figure 10.7.
To implement the SMS Messaging facility in our application, Android provides a built-in class known as
SmsManager, which we can use to send and receive SMS messages.
For testing SMS messaging, we don’t need a real device but can easily test it on the Android emulator.
Step1: Design the user interface for sending messages via SMS
The user interface consists of following controls:
➢ Three TextView (for displaying the title of the screen, “To” Label and “SMS Message” Label ),
➢ Two EditText (to read receiver contact no and SMS message), and
➢ Two Button controls (for sending SMS or Cancel).
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView // Main Lable
android:text="SMS Sending Form"
android:layout_height ="wrap_content"
android:layout_width ="match_parent" />
<TextView // create To: contact number of the receiver
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To:" />
<EditText
android:id="@+id/recvr_No"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
The code defined in the activity_send_smsapp.xml layout file makes the user interface screen
appear as shown in Figure 11.3.
<uses-permission android:name="android.permission.SEND_SMS"/>
All, three communication mediums—SMS, email, and voice calls—use the concept of broadcast
receivers and notifications. So let’s first examine them.
Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 11
Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263
a) Broadcasting an Intent
To broadcast an Intent, we first create an Intent object, assign a specific action to it, attach data
or a message to the broadcast receiver, and finally broadcast it. We can optionally put an extra
message or data on the Intent. Table 11.1 lists the methods involved in broadcasting an Intent.
We can see that an Intent object called broadcastIntent is created. The data or message to be
passed along with the Intent is "New Email arrived", and the name or key assigned to this
message is message. The action string is made unique by using a namespace similar to a Java
class. We can see that the com.androidunleashed.testingbroadcast is assigned as an action to the
Intent. Finally, the broadcastIntent is sent or broadcasted and received by the broadcast receivers.
A broadcast receiver is a class that extends the BroadcastReceiver. It also needs to be registered as
a receiver in an Android application via the AndroidManifest.xml file or through code at runtime.
The broadcast receiver class needs to implement the onReceive() method. The following is sample
code of an onReceive() method:
The getAction() and getStringExtra() methods used here need some explanation:
o getAction() - Retrieves the action to be performed from the Intent object. It is the action that
indicates what task has to be performed on the data passed along with the Intent.
Syntax: getAction()
o getStringExtra() - Retrieves the extended data from the Intent.
Syntax: getStringExtra(String name)
where name represents the key or the name assigned to the value while adding data to the
Intentthrough the putExtra() method.
In the onReceive() method, we access the Intent object passed as a parameter. From the
Intentobject, we retrieve the action that is supposed to be performed. If the action to be performed
is not null and matches the one that is sent by the sender activity, the message or data passed
along with the Intent is extracted from the Intent and is logged.
Let’s create an Android project called BroadcastApp. In this application, a Button is displayed
with the caption Send Broadcast. After we click the Button, an Intent with a message is broadcast.
The broadcasted Intent is then received through a broadcast receiver, and the message sent with
the Intent is extracted and logged. To define a Button control, write the code shown in Listing
11.1 into the activity_broadcast_app.xml layout file.
Figure-5.3: The contacts information accessed from the device/emulator is displayed via ListView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools=http://schemas.android.com/tools
android:layout_height="match_parent” >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Content provider"
android:textSize="30dp" />
------
------
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Add Name"
android:onClick="onClickAddName"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText" />
------
------
</RelativeLayout>
o Defining Database
The database for the content provider that provide information on countries and the respective
STD code are created using the following constants.
static final String DB_NAME = "Countries.db";
static final String DB_TABLE = "stdinfo";
static final String DB_VERSION = 1;
static final String CREATE_TABLE = "CREATE TABLE" + DB_TABLE + (_id
INTEGER PRIMARY KEY AUTOINCREMENT, stdcode TEXT not null);”
public static final String ID = "_id";
public static final String COUNTRY = "country";
static final String DB_NAME = "stdcode";
content://authority/path
Following are the details about various parts of an URI in android application.
o content:// - The string content:// is always present in the URI and it is used to represent the
given URI is a content URI.
o authority - It represents the name of content provider, for example phone, contacts, etc. and
we need to use a fully qualified name for third party content providers like
com.tutlane.contactprovider
o path - It represents the table’s path.
content://contacts_info/users
Here the string content:// is used to represent URI is a content URI, contacts_info string is the
name of the provider’s authority and users string is the table’s path.
We can perform multiple operations like insert, update, delete and edit on the data stored in
content provider using insert(), update(), delete() and query() methods.
where,
Uri - Uri maps to the table in the provider named table_name.
Projection - projection is an array of columns that is included for each row retrieved.
Selection - selection specifies the criteria for selecting rows.
selectionArgs - placeholders in the selection clause.
sortOrder - sortOrder specifies the order in which rows appear in the returned Cursor.
− Like any other main portions of Android application, we need to register the content providers too
in the AndroidManifest.xml.
− <provider> part is used to register the content providers. <application> is its parent component.
<provider android:name="com.tag.customContentproviderdemo.PlatesContentProvider"
android:authorities ="com.tag.custom_contentproviderdemo.Plates" >
</provider>
− A service is a component which runs in the background without direct interaction with the user.
As the service has no user interface, it is not bound to the lifecycle of an activity.
− Services are used for repetitive and potentially long running operations, i.e., Internet
downloads, checking for new data, data processing, updating content providers and the like.
• Types of Services
1. Foreground services:
These services keep the user informed about the progress of its ongoing operations. Like - when
you are downloading a file, you can see how much your file has been downloaded and can also
pause/resume the download. You can interact with Foreground services by responding to the
notification about the ongoing task.
2. Background services:
As the name suggests, these services run in the background and don't need user interaction.
Unlike Foreground Services, Background services don't notify the user about its ongoing task.
You might have seen a notification for data syncing in your mobile device, which generally occurs
after a specified period of time, to sync your mobile data.
3. Bound services:
Bound Service allows activities or any other application components to bound them to it. Multiple
activities can bind themselves to one Bound Service. Upon unbinding all the activities,
the service gets destroyed automatically.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background
and then synchronize again with our main thread. This class will override at least one method i.e
doInBackground(Params) and most often will override second method onPostExecute(Result).
Every Android application must include a version number to inform users about the enhanced or
improved versions of the application if any. Also, we must define the version name, label, and
icon of the application. The attributes used in the AndroidManifest.xml file to define the version
number, name, label, and icon of the application are as follows:
− android:versionCode
Written within the <manifest> element, this attribute represents the version number of our
application. Usually, we begin with version 1, and with every revised version of the
application, we increment the value by 1. The android:versionCode attribute is used by
Google Play to determine whether a newer version of your application is available.
− android:versionName
Written within the <manifest> element, this attribute contains versioning information that is
visible to users. The versioning information is provided in any format that the developer
chooses. The common format is <major>.<minor>.<point>. For example, the
versionName="1.0.0" indicates the versioning information of the application that is published
for the first time. If the application is upgraded drastically, the <major> value is incremented
by 1 making the versionName as "2.0.0". If small enhancements are made, either
the <minor> or <point> value is incremented by 1, setting the versionName as "1.1.0" or
“1.0.1".
− android:icon
Written within the <application> element, this attribute represents the icon of the application.
− android:label
Written within the <application> element, this attribute represents the name of our application.
After we set the preceding attributes, our AndroidManifest.xml file may appear as shown
in Listing 14.1.
<uses-sdk
android:minSdkVersion = "8"
android:targetSdkVersion = "16" />
<application
android:icon = "@drawable/ic_launcher"
android:label = "@string/app_name" >
<activity
android:name=".CreateServiceAppActivity"
android:label="@string/title_activity_create_service_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".HandleService" >
<intent-filter>
<action android:name="com.androidunleashed.handleservice" />
</intent-filter>
</service>
</application>
</manifest>
Also, to inform the user about the minimum version of the Android OS required to run the
application, the android:minSdkVersion attribute is used. The following statement indicates that
the application requires the minimum SDK version "8" to run the application:
1. Select the Android project in the Package Explorer window and select the File, Export option
or right-click the project in the Package Explorer window and select the Export option.
2. In the Export dialog, expand the Android item and select Export Android Application.
Click Next.
3. Our Android project name, CreateServiceApp, is displayed in the Project box. Click Next.
4. The next dialog prompts us to either select an existing keystore or create a new one. Select
the Create new keystore option to create a new certificate, that is, keystore, for our application.
In the Location box, specify the name and path of the keystore. Assign the name
as CreateService to our new keystore. In the Password and Confirm boxes, enter the password to
protect the keystore. After entering the password (see Figure 14.1), click Next.
Figure 14.1. The Export Android Application dialog for entering keystore information
5. Provide an alias for the private key and enter a password to protect the private key (see Figure
14.2). Applications published on Google Play require a certificate with a validity period
ending after October 22, 2033. Hence, enter a number that is greater than 2033 minus the
current year in the Validity box. Also fill the First and Last Name box with your name and
click Next.
6. Enter a path to store the destination APK file (see Figure 14.3). Click Finish.
For uploading applications to the Google Play, we need to first create a developer account. To do
so, we need to have a Google account, for example, an email account in gmail.com. Then, we
create a developer account by signing up at the https://play.google.com/apps/publish/signup. We
get the Android Developer Console at the given URL. The Developer Console is used for
managing our applications in Google Play (see Figure 14.4).
The next screen prompts us to pay a one-time registration fee of $25 to complete the registration.
After creating a developer account, we see the screen shown in Figure 14.5, which enables us to
upload our application(s) so that users can find and download them.