0% found this document useful (0 votes)
107 views7 pages

Mobile Application Development Unit 3

Uploaded by

dibashkhanal111
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)
107 views7 pages

Mobile Application Development Unit 3

Uploaded by

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

Mobile Application Development

Unit 3. Intents, Broadcast Receivers, Adapters, and the Internet


3.1 Introducing Intents
An Intent is an messaging object you can use to request an action from another app component.
Intents are used as a message-passing mechanism that works both within your application and
between applications. Although intents facilitate communication between components in several
ways, there are three fundamental use cases:
➢ Explicitly start a particular Service or Activity using its class name.
➢ Start an Activity or Service to perform an action with (or on) a particular piece of data.
➢ Broadcast that an event has occurred.

You can use Intents to support interaction among any of the application components installed on an
Android device, no matter which application they’re a part of. This turns your device from a
platform containing a collection of independent components into a single, interconnected system.

3.2 Using Intents to Launch Activities


The most common use of Intents is to bind your application components and communicate between
them. Intents are used to start Activities, allowing you to create a workflow of different screens.
An Activity represents a single screen in an app. You can start a new instance of an Activity by
passing an Intent to startActivity(). The Intent describes the activity to start and carries any
necessary data.
If you want to receive a result from the activity when it finishes, call startActivityForResult(). Your
activity receives the result as a separate Intent object in your activity's onActivityResult() callback.
For more information, see the Activities guide.

To create and display an Activity, call startActivity, passing in an Intent, as follows:


Intent myIntent = new Intent(getApplicationContext(), MyActivity.class);
startActivity(myIntent);
The startActivity method finds and starts the single Activity that best matches your Intent.

3.3 Using Intent Filters for plug-ins and Extensibility


An intent filter is an expression in an app's manifest file that specifies the type of intents that the
component would like to receive. For instance, by declaring an intent filter for an activity, you make
it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you
do not declare any intent filters for an activity, then it can be started only with an explicit intent.

Android provides a plug-in model that lets your applications take advantage of functionality,
provided anonymously from your own or third-party application components you haven’t yet
conceived of, without your having to modify or recompile your projects.

Supplying Anonymous Actions to Applications


To use this mechanism to make your Activity’s actions available anonymously for existing
applications, publish them using intent-filter tags within their manifest nodes, as described earlier.

The Intent Filter describes the action it performs and the data upon which it can be performed. The
latter will be used during the intent-resolution process to determine when this action should be
available. The category tag must be either ALTERNATIVE or SELECTED_ALTERNATIVE, or
both. The android:label attribute should be a human-readable label that describes the action.
Following code shows an example of an Intent Filter used to advertise an Activity’s capability to
nuke Moon bases from orbit.

<activity android:name=”.NostromoController”>
<intent-filter
android:label=”@string/Nuke_From_Orbit”>
<action android:name=”com.pad.nostromo.NUKE_FROM_ORBIT”/>
<data android:mimeType=”vnd.moonbase.cursor.item/*”/>
<category android:name=”android.intent.category.ALTERNATIVE”/>
<category
android:name=”android.intent.category.SELECTED_ALTERNATIVE”
/>
</intent-filter>
</activity>

Discovering New Actions from Third-Party Intent Receivers


Using the Package Manager, you can create an Intent that specifies a type of data and a category of
action, and have the system return a list of Activities capable of performing an action on that data.

This provides you with the ability to retrofit functionality to your application when you create new
components capable of performing actions on a given type of data. Many of Android’s native
applications use this functionality, enabling you to provide additional actions to native Activities.

3.4 Using Intents to Broadcast Events


To broadcast events using intents, you can:
1. Construct the intent you want to broadcast within your application component.
2. Set the action, data, and category of your intent.
3. Use the sendBroadcast method to send the intent.

The broadcast message is wrapped in an Intent object. The intent's action string must provide the
app's Java package name syntax and uniquely identify the broadcast event. You can attach
additional information to the intent with putExtra(String, Bundle).

The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is
called a Normal Broadcast.

Broadcast intents are intents that are broadcasted throughout the system. Registered applications
receive these intents and take actions accordingly.

The following code snippet demonstrates how to send a broadcast by creating an Intent and calling
sendBroadcast(Intent).

Intent intent = new Intent();


intent.setAction("com.example.broadcast.MY_BROADCAST");
intent.putExtra("data", "Some test data.");
sendBroadcast(intent);

The Android system automatically sends broadcasts when various system events occur, such as
when the system switches in and out of airplane mode.
Listening for Broadcasts with Broadcast Receivers
Broadcast Receivers (commonly referred to simply as Receivers) are used to listen for Broadcast
Intents. For a Receiver to receive broadcasts, it must be registered, either in code or within the
application manifest. We then use an IntentFilter to specify which Intent actions and data our
Receiver is listening for.

To create a new Broadcast Receiver, extend the BroadcastReceiver class and override the onReceive
event handler:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBroadcastReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
//TODO: React to the Intent received.
}
}

The onReceive method will be executed on the main application thread when a Broadcast Intent
is received that matches the Intent Filter used to register the Receiver.

To include a Broadcast Receiver in the application manifest, add a receiver tag within the appli-
cation node, specifying the class name of the Broadcast Receiver to register. The receiver node
needs to include an intent-filter tag that specifies the action string being listened for.
<receiver android:name=”.MyBroadcastReceiver”>
<intent-filter>
<action android:name=”com.example.broadcast.MY_BROADCAST”/>
</intent-filter>
</receiver>

3.5 Introducing Adapters


Adapters are used to bind data to View Groups that extend the AdapterView class (such as List
View or Gallery). Adapters are responsible for creating child Views that represent the underlying
data within the bound parent View.

You can create your own Adapter classes and build your own AdapterView derived controls.

Android supplies a set of Adapters that can pump data from common data sources(including Arrays
and Cursors) into the native controls that extend Adapter View.
Because Adapters are responsible both for supplying the data and for creating the Views that
represent each item, Adapters can radically modify the appearance and functionality of the controls
they’re bound to.

The following list highlights two of the most useful and versatile native Adapters:
• ArrayAdapter: The Array Adapter uses generics to bind an Adapter View to an array of
objects of the specified class. By default, the Array Adapter uses the toString value of each
object in the array to create and populate Text Views. Alternative constructors enable us to
use more complex layouts, or we can extend the class to bind data to more complicated
layouts.
• SimpleCursorAdapter: The Simple Cursor Adapter enables us to bind the Views within a
layout to specific columns contained within a Cursor. We can specify an XML layout to
inflate and populate to display each child, and then bind each column in the Cursor to a
particular View within that layout. The adapter will create a new View for each Cursor entry
and inflate the layout into it, populating each View within the layout using the Cursor’s
corresponding column value.

3.6 Using Adapters for Data Binding

Using ArrayAdapter:
To apply an Adapter to an AdapterView-derived class, call the View’s setAdapter method, passing
in an Adapter instance, as shown in the following example:

ArrayList<String> myStringArray = new ArrayList<String>();


int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter<String> myAdapterInstance;
myAdapterInstance =
new ArrayAdapter<String>(this, layoutID, myStringArray);
myListView.setAdapter(myAdapterInstance);

This snippet shows the simplest case, in which the array being bound contains Strings and each List
View item is represented by a single Text View.

Using SimpleCursorAdapter:
The SimpleCursorAdapter is used to bind a Cursor (result set from a database query or content
provider) to an Adapter View using a layout to define the UI of each row/item. The content of each
row’s View is populated using the column values of the corresponding row in the underlying
Cursor.

Construct a Simple Cursor Adapter by passing in the current context, a layout resource to use for
each item, a Cursor that represents the data to display, and two integer arrays: one that contains the
indexes of the columns from which to source the data, and a second (equally sized) array that
contains resource IDs to specify which Views within the layout should be used to display the
contents of the corresponding columns.

SimpleCursorAdapter is deprecated, that means it is no longer used.

Example:

// Assuming you have a Cursor from a database query


Cursor cursor = //...

// Define the columns you want to bind


String[] fromColumns = {YourDatabaseHelper.COLUMN_NAME1,
YourDatabaseHelper.COLUMN_NAME2};

// Define the corresponding views in the layout


int[] toViews = {R.id.textView1, R.id.textView2};

// Create a SimpleCursorAdapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
context,
R.layout.your_list_item_layout,
cursor,
fromColumns,
toViews,
0
);

// Set the adapter to your ListView


ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);

3.7 Using Internet Resources


When working with Android development and Internet resources, you may often need to interact
with web services, fetch data, or download content. Android offers several ways to leverage Internet
resources.

With Internet connectivity and WebKit browser, we might think if there’s any reason to create
native Internet-based applications when we could make web-based version instead.
There are a number of benefits to creating client native applications rather than relying on entirely
web-based solutions.
Benefits of native application over web-based solution:
• Bandwidth: Bandwidth is the amount of data that can be transferred through communication
channel per second. Static resources such as images, layouts, and sounds can be expensive
on devices with bandwidth restraints. By creating a native application, you can limit the
bandwidth requirements to changed(user) data only.
• Caching: With a browser-based solution, a patchy Internet connection can result in
intermittent application availability. A native application can cache data and user actions to
provide as much functionality as possible without a live connection and synchronize with
the cloud when a connection is reestablished.
• Reducing battery drain: Each time your application opens a connection to a server, the
wireless radio will be turned on (or kept on). A native application can bundle its
connections, minimizing the number of connections initiated. The longer the period between
network requests, the longer the wireless radio can be left off.
• Native features:Android devices are more than simple platforms for running a browser. They
include location-based services, Notifications, widgets, camera hardware, background
Services, and hardware sensors. By creating a native application, you can combine the data
available online with the hardware features available on the device to provide a richer user
experience.

Android provides two connection techniques for Internet connectivity. Each is offered transparently
to the application layer.
• Mobile Internet: GPRS, EDGE, 3G, 4G, and LTE Internet access is available through
carriers that offer mobile data.
• WiFi: Wi-Fi receivers and mobile hotspots are becoming increasingly common.

We have to optimize the user experience by limiting the quantity of data transmitted and ensure that
our application is robust enough to handle network outages and bandwidth limitations.
3.8 Connecting to an Internet Resource

To perform network operations in our application, our manifest must include the following
permissions:
<uses-permission android:name="android.permission.INTERNET" />

To build network connected apps, we will use HTTP to send or receive data over internet. The
Android platform includes the HttpURLConnection client, which supports TLS, streaming
uploads and downloads, configurable timeouts, IPv6, and connection pooling.
We can use other third-party libraries as well that offer higher-level APIs for networking operations.

Simple Example for Connecting to Internet:

try {
URL url = new URL(“https://example.com”);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

int responseCode = conn.getResponseCode();


if(responseCode == HttpURLConnection.HTTP_OK) {
return "OK (" + responseCode + ")";
} else {
return "Fail (" + responseCode + ")";
}
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid";
}

Android includes several classes to help you handle network communications. They are available in
the java.net.* and android.net.* packages.

3.9 Introducing Dialogs


Dialog boxes are a common UI metaphor in desktop, web, and mobile applications. They’re used to
help users answer questions, make selections, and confirm actions, and to display warning or error
messages. Dialog boxes in Android are partially transparent, floating Activities or Fragments that
partially obscure the UI that launched them.

There are three ways to implement a dialog in Android:


➢ Using the Dialog class
In addition to the general-purpose AlertDialog class, Android includes a number of classes
that extend Dialog. Each is designed to provide specific dialog box functionality. A Dialog
class based screen is constructed and controlled entirely within its calling Activity, so it
doesn’t need to be registered in the manifest.

➢ Dialog-themed Activities
We can apply the dialog theme to a regular Activity to give it appearance of a standard
dialog box.

➢ Toasts
Toasts are special nonmodal transient message box, often used by Broadcast Receivers and
Services to notify users of events occurring in the background.

Creating a Dialog Using Dialog Class


To create a new Dialog, instantiate a new Dialog instance and set the title and layout, using the
setTitle and setContentView methods. The setContentView method accepts a resource identifier for
a layout that will be inflated to display the Dialog’s UI.

// Create the new Dialog.


Dialog dialog = new Dialog(MyActivity.this);

// Set the title.


dialog.setTitle(“Dialog Title”);

// Inflate the layout.


dialog.setContentView(R.layout.dialog_text_view);

// Update the Dialog’s contents.


TextView text = (TextView) dialog.findViewById(R.id.textView);
text.setText(“This is the text in my dialog”);

// Display the Dialog.


dialog.show();

3.10 Using Activities as Dialogs


Dialogs and Dialog Fragments offer a simple and lightweight technique for displaying screens, but
we can also style an Activity so that it appears as a Dialog.
Note that in must circumstances we can gain the same level of control over the appearance and
lifecycle of our Dialog by using a Dialog Fragment.
The easiest way to make an Activity look like a Dialog is to apply the @style/Theme.AppCompat.Dialog
theme when we add the Activity to our manifest.

<activity android:name=”MyDialogActivity”
android:theme=”@style/Theme.AppCompat.Dialog”>
</activity>

This will cause our Activity to behave as a Dialog, floating on top of, and partially obscuring, the
Activity beneath it.

You might also like