Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Mobile Computing

Unit No-:03
Android Services and Broadcast Receivers
1) Explain in brief Broadcast and Broadcast Receivers in Android.
Broadcast in android is the system-wide events that can occur when the device starts, when a
message is received on the device or when incoming calls are received, or when a device goes
to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.
Broadcast Receivers allow us to register for the system and application events, and when that
event happens, then the register receivers get notified.

Broadcast Receivers simply respond to broadcast messages from other applications or from the
system itself. These messages are sometime called events or intents. For example, applications
can also initiate broadcasts to let other applications know that some data has been downloaded
to the device and is available for them to use, so this is broadcast receiver who will intercept
this communication and will initiate appropriate action.

There are mainly two types of Broadcast Receivers:


 Static Broadcast Receivers: These types of Receivers are declared in the manifest file and
works even if the app is closed.
 Dynamic Broadcast Receivers: These types of receivers work only if the app is active or
minimized.

Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so
we have implemented dynamic receivers in our sample project given below. There are some
static fields defined in the Intent class which can be used to broadcast different events. We have
taken a change of airplane mode as a broadcast event, but there are many events for which
broadcast register can be used. Following are some of the important system-wide generated
intents:-
2) How to implement Broadcast receiver in Android.
There are following two important steps to make BroadcastReceiver works for the system
broadcasted intents −
 Creating the Broadcast Receiver.
 Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you
will have to create and broadcast those intents.
Creating the Broadcast Receiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding


the onReceive() method where each message is received as a Intent object parameter.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}

Registering Broadcast Receiver

An application listens for specific broadcast intents by registering a broadcast receiver


in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated
event ACTION_BOOT_COMPLETED which is fired by the system once the Android system
has completed the boot process.

Broadcast-Receiver
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>

</receiver>
</application>
Now whenever your Android device gets booted, it will be intercepted by
BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.
There are several system generated events defined as final static fields in the Intent class. The
following table lists a few important system events.

Sr.No Event Constant & Description

android.intent.action.BATTERY_CHANGED
1 Sticky broadcast containing the charging state, level, and other information about the
battery.

android.intent.action.BATTERY_LOW
2
Indicates low battery condition on the device.

android.intent.action.BATTERY_OKAY
3
Indicates the battery is now okay after being low.

android.intent.action.BOOT_COMPLETED
4
This is broadcast once, after the system has finished booting.

android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.

android.intent.action.CALL
6
Perform a call to someone specified by the data.

android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for placing
a call.

android.intent.action.DATE_CHANGED
8
The date has changed.

android.intent.action.REBOOT
9
Have the device reboot.
3) Write a short note on –
a) Intents in Android
In Android, it is quite usual for users to witness a jump from one application to another as a part
of the whole process, for example, searching for a location on the browser and witnessing a
direct jump into Google Maps or receiving payment links in Messages Application (SMS) and
on clicking jumping to PayPal or GPay (Google Pay). This process of taking users from one
application to another is achieved by passing the Intent to the system. Intents, in general, are
used for navigating among various activities within the same application, but note, is not limited
to one single application, i.e., they can be utilized from moving from one application to another
as well.

Intents could be Implicit, for instance, calling intended actions, and explicit as well, such as
opening another activity after some operations like onClick or anything else. Below are some
applications of Intents:

1. Sending the User to Another App


2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity

The collaborative nature of Android applications only results in a better user experience. The
question here is if the intent is for an application that is not present in the device, what’s the
next call?
Some Important Method of Intent and their Description

Methods Description

This is to launch a new activity or get an existing activity to be


Context.startActivity() action.

This is to start a new service or deliver instructions for an existing


Context.startService() service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.


Deep Linking

Deep Link is an URL that redirects the device to the API of that Missing Application and then
the service is run on the system to check if a version of that application exists on the device.
For time being, let’s assume that the application is not available on the device and no previous
versions ever existed. This service then makes a call to the Play Store from the device and the
application appears, just a matter of download.
Not deviating from the topic, there are a few examples that already exist in Android Studio for
redirecting to other applications, for example, Dialing Numbers, Sending SMSs, Opening
Settings, etc. Everyday examples include redirecting to YouTube, Maps, WhatsApp,
Facebook, etc. Android community, especially the Kotlin Community is at its zenith every
single impending day. Kotlin has witnessed a huge amount of sudden growth in the past few
years and could be one of the vital tools in the future replacing Java & possibly Julia also.
Types of Android Intents
There are two types of intents in android
1. Implicit
2. Explicit

Implicit Intent
Implicit Intent doesn’t specify the component. In such a case, intent provides information on
available components provided by the system that is to be invoked. For example, you may
write the following code to view the webpage.
Syntax:
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.geeksforgeeks.org/"));
startActivity(intent);
For Example: In the below images, no component is specified, instead, an action is
performed i.e. a webpage is going to be opened. As you type the name of your desired
webpage and click on the ‘CLICK’ button. Your webpage is opened.
Explicit Intent
Explicit Intent specifies the component. In such a case, intent provides the external class to be
invoked.
Syntax:
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
For Example: In the below example, there are two activities (FirstActivity, and
SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ Button in the
FirstActivity, then you move to the SecondActivity. When you click on the ‘GO TO HOME
ACTIVITY’ button in the SecondActivity, then you move to the first activity. This is getting
done through Explicit Intent.

Note: To know more about the types of intent with example code please refer to Implicit and
Explicit Intents with Examples.

b) Intent Filters in Android


An intent filter is an instance of the IntentFilter class. Intent filters are helpful while using implicit
intents, It is not going to handle in java code, we have to set it up in AndroidManifest.xml.
Android must know what kind of intent it is launching so intent filters give the information to
android about intent and actions.
Before launching intent, android going to do action test, category test and data test. This example
demonstrate about how to use intent filters in android.
Step 1 − Create a new project in Android Studio,go to File ⇒ New Project and fill all required
details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/buton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="intent filter button" />
</LinearLayout>
In the above, we have given a button when you click on button it will show intent with action.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
public class MainActivity extends AppCompatActivity {
RadioButton radioButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.buton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"contact@tutorialspoint.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Welcome to tutorialspoint.com");
startActivity(Intent.createChooser(intent, "Choose default Mail App"));
}
});
}
}
In the above when user click on button it will call intent using ACTION_SEND and will set type
as message/rfc882. Now we passed out email id and subject message.
Step 4 − Add the following code to manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.andy.myapplication">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="message/rfc822" />
</intent-filter>
</activity>
</application>
</manifest>
In the above we have declared action, category and data. Let's try to run your application. I
assume you have connected your actual Android Mobile device with your computer. To run the
app from android studio, open one of your project's activity files and click Run icon from the
toolbar. Select your mobile device as an option and then check your mobile device which will
display your default screen –
Click on above button it will call intent chooser to choose application to send data from intent as
shown below –
We have selected gmail application as shown below -

c) System broadcast

The Android system automatically sends broadcasts when various system events occur, such as
when the system switches in and out of airplane mode. The system sends these broadcasts to all
apps that are subscribed to receive the event.
The table below lists the standard system broadcast intents that your app can receive in Android
11 (API level 30). To learn more about each broadcast Intent, use the links below. To learn
more about broadcasts or how to receive them, see the documentation.

4) What are intents in Android? Explain its types with example.


5) List out different system broadcasts. Give example by implementing any one
of them.

You might also like