Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 6 Theory – Calling Built-in Applications Using Intents; Displaying Notifications

Week 6 – Intents and Notifications · 85 min read · 31 MCQs to check yourself

Philipp Lackner – Intents and intent filters

Notifications and notification channels in Android

1. What is an Intent?

An Intent is a messaging object used to request an action from another app component. It is the "glue" that connects activities, services and broadcast receivers – within your app and across apps.

Three fundamental uses:

Use Method
Start an activity startActivity(intent) / activity result launcher
Start a service startService(intent) / startForegroundService(intent)
Deliver a broadcast sendBroadcast(intent)

Parts of an Intent

Part Meaning Example
Component name Exact class to start (explicit intents) SecondActivity.class
Action Generic action to perform Intent.ACTION_VIEW, ACTION_DIAL, ACTION_SEND
Data (URI) Data to act on, and its scheme decides the app tel:0300..., https://..., geo:33.6,73.0
Category Extra info about the component type CATEGORY_LAUNCHER, CATEGORY_BROWSABLE
Type (MIME) Type of data text/plain, image/*
Extras Key–value Bundle of additional data putExtra(Intent.EXTRA_TEXT, "Hi")
Flags How to launch FLAG_ACTIVITY_NEW_TASK, FLAG_ACTIVITY_CLEAR_TOP

2. Types of intents

Explicit intent

Names the exact component – used inside your own app (lab 4):

Intent intent = new Intent(this, DetailActivity.class);
startActivity(intent);

Implicit intent

Does not name a component; it declares an action (and data), and Android finds an app that can handle it. This is how you call built-in applications – browser, dialer, camera, maps, email, SMS – without writing those features yourself and usually without any permission.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.hec.gov.pk"));
startActivity(intent);

If several apps can handle it, the user sees a chooser ("Open with").

Pending intent

A token that lets another app (the system) perform your intent later with your app's permissions – used by notifications, alarms and widgets (section 6).

3. Calling built-in applications (common implicit intents)

Task Action Data / extras Permission
Open a web page ACTION_VIEW Uri.parse("https://...") None
Open the dialer with a number ACTION_DIAL Uri.parse("tel:03001234567") None
Call directly ACTION_CALL tel: URI CALL_PHONE (dangerous – runtime)
Show a location on a map ACTION_VIEW Uri.parse("geo:33.6844,73.0479?q=33.6844,73.0479(Campus)") None
Compose SMS ACTION_SENDTO smsto:0300... + extra "sms_body" None
Compose email ACTION_SENDTO mailto: + EXTRA_EMAIL, EXTRA_SUBJECT, EXTRA_TEXT None
Share text with any app ACTION_SEND type text/plain, EXTRA_TEXT None
Take a photo MediaStore.ACTION_IMAGE_CAPTURE output URI None (camera app does it)
Pick a contact ACTION_PICK ContactsContract.Contacts.CONTENT_URI None
Pick an image ACTION_GET_CONTENT / Photo Picker type image/* None
Open app settings Settings.ACTION_APPLICATION_DETAILS_SETTINGS package: URI None
Set an alarm AlarmClock.ACTION_SET_ALARM EXTRA_HOUR, EXTRA_MINUTES SET_ALARM (normal)
// Dialer
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:03001234567")));

// Share text
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
send.putExtra(Intent.EXTRA_TEXT, "Join MAD class at 10 am");
startActivity(Intent.createChooser(send, "Share via"));

// Map
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=Faisal+Mosque+Islamabad")));

Safety: what if no app can handle the intent?

startActivity throws ActivityNotFoundException. Wrap it:

try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    Toast.makeText(this, "No app found", Toast.LENGTH_SHORT).show();
}

(Since Android 11 package visibility rules mean intent.resolveActivity(packageManager) may return null unless you add a queries element in the manifest – so try/catch is the simplest reliable approach.)

4. Intent filters and intent resolution

An intent filter (in the manifest) declares which implicit intents a component can respond to:

<activity android:name=".ShareReceiverActivity" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>

Now your app appears in the share sheet when users share text.

Intent resolution – Android compares the implicit intent with all installed apps' filters using three tests:

  1. Action test – the intent's action must be listed in the filter.
  2. Category test – every category in the intent must be in the filter (activities need CATEGORY_DEFAULT to receive implicit intents).
  3. Data test – the URI scheme/host/path and MIME type must match. Matching activities are shown in a chooser; the user may pick a default.

Other filter examples: MAIN + LAUNCHER (launcher icon), VIEW + BROWSABLE with https data (deep links / App Links – open your app from a website link).

android:exported="true" is required (Android 12+) for any activity, service or receiver with an intent filter.

5. Displaying notifications

A notification is a message Android shows outside your app's UI – in the status bar, the notification drawer, on the lock screen, as a heads-up pop-up, or as an app icon badge.

Anatomy

Small icon · app name · time · title · text · large icon/picture · action buttons · progress bar.

Steps to show a notification

  1. Create a notification channel (Android 8.0+, once, e.g. in onCreate).
  2. Ask for the POST_NOTIFICATIONS permission (Android 13+).
  3. Build the notification with NotificationCompat.Builder.
  4. Post it with NotificationManagerCompat.notify(id, notification).
private static final String CHANNEL_ID = "class_updates";

private void createChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID, "Class updates", NotificationManager.IMPORTANCE_DEFAULT);
        channel.setDescription("Timetable and quiz reminders");
        getSystemService(NotificationManager.class).createNotificationChannel(channel);
    }
}

private void showNotification() {
    Intent open = new Intent(this, MainActivity.class);
    PendingIntent openApp = PendingIntent.getActivity(this, 0, open,
            PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

    Notification n = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_notification)       // required; white silhouette icon
            .setContentTitle("MAD Quiz Tomorrow")
            .setContentText("Revise intents and notifications")
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText("Quiz covers weeks 5 and 6: fragments, intents and notifications."))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)  // for Android 7.1 and lower
            .setContentIntent(openApp)                          // tap opens the app
            .setAutoCancel(true)                                // remove when tapped
            .build();

    if (Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission(this,
            Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
        NotificationManagerCompat.from(this).notify(1, n);
    }
}

Notification styles

Style Use
BigTextStyle Long text
BigPictureStyle Large image
InboxStyle Several short lines (emails)
MessagingStyle Chat conversations
MediaStyle Music player controls
Progress setProgress(max, current, false) – download progress

Updating and removing

6. Channels, permission and PendingIntent

Notification channels (Android 8.0 Oreo, API 26+)

Notification runtime permission (Android 13, API 33+)

Declare in the manifest and request at run time:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
private final ActivityResultLauncher<String> askPermission =
        registerForActivityResult(new ActivityResultContracts.RequestPermission(), granted -> {
            if (granted) showNotification();
            else Toast.makeText(this, "Notifications blocked", Toast.LENGTH_SHORT).show();
        });

// when the user taps "Notify me":
if (Build.VERSION.SDK_INT >= 33) askPermission.launch(Manifest.permission.POST_NOTIFICATIONS);
else showNotification();

PendingIntent

Local vs push notifications

Good notification practice

Notify only about timely, relevant information; group related notifications; respect user choices; never spam – users block or uninstall noisy apps.

Short and long questions

1. List the main parts of an Intent object.

Model answer

Component name, action, data (URI), category, type (MIME), extras (Bundle) and flags.

2. What is an intent? Name its three fundamental uses.

Model answer

An intent is a messaging object used to request an action from another app component. It is used to start an activity, start a service and deliver a broadcast.

3. Why is ACTIONDIAL preferred over ACTIONCALL?

Model answer

ACTION_DIAL only opens the dialer with the number filled, so the user confirms the call and no permission is required. ACTION_CALL places the call immediately and needs the dangerous CALL_PHONE runtime permission.

4. What is an intent filter? Give an example.

Model answer

An intent filter is a manifest declaration specifying which implicit intents (action, category, data/MIME type) a component can handle. Example: an activity with action SEND, category DEFAULT and mimeType text/plain appears in the share sheet for text.

5. Differentiate between local and push notifications.

Model answer

Local notifications are created and scheduled by the app on the device itself (reminders, timers). Push notifications are sent from a remote server through a service such as Firebase Cloud Messaging (Android) or APNs (iOS) and are received even when the app is not running.

6. List the steps to display a notification in Android.

Model answer

(1) Create a notification channel (Android 8+). (2) Declare and request POST_NOTIFICATIONS (Android 13+). (3) Build the notification with NotificationCompat.Builder – small icon, title, text, priority, content intent. (4) Post it with NotificationManagerCompat.from(context).notify(id, notification).

7. What is a PendingIntent?

Model answer

A PendingIntent wraps an intent and grants another application (such as the notification manager, AlarmManager or a widget host) the right to perform it later using your app's identity and permissions. It is used for notification taps and action buttons, alarms and widgets, and must be FLAG_IMMUTABLE or FLAG_MUTABLE from Android 12.

8. What is a notification channel? Why was it introduced?

Model answer

A notification channel (Android 8.0+) is a category of notifications with its own name, description and importance. Every notification must belong to a channel; it was introduced so users can control sound, vibration and blocking for each category of an app's notifications separately.

9. What are intents? Explain explicit and implicit intents and describe how an app can call built-in applications (browser, dialer, maps, SMS, email, camera) using implicit intents with code. How does Android resolve implicit intents?

Model answer

An intent is a messaging object used to request an action from another component – starting an activity, starting a service or delivering a broadcast. It may contain a component name, action, data URI, category, MIME type, extras and flags.

Explicit intents name the exact class and are used inside the app: startActivity(new Intent(this, DetailActivity.class));.

Implicit intents declare an action and data; Android finds an app whose intent filter matches. This lets an app reuse built-in apps without implementing their features, usually without permissions:

  • Browser: Intent(Intent.ACTION_VIEW, Uri.parse("https://www.hec.gov.pk"))
  • Dialer: Intent(Intent.ACTION_DIAL, Uri.parse("tel:03001234567")) (ACTION_CALL needs CALL_PHONE)
  • Maps: Intent(Intent.ACTION_VIEW, Uri.parse("geo:33.6844,73.0479?q=33.6844,73.0479(Campus)"))
  • SMS: Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:03001234567")).putExtra("sms_body", "Hello")
  • Email: new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")).putExtra(Intent.EXTRA_EMAIL, new String[]{"cs@uni.edu.pk"}).putExtra(Intent.EXTRA_SUBJECT, "Leave")
  • Camera: Intent(MediaStore.ACTION_IMAGE_CAPTURE); Share: ACTION_SEND with type text/plain and EXTRA_TEXT, wrapped in Intent.createChooser. Each call is placed in try/catch for ActivityNotFoundException in case no app is installed.

Resolution: Android compares the implicit intent against the intent filters of installed components using the action test, the category test (activities must include CATEGORY_DEFAULT) and the data test (scheme, host, path, MIME type). If one app matches it opens; if several match, a chooser is shown; if none match, ActivityNotFoundException is thrown. Components with filters must declare android:exported="true" (Android 12+).

10. Write Java code to open the dialer with a phone number and to open a web page.

Model answer

Dialer: startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:03001234567"))). Web page: startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://developer.android.com"))).

11. Explain notifications in Android. Describe notification channels, the POSTNOTIFICATIONS permission, NotificationCompat.Builder, PendingIntent and notification styles, with complete code to show a notification that opens the app when tapped.

Model answer

A notification is a message displayed outside the app's UI – status bar icon, notification drawer, lock screen, heads-up pop-up and icon badge – to inform users about timely events such as messages, reminders or downloads.

Channels (Android 8+): every notification must belong to a channel created once with a name, description and importance (HIGH = sound + heads-up, DEFAULT = sound, LOW = silent, MIN = minimal). Users control each channel in Settings.

Permission (Android 13+): declare android.permission.POST_NOTIFICATIONS in the manifest and request it at run time with registerForActivityResult(ActivityResultContracts.RequestPermission()).

Building: NotificationCompat.Builder(context, CHANNEL_ID) with setSmallIcon (required), setContentTitle, setContentText, setPriority, setStyle, setContentIntent, setAutoCancel, addAction; then NotificationManagerCompat.from(context).notify(id, builder.build()). Re-posting the same id updates it; cancel(id) removes it.

PendingIntent: wraps an intent so the system can launch the app later on the user's behalf: PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_IMMUTABLE); passed to setContentIntent (tap) or addAction (buttons).

Styles: BigTextStyle (long text), BigPictureStyle (image), InboxStyle (lines), MessagingStyle (chat), MediaStyle (player) and progress notifications.

Code outline:

// 1. channel
NotificationChannel ch = new NotificationChannel("class_updates", "Class updates",
        NotificationManager.IMPORTANCE_DEFAULT);
getSystemService(NotificationManager.class).createNotificationChannel(ch);
// 2. tap action
PendingIntent pi = PendingIntent.getActivity(this, 0,
        new Intent(this, MainActivity.class), PendingIntent.FLAG_IMMUTABLE);
// 3. build and 4. post (after POST_NOTIFICATIONS is granted on API 33+)
Notification n = new NotificationCompat.Builder(this, "class_updates")
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("MAD Quiz Tomorrow")
        .setContentText("Revise intents and notifications")
        .setContentIntent(pi).setAutoCancel(true).build();
NotificationManagerCompat.from(this).notify(1, n);

Push notifications arrive from servers via Firebase Cloud Messaging; good apps send only relevant notifications and respect user settings.

12. Differentiate between explicit and implicit intents with one example each.

Model answer

An explicit intent names the target component class, e.g. new Intent(this, SecondActivity.class) to open a screen of the same app. An implicit intent gives only an action and data, and Android chooses a suitable app, e.g. new Intent(Intent.ACTION_VIEW, Uri.parse("https://hec.gov.pk")) opens a browser.

This lesson ends with a quiz of 31 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 5 Lab 5 – Bottom Navigation Using Fragments Inside a Single Host Activity · Next: Week 6 Lab 6 – Open the Browser and the Dialer Using Buttons (plus a notification bonus)

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester