0% found this document useful (0 votes)
7 views27 pages

Mad Module 5

This document discusses displaying web pages and maps in mobile applications. It describes using a WebView widget to display web pages within an activity layout. It also covers obtaining a Google Maps API key, installing the Google API, and creating an Android Virtual Device (AVD) targeted at the Google API to test maps-based applications. Code examples are provided to load a URL into a WebView when the user presses enter or clicks a button, and for displaying a map using the user's Google Maps API key.

Uploaded by

disij75096
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views27 pages

Mad Module 5

This document discusses displaying web pages and maps in mobile applications. It describes using a WebView widget to display web pages within an activity layout. It also covers obtaining a Google Maps API key, installing the Google API, and creating an Android Virtual Device (AVD) targeted at the Google API to test maps-based applications. Code examples are provided to load a URL into a WebView when the user presses enter or clicks a button, and for displaying a map using the user's Google Maps API key.

Uploaded by

disij75096
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Mobile Application Development

MODULE – 5: Displaying web pages and maps 22MCA263

Objective:

5). Displaying web pages and maps

5.1. Communicating with SMS and emails

5.2. Creating and using content providers

5.3. Creating and consuming services,

5.4. Publishing android applications

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 1


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

5). Displaying web pages and maps

a) Displaying Web Pages


WebView is a widget commonly used for viewing web applications or pages. It displays web pages as a
part of our activity layout.
Example:
Let’s make a small browser application that prompts the user to enter the URL of a website, and
then loads and displays it through the WebView control.
In this application, we use following controls

• TextView: displays the label Address:


• EditText: to read URL
• Button: To read URL and load to WebView
• WebView: Displays Website for given URL.

Listing 10.1. Code Written into the activity_web_view_app.xml Layout File


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Address:"/>
<EditText
android:id="@+id/web_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint = http:// />
<Button
android:id="@+id/go_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
/>
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 2


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

Modify the Java activity file WebViewAppActivity.java

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;

public class WebViewAppActivity extends Activity implements OnClickListener {


EditText url;
WebView webView;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_web_view_app);
url = (EditText) this.findViewById (R.id.web_url);
webView = (WebView) findViewById (R.id.web_view);
webView.setInitialScale(50);
url.setOnKeyListener (new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode ==
KeyEvent.KEYCODE_ENTER)) {
webView.loadUrl(url.getText().toString());
return true;
}
return false;
}
});
Button b = (Button)this.findViewById(R.id.go_btn);
b.setOnClickListener(this);
}
@Override
public void onClick (View v) {
webView.loadUrl(url.getText().toString());
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyUp(keyCode, event);
}
}

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 3


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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.

----------------------------------------------------------------------------------------------

b) Using Google Maps


To access Google Maps in our Android application, we need to have a Google Maps API key first.

Step1: Obtaining a Google Maps API Key

The steps for obtaining a Google key are as follows:


1. To get a Google key, the application needs to be signed with a certificate and you need to notify
Google about the Hash (MD5) fingerprint of the certificate. To test the application on the Android
emulator, search for the SDK debug certificate located in the default
folder: C:\Users\<user_name>\.android. The filename of the debug certificate is debug.keystore. For
deploying to a real Android device, substitute the debug.keystore file with your own keystore file.
2. Copy the debug.keystore to any drive.
3. Using the debug keystore certificate, extract its MD5 fingerprint using the keytool.exe application
provided with the JDK installation. This fingerprint is needed to apply for the free Google Maps key.
The keytool.exe file can be found in the C:\Program Files\Java\jdk_version_number\bin folder.
4. Open the command prompt and go to the
C:\ProgramFiles\Java\jdk_version_number\bin
folder using the CD command.
5. Issue the following command to extract the MD5 fingerprint:

keytool.exe -list -alias androiddebugkey -keystore "E:\debug.keystore" -store-


pass android -keypass android

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 4


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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"/>

Step2: Installing the Google API


For building Google Map-based applications, we need to install the Google API. To confirm that
it is actually installed, select the Window, Android SDK Manager option. A dialog box opens
showing the status of packages and tools on your machine (see Figure 10.4). If the Google API is
not yet installed, you can select it in the Android SDK Manager window and then click the Install
package button.

Figure 10.4. The Android SDK Manager window

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 5


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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.

Step3: AVDs for Map-Based Applications


We need to create a separate AVD to try out Google Maps-based applications. To create a new
AVD, select Window, AVD Manager to open the AVD Manager dialog box. The dialog displays
a list of existing AVDs. Click the New button to define a new AVD. A Create new Android
Virtual Device (AVD) dialog box opens where we can specify information about the new AVD.
Set the Name as GoogleAppAVD to indicate that it is a virtual device to run Google Map-based
applications. Choose Google APIs (Google Inc.)—API Level 16 for the Target, set SD Card to 64
MiB, and leave the Default (WVGA800) for Skin. Also keep the default in the Hardware section.
Using the New button, we can set the GPS support property. Besides the GPS support, we can
also add several other properties that we want our AVD to emulate, such as Abstracted LCD
density, DPad support, Accelerometer, and Maximum horizontal camera pixels. Finally, click
the Create AVD button (see Figure 10.5) to create the virtual device called GoogleAppAVD.

Figure 10.5. Creating a new AVD

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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 6


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

Step4: Creating a Google Maps-Based Application

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" />

• The second statement includes the Android map library:


<uses-library android:name="com.google.android.maps" />

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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 7


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

Figure 10.7. The application showing the startup Google map

5.1. Communicating with SMS and emails

5.1.1. SENDING SMS MESSAGES WITH JAVA CODE

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.

Steps to Create a new Android project called SendSMSApp:


➢ Design the user interface for sending messages via SMS.
➢ Getting Permission to Send SMS Messages
➢ Receive SMS messages.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 8


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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).

USER Interface: Listing 11.10. Code Written into activity_send_smsapp.xml

<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" />

<TextView // create To: address (email address of the receiver)


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Message" />
<EditText
android:id="@+id/SMS_text"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/Send_sms"
android:text="Send SMS"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
<Button
android:id="@+id/Send_sms"
android:text="Cancel"
android:layout_height="wrap_content"
android:layout_width="match_parent" />
</RelativeLayout>
</LinearLayout>

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 9


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

The code defined in the activity_send_smsapp.xml layout file makes the user interface screen
appear as shown in Figure 11.3.

Step2: Getting Permission to Send SMS Messages


To send and receive SMS messages in an application, we need to use permissions. All the
permissions our application uses are defined in the AndroidManifest.xml file, so that when the
application is installed on a device, the user is informed of the access permissions that the
application uses.

<uses-permission android:name="android.permission.SEND_SMS"/>

Step3: RECEIVING SMS MESSAGES


Create a new Android project called ReceiveSMSApp. When a device receives a new SMS
message, a new broadcast Intent is fired with the android.provider.Telephony.SMS_RECEIVED
action. To listen for this action, our application must register a BroadcastReceiver.
public class ReceiverSMS extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras(); SmsMessage[]
msg = null;
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msg = new SmsMessage[pdus.length];
for (int i=0; i<msg.length; i++){
msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS Received from: " + msg[i].getOriginatingAddress();
str += ":";
str += msg[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 10


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

5.1.2. SENDING EMAIL


To send an email with Android, we use the following Intent:
Intent.ACTION_SEND
The Intent.ACTION_SEND calls an existing email client to send an email. So, for sending email through
the Android emulator, we need to first configure the email client. If the email client is not configured, the
emulator does not respond to the Intent. Through the ACTION_SEND Intent, messages of different types,
such as text or image, can be sent.
For example, the following statement declares that the text data type will be sent through the Intent:
emailIntent.setType("plain/text");
The emailIntent is the Intent.ACTION_SEND object. After we launch this Intent, any application on the
device that supports plain text messaging may handle this request. To let a user choose the email client to
handle the Intent, we call startActivity() with the createChooser() method. As the name suggests, the
createChooser() method prompts the user to choose the application to handle the Intent. This statement
shows how to call startActivity() with the createChooser()method:
startActivity(Intent.createChooser(emailIntent, "Sending Email"));
This statement displays all the applications that are eligible to handle the Intent, allowing the user to
choose the application to launch. If there is only one application able to handle the Intent, it is launched
automatically without prompting the user. To supply data for the email message fields, we set certain
standard extras for the Intent.
For example, we can set the following:
✓ EXTRA_EMAIL—Sets the To: address (email address of the receiver)
✓ EXTRA_CC—Sets the Cc: address (email address of the carbon copy receiver)
✓ EXTRA_BCC—Sets the Bcc: address (email address of the blind carbon copy receiver)
✓ EXTRA_SUBJECT—Sets the Subject of the email
✓ EXTRA_TEXT—Sets the body of the email After setting the desired Intent’s extras, launch
the activity to initiate the sending email task.
Before we go ahead and create an application for sending email, let’s configure the email client of the
Android emulator in these steps:
✓ Start the emulator and then click on the Menu button.
✓ Click on the System settings option.
✓ Perform Account setup form where we need to enter our existing Email ID and password (see Figure
11.11—right) followed by clicking the Next button.

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

5.1.3. UNDERSTANDING BROADCAST RECEIVERS


A broadcast receiver is a component that responds to different messages that are broadcast by the
system or other applications. Messages such as new mail, low battery, captured photo, or
completed download require attention. Such messages are broadcast as an Intent object that is
waiting for broadcast receivers to respond. The broadcast receiver responds to such broadcasted
Intents and takes the necessary actions. The broadcast receivers can, for example, create a status
bar notification to alert the user when a broadcast occurs.
We cover two separate aspects of broadcast receivers:
➢ Broadcasting an Intent
➢ Receiving the broadcast Intent

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.

Table 11.1. Methods Involved in Broadcasting an Intent

The following code broadcasts an Intent:

public static String BROADCAST_STRING = "com.androidunleashed.testingbroadcast";


Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("message", "New Email arrived");
roadcastIntent.setAction(BROADCAST_STRING);
sendBroadcast(broadcastIntent);

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 12


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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.

b) Receiving the Broadcast Intent

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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 13


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

5.2. Creating and using content providers

• What Is a Content Provider


− A content provider acts as a data store and provides an interface to access its contents.
− It encapsulate data and provide it to applications through the
single ContentResolver interface.
− A content provider is only required if you need to share data between multiple applications.
− Example: the contacts data is used by multiple applications and must be stored in a content
provider. If you don't need to share data amongst multiple applications you can use a
database directly via SQLiteDatabase.

• Characteristics of Content Provider


− Like the database we can query, add, edit, delete and update data in content provider.
− Content providers are not limited to texts, but also contains images and videos as well.
− Data can be stored in a data base, files and over a network.
− Content providers act as wrapper, that is data in Content providers is exposed as service.

Figure-5.1: content provider in Android

• Using Content Providers : Accessing contact information.


− How to insert contact information.
✓ Contact are named as people in the emulator
✓ To access contact information click people icon on home screen as shown in figure 5.2
✓ A page is displayed as showing “no contacts exists”
✓ Three buttons are displayed on the screen: “create a new contact”, “sign into an account”,
and “import contacts”
✓ Select create new contact and enter relevant information on the dialog box that appears.
✓ Once all contacts added, The contacts information accessed from the device/emulator is
displayed vis ListView as shown in figure 5.3

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 14


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

Figure-5.2: Accessing Contact information

Figure-5.3: The contacts information accessed from the device/emulator is displayed via ListView

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 15


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

• Creating a custom Content Providers :


− Steps taken to create our own Content provider.
o Define the content provider.
o Define the database, URIs, column names, MIME types.
o Implement the query (insert/update/delete)
o Register the provider in a manifest file.

a) Step1: Define the content provider.


− To define content provider, lets create new Android project.
− On startup to display the user interface create the xml lay out file as

<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>

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 16


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

b) Step2: Defining database and URI.

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";

o Defining the content URIs


In android, to fetch data from content provider, a suitable URI is required.
Generally, the format of URI in android applications will be like as shown below

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.

Following is the example of a simple example of URI in android applications.

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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 17


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

c) Step3: Implement the Query

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.

Format of the query method is


@Override
public Cursor query(Uri uri, String[] projection,
String selection,String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(STUDENTS_TABLE_NAME);

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.

d) Step4: Register content provider

− 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>

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 18


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

5.3. Creating and consuming services,

• What are services?

− 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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 19


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

• Two ways of moving task to background


− Using Handler class
− Using AsyncTask class

a) Using Handler class

We mainly use the Handlers to


− Update the User Interface from a background thread,
− Enqueue a task for a different thread
− Schedule a task for a specified time.

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;

public class HandlerAppActivity extends Activity {


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seqView = (TextView)findViewById(R.id.sequenceView);
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
seqView.setText(msg.obj.toString());
}
}
};

Protected void onStart () {


void mMessageSender = new Runnable() {
public void run() {
-------
--------
}
}
Thread.start();
}

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 20


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

b) Using AsyncTask class

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).

Syntax of AsyncTask class:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {


protected Long doInBackground (URL... urls) {
// code that will run in the background
return ;
}

protected void onProgressUpdate (Integer... progress) {


// receive progress updates from doInBackground
}

protected void onPostExecute (Long result) {


// update the UI after background processes completes
}
}

Method of AsyncTask In Android:


1. doInBackground(Params) – This method is invoked on the background thread immediately
after onPreExecute() finishes its execution. Main purpose of this method is to perform the
background operations that can take a long time. The result of the operations must be returned
by this step and it will be passed back to the last step/method i.e onPostExecutes().
2. onProgressUpdate(Progress…) – This method is invoked on the main UI thread after a call
to publishProgress(Progress…). Timing of the execution is undefined. This method is used to
display any form of progress in the user interface while the background operations are
executing. We can also update our progress status for good user experience.
3. onPostExecute(Result) – This method is invoked on the main UI thread after the background
operation finishes in the doInBackground method. The result of the background operation is
passed to this step as a parameter and then we can easily update our UI to show the results.
4. onPreExecute() – It invoked on the main UI thread before the task is executed. This method
is mainly used to setup the task for instance by showing a ProgressBar or ProgressDialog in
the UI(user interface).

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 21


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

5.4. Publishing android applications

Following are the steps to publish an Android application:

1. Setting the versioning information of the application.


2. Generate a certificate: Digitally sign the Android application and generate the APK
(Android Package) file.
3. Distribute to Google Play or other marketplace to host and sell the application.

Sep1: Setting Versioning Information of an Application

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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 22


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

After we set the preceding attributes, our AndroidManifest.xml file may appear as shown
in Listing 14.1.

<manifest xmlns:android = "http://schemas.android.com/apk/res/android"


package = "com.androidunleashed.createserviceapp"
android:versionCode = "1"
android:versionName = "1.0" >

<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:

<uses-sdk android:minSdkVersion="8" />

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 23


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

Brief Description of the <uses-feature>, <uses-configuration>, and <uses-permissions> Tags

Step2: Signing Applications Using the Export Android Application Wizard

To launch the wizard, follow these steps:

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.

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 24


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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.

Figure 14.2. Dialog prompting information for key creation

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 25


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

6. Enter a path to store the destination APK file (see Figure 14.3). Click Finish.

Step3: Distributing Applications with Google Play

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).

Figure 14.4. Form for creating developer account on Google Play

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 26


Mobile Application Development
MODULE – 5: Displaying web pages and maps 22MCA263

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.

Figure 14.5. Screen after creating a developer account on Google Play

Mr. Vishwanath Murthy, Dept of MCA, RNSIT Page 27

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy