You are on page 1of 46

Mobile Computing

Lecture #05
Intents
Previous Lecture
Android Activities
Today’s Lecture
Intents
Intent Usage
1. Start an Activity
2. Start a Service
3. Delivering a Broadcast
Intent Types
1. Explicit Intents
2. Implicit Intents
Creating an Intent
Receiving an Implicit Intent
Pending Intent
Using a Pending Intent
Intent Resolution
Activity
Activities are subclasses of the Activity class.
By default, when you create a new project, Your activities are
subclasses of the AppCompatActivity class. The AppCompatActivity
class is a subclass of Activity that lets you to use up-to-data Android
app features .

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The first task for you in your activity subclass is to implement the
standard activity lifecycle callback methods

setContentView() helps the OnCreate() method to create the primary


layout for the activity with the path of layout file
setContentView(R.layout.activity_main);
Intent
In English, Intent means “intention”,
• Intents are message object, which android use for passing the
information among Activities in an Application and from one app to
another app.
• It is used to start activity because, when app start from home screen,
the android runtime sends an intent to your app to start, you app’s
main activity. To start another sub activity, you build your own intent
with the intent class and call the startActivity() method to send that
intent.
Intents …
Intent in = new Intent(getApplicationContext(), myActivity.class);
startActivity(in);

myActivity.class

ublic class myActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
}
Intent
An Intent is a small message passed around the Android system
One can simply say that it is a abstract description of an operation to be
performed
Operation may include starting an activity, launching a service, delivering a
broadcast, setting alarm and triggering an event in future etc.
Intent can use class name (package name) or a URI as target component
In case, the intent wants to launch an activity or a service, target must be listed
in manifest.xml file
In case of URI, then the intent can mention attributes (the scheme, host name, or
MIME type)
Similarly, the intent handling component must match the attributes of URI
Intent Usage … Start an Activity
An Activity represents a screen in an Android application
An Activity (say MyActivity) can start a new Activity (say AnotherActivity)
using startActivity() method
startActivity() method requires an Intent as its parameter
The Intent contains information about which Activity to start and necessary
data
If current Activity requires that launching Activity must return some result,
startActivityForResult() should be called instead of startActivity()
Launching activity will return the result that current activity receives in a
separate Intent object in its onActivityResult() callback
Intent Usage … Start an Activity … Launch Code
Intent intent = new Intent(MainActivity.this, NextActivity.class);
startActivity(intent);
Intent Usage … Start an Activity … AndroidManifest
<manifest xmlns:android=http://schemas.android.com/apk/res/android package="com.imran.first">
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NextActivity"></activity>
</application>
</manifest>
Intent Usage … Start an Activity … activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next“
android:onClick=“launchNextActivity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Intent Usage … Start an Activity … next.xml
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".NextActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/back"
android:textSize="20dp"
android:textColor="@color/grey"
android:onClick="goBack"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Intent Usage … Start an Activity … MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void launchNextActivity(View view) {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
startActivity(intent);
}
}
Intent Usage … Start an Activity … NextActivity.java
public class NextActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
}
public void goBack(View view){
Intent intent = new Intent(NextActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
}
Intent Usage … Start Activity for Result… activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"

xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20dp"
android:text="Result will be shown here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/result"
android:layout_centerHorizontal="true"
android:onClick="launchDataActivity"
android:text="@string/click" />
</RelativeLayout>
Intent Usage … Start Activity for Result… data.xml
Intent Usage … Start Activity for Result… data.xml
Intent Usage … Start Activity for Result… MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.result);
}

public void launchDataActivity(View view){


Intent intent = new Intent(MainActivity.this, DataActivity.class);
startActivityForResult(intent, Utils.REQUEST_CODE);
}
Intent Usage … Start Activity for Result… MainActivity.java
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utils.REQUEST_CODE){
if(resultCode == Activity.RESULT_OK) {
String loan = data.getStringExtra("loanAmount");
String interest = data.getStringExtra("interestRate");
double loanAmount = Double.parseDouble(loan);
double interestRate = Double.parseDouble(interest);
double totalAmount = loanAmount * (1.0+interestRate);
String output = getString(R.string.payable_amount) + " "+ totalAmount;
result.setText(output);
}
}
}
}
Intent Usage … Start Activity for Result… DataActivity.java
public class DataActivity extends AppCompatActivity {
EditText amount, interest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
amount = findViewById(R.id.amount);
interest = findViewById(R.id.interest_rate);
}

public void goBack(View view){


final Intent data = new Intent();
data.putExtra("loanAmount", amount.getText().toString());
data.putExtra("interestRate", interest.getText().toString());
setResult(Activity.RESULT_OK, data);
finish();
}

}
Intent Usage … Start Activity for Result… Utils.java
public class Utils {
public static final int REQUEST_CODE = 0x9344;
}
Intent Usage … Start an Service
Just like activities, a service (background running process) can also be
launched using an intent

// use this to start and trigger a service


Intent intent= new Intent(MyActivity.this, MyService.class);
context.startService(intent);
Intent Usage … Broadcasting
Android apps can send or receive broadcast messages from the Android
system and other Android apps
Broadcasts are sent when an event of interest occurs. For example, the system
boots up, the device starts charging or device is connected to internet
Apps can also send custom broadcasts, for example, to notify other apps of
something that they might be interested in (for example, some new data has
been downloaded)
Intent Usage … Broadcast … Sending Broadcast
Intent intent = new Intent();
intent.setAction("com.myapp.broadcasts.NEW_NOTIFICATION");
sendBroadcast(intent);
Intent Usage … Broadcast … Sending Broadcast
There are three different ways to send a broadcast:
1. sendOrderedBroadcast(Intent, String)
2. sendBroadcast(Intent)
3. LocalBroadcastManager.sendBroadcast()
Intent Usage … Broadcast … Register as Receiver
Register as BroadcastReceiver using Manifest
<receiver android:name=".MyBroadcastReceiver“>
<intent-filter>
<action android:name="com.myapp.broadcasts.NEW_NOTIFICATION "/>
</intent-filter>
</receiver>
Intent Usage … Broadcast … Register Dynamically
Registering as BroadcastReceiver using Java Code is a three step process:
1. Create an instance of BroadcastReceiver
2. Create an IntentFilter
3. register the receiver by calling registerReceiver(BroadcastReceiver,
IntentFilter)
Code:
BroadcastReceiver br = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
this.registerReceiver(br, filter);
Intent Usage … Broadcast … Responding to a Broadcast
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
StringBuilder sb = new StringBuilder();
sb.append("Action: " + intent.getAction() + "\n");
String log = sb.toString();
Log.d(TAG, log);
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}
Intent Types
Two types of Intents
1. Explicit Intent
2. Implicit Intent
Intent Types … Explicit Intent
An intent which specifies target app’s package name or fully qualified class
name
This type of intent is used to launch an activity/service within current
application since a programmer knows the exact name of target
For example, you might want to launch an activity within same application
Intent Types … Explicit Intent … Example
Below is an example of explicit intent:
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
Intent Types … Implicit Intent
An implicit intent does not declare the name of target component but rather
defines a general action to be performed
Any component from current application or any other application that has
registered itself for said action, can handle the intent
For example, if an application wants to show a location on a map, it can use an
implicit intent to request any component capable of doing that should do it

Below is an example of implicit intent:


Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);
Pending an Intent
A PendingIntent object is a wrapper around an Intent object
The primary purpose of a PendingIntent is to grant permission to a foreign
application to use the contained Intent as if it were executed from your
app's own process
Using a Pending Intent
Major use cases for a pending intent include the following:
Use Case User’s Action Which Component Launches the Intent
Handler?
1 Declaring an intent to be executed when the Android system's
the user performs an action with your NotificationManager executes the Intent
Notification
2 Declaring an intent to be executed when the Home screen app executes the
the user performs an action with your Intent
App Widget
3 Declaring an intent to be executed at a the Android system's AlarmManager
specified future time executes the Intent
Resolving an Intent
When the system receives an implicit intent to start an activity, it searches
for the best activity for the intent by comparing it to intent filters based on
three aspects:
1. Action
2. Data (both URI and data type)
3. Category
Resolving an Intent … Action
To specify accepted intent actions, an intent filter can declare zero or more
<action> elements, as shown in the following example:
<intent-filter>
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.VIEW" />
...
</intent-filter>
To pass this filter, the action specified in the Intent must match one of the
actions listed in the filter
If the filter does not list any actions, there is nothing for an intent to match,
so all intents fail the test
However, if an Intent does not specify an action, it passes the test as long as
the filter contains at least one action
Resolving an Intent … Category
To specify accepted intent categories, an intent filter can declare zero or more <category>
elements, as shown in the following example:
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
...
</intent-filter>
For an intent to pass the category test, every category in the Intent must match a category in
intent-filter
The reverse is not necessary
An intent filter can declare more categories than are specified in the Intent and the Intent still
passes
Therefore, an intent with no categories always passes this test, regardless of what categories
are declared in the filter.
If you want your activity to receive implicit intents, it must include a category for
"android.intent.category.DEFAULT" in its intent filters, as shown in the previous <intent-filter>
example
Note: Android automatically applies the CATEGORY_DEFAULT category to all implicit intents
passed to startActivity() and startActivityForResult()
Resolving an Intent … Data
To specify accepted intent data, an intent filter can declare zero or more
<data> elements, as shown in the following example:
<intent-filter>
<data android:mimeType="video/mpeg" android:scheme="http" ... />
<data android:mimeType="audio/mpeg" android:scheme="http" ... />
...
</intent-filter>
Resolving an Intent … Data
Each <data> element can specify a URI structure and a data type (MIME
media type). Each part of the URI is a separate attribute: scheme, host, port,
and path:
<scheme>://<host>:<port>/<path>
The following example shows possible values for these attributes:
content://com.example.project:200/folder/subfolder/etc
In above URI, the scheme is content, the host is com.example.project, the
port is 200, and the path is folder/subfolder/etc
Resolving an Intent … Data … Dependencies
Each of these attributes is optional in a <data> element, but there are linear
dependencies:
If a scheme is not specified, the host is ignored.
If a host is not specified, the port is ignored.
If both the scheme and host are not specified, the path is ignored.
Resolving an Intent … Data … URI Comparison
When the URI in an intent is compared to a URI specification in an intent-
filter, it's compared only to the parts of the URI included in the filter. For
example:
If a filter specifies only a scheme, all URIs with that scheme match the filter
If a filter specifies a scheme and an authority but no path, all URIs with the
same scheme and authority pass the filter, regardless of their paths
If a filter specifies a scheme, an authority, and a path, only URIs with the
same scheme, authority, and path pass the filter
Resolving an Intent … Data … URI Comparison
The data test compares both the URI and the MIME type in the intent to a URI
and MIME type specified in the filter. The rules are as follows:
a. An intent that contains neither a URI nor a MIME type passes the test only if
the filter does not specify any URIs or MIME types
b. An intent that contains a URI but no MIME type (neither explicit nor
inferable from the URI) passes the test only if its URI matches the filter's URI
format and the filter likewise does not specify a MIME type
c. An intent that contains a MIME type but not a URI passes the test only if the
filter lists the same MIME type and does not specify a URI format
d. An intent that contains both a URI and a MIME type (either explicit or
inferable from the URI) passes the MIME type part of the test only if that type
matches a type listed in the filter. It passes the URI part of the test either if its
URI matches a URI in the filter or if it has a content: or file: URI and the filter
does not specify a URI. In other words, a component is presumed to support
content: and file: data if its filter lists only a MIME type.
Resolving an Intent … Data … Matching Example
The following example shows a typical case in which a <data> element tells
Android that the component can get image data from a content provider and
display it:
<intent-filter>
<data android:mimeType="image/*" />
...
</intent-filter>
Resolving an Intent … Data … Matching Example
<data> element like the following tells Android that the component can
retrieve video data from the network in order to perform the action:
<intent-filter>
<data android:scheme="http" android:mimeType="video/*" />
...
</intent-filter>
Intent Match
Intents are matched against intent filters not only to discover a target component,
but also to discover the set of components on the device
For example, the Home app populates the app launcher by finding all the activities
with intent filters that specify the ACTION_MAIN action and CATEGORY_LAUNCHER
category
A match is only successful if the actions and categories in the Intent match against
the filter, as described in the documentation for the IntentFilter class
In a similar way, your application can query Android System to discover which
applications (or components) can handle a particular intent

You might also like