SlideShare a Scribd company logo
1 of 17
Download to read offline
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 1/17
Android BroadcastReceiver -
Tutorial
Lars Vogel (c) 2014, 2016 vogella GmbH – Version 3.1, 
27.06.2016
Table of Contents
1. Broadcast receiver
2. System broadcasts
3. Automatically starting Services from a Receivers
4. Exercise: Register a receiver for incoming phone calls
5. Exercise: System services and receiver
6. Dynamic broadcast receiver registration
7. About this website
8. Links and Literature
Appendix A: Copyright and License
Using Broadcast receivers in Android. This tutorial
describes how to create and consume broadcast
receivers in Android.
1. Broadcast receiver
1.1. De nition
A broadcast receiver (receiver) is an Android component
which allows you to register for system or application
events. All registered receivers for an event are notified by
the Android runtime once this event happens.
For example, applications can register for the
ACTION_BOOT_COMPLETEDsystem event which is fired once
the Android system has completed the boot process.
1.2. Implementation
A receiver can be registered via the AndroidManifest.xml
file.
Alternatively to this static registration, you can also
register a receiver dynamically via the
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 2/17
register a receiver dynamically via the
Context.registerReceiver()method.
The implementing class for a receiver extends the
BroadcastReceiverclass.
If the event for which the broadcast receiver has
registered happens, the onReceive()method of the
receiver is called by the Android system.
1.3. Life cycle of a broadcast receiver
After the onReceive()of the receiver class has finished,
the Android system is allowed to recycle the receiver.
1.4. Asynchronous processing
Before API level 11, you could not perform any
asynchronous operation in the onReceive()method,
because once the onReceive()method had been finished,
the Android system was allowed to recycle that component.
If you have potentially long running operations, you
should trigger a service instead.
Since Android API 11 you can call the goAsync()method.
This method returns an object of the PendingResulttype.
The Android system considers the receiver as alive until
you call the PendingResult.finish()on this object. With
this option you can trigger asynchronous processing in a
receiver. As soon as that thread has completed, its task calls
finish()to indicate to the Android system that this
component can be recycled.
1.5. Restrictions for de ning broadcast
receiver
As of Android 3.1 the Android system excludes all receiver
from receiving intents by default if the corresponding
application has never been started by the user or if the
user explicitly stopped the application via the Android
menu (in Manage ▸ Application ).
This is an additional security feature as the user can be
sure that only the applications he started will receive
broadcast intents.
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 3/17
NOW Hiring
(http://www.vogella.com/job
QUICK LINKS
09 OCT - RCP
Training
(http://www.vogella.com
23 OCT - Android
Development
(http://www.vogella.com
vogella Training
(http://www.vogella.com
vogella Books
(http://www.vogella.com
SHARE
broadcast intents.

This does not mean the user has to start the
application again after a reboot. The
Android system remembers that the user
already started it. Only one start is required
without a forced stop by the user.
1.6. Send the broadcast to your application
for testing
You can use the following command from the adb
command line tool. The class name and package names
which are targeted via the command line tool need to be as
defined in the manifest. You should send the intent you
generated to your specific component, for example if you
send a general ACTION_BOOT_COMPLETED broadcast, this
will trigger a lot of things in an Android system.
1.7. Pending Intent
A pending intent is a token that you give to another
application. For example, the notification manager, alarm
manager or other 3rd party applications). This allows the
other application to restore the permissions of your
application to execute a predefined piece of code.
To perform a broadcast via a pending intent, get a
PendingIntentvia the getBroadcast()method of the
PendingIntentclass. To perform an activity via a pending
intent, you receive the activity via
PendingIntent.getActivity().
2. System broadcasts
# trigger a broadcast and deliver it to a component
adb shell am activity/service/broadcast -a ACTION -c
CATEGORY -n NAME
# for example (this goes into one line)
adb shell am broadcast -a
android.intent.action.BOOT_COMPLETED -c
android.intent.category.HOME -n
package_name/class_name
JAVA
Tutorials (http://www.vogella.com/tutorials/) Training (http://www.vogella.com/training/)
Consulting (http://www.vogella.com/consulting/) Downloads (http://www.vogella.com/downloads/)
Books (http://www.vogella.com/books/) Company (http://www.vogella.com/company/) Donate (http://www.vogella.com/support.html)
Contact us (http://www.vogella.com/contact.html)
(http://www.vogella.com)
Search
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 4/17
2. System broadcasts
Several system events are defined as final static fields in
the Intentclass. Other Android system classes also define
events, e.g., the TelephonyManagerdefines events for the
change of the phone state.
The following table lists a few important system events.
Table 1. System Events
Event Description
Intent.ACTION_BOOT_COM
PLETED
Boot completed. Requires
the
android.permission.RECE
IVE_BOOT_COMPLETED
permission
Intent.ACTION_POWER_CO
NNECTED
Power got connected to
the device.
Intent.ACTION_POWER_DI
SCONNECTED
Power got disconnected to
the device.
Intent.ACTION_BATTERY_L
OW
Triggered on low battery.
Typically used to reduce
activities in your app
which consume power.
Intent.ACTION_BATTERY_O
KAY
Battery status good again.
3. Automatically starting Services
from a Receivers
A common requirement is to automatically start a service
after a system reboot, i.e., for synchronizing data. For this
you can register a receiver for the
android.intent.action.BOOT_COMPLETEDsystem event.
This requires the
android.permission.RECEIVE_BOOT_COMPLETED
permission.
The following example demonstrates the registration for
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 5/17
The following example demonstrates the registration for
the BOOT_COMPLETEDevent in the Android manifest file.
The receive would start the service as demonstrated in the
following example code.
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/andr
oid"
package="de.vogella.android.ownservice.local"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission
android:name="android.permission.RECEIVE_BOOT_COMPLETE
D" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".ServiceConsumerActivity"
android:label="@string/app_name" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyScheduleReceiver" >
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name="MyStartServiceReceiver" >
</receiver>
</application>
</manifest>
XML
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent
JAVA
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 6/17

If your application is installed on the SD
card, then it is not available after the
android.intent.action.BOOT_COMPLETED
event. In this case register it for the
`android.intent.action.ACTION_EXTERNAL_
APPLICATIONS_AVAILABLE ` event.

Remember that as of Android API level 11
the user needs to have started the
application at least once before your
application can receive
android.intent.action.BOOT_COMPLETED
events.
4. Exercise: Register a receiver for
incoming phone calls
4.1. Target
In this exercise you define a broadcast receiver which
listens to telephone state changes. If the phone receives a
phone call, then our receiver will be notified and log a
message.
4.2. Create project
Create a new project called
de.vogella.android.receiver.phone. Also create an
activity.
TIP:Remember that your receiver is only called if the user
started it once. This requires an activity.
4.3. Implement receiver for the phone
event
Create the MyPhoneReceiverclass.
public void onReceive(Context context, Intent
intent) {
// assumes WordService is a registered service
Intent intent = new Intent(context,
WordService.class);
context.startService(intent);
}
}
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 7/17
4.4. Request permission
Add the android.permission.READ_PHONE_STATE
permission to your manifest file which allows you to listen
to state changes in your receiver. Also Register your
receiver in your manifest file. The resulting manifest
should be similar to the following listing.
package de.vogella.android.receiver.phone;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
public class MyPhoneReceiver extends
BroadcastReceiver {
@Override
public void onReceive(Context context, Intent
intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state =
extras.getString(TelephonyManager.EXTRA_STATE);
Log.w("MY_DEBUG_TAG", state);
if
(state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.w("MY_DEBUG_TAG", phoneNumber);
}
}
}
}
JAVA
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/andr
oid"
package="de.vogella.android.receiver.phone"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission
XML
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 8/17
4.5. Validate implementations
Install your application and simulate a phone call via the
Android Device Monitor. Validate that your receiver is
called and logs a message to the LogCatview.
5. Exercise: System services and
receiver
5.1. Target
In this chapter we will schedule a receiver via the Android
alert manager system service. Once called, it uses the
Android vibrator manager and a popup message (Toast) to
notify the user.
5.2. Implement project
Create a new project called de.vogella.android.alarm with
the activity called AlarmActivity.
<uses-permission
android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyPhoneReceiver" >
<intent-filter>
<action
android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 9/17
Create the following layout.
Create the following broadcast receiver class. This class will
get the vibrator service.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/andr
oid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Number of seconds"
android:inputType="numberDecimal" >
</EditText>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAlert"
android:text="Start Counter" >
</Button>
</LinearLayout>
XML
package de.vogella.android.alarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;
public class MyBroadcastReceiver extends
BroadcastReceiver {
@Override
public void onReceive(Context context, Intent
intent) {
Toast.makeText(context, "Don't panik but your
JAVA
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 10/17
Register this class as a broadcast receiver in
AndroidManifest.xml and request authorization to vibrate
the phone.
Toast.makeText(context, "Don't panik but your
time is up!!!!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator)
context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/andr
oid"
package="de.vogella.android.alarm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission
android:name="android.permission.VIBRATE" >
</uses-permission>
<application
XML
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 11/17
Change the code of your AlarmActivityclass to the
following. This activity creates an intent to start the
receiver and register this intent with the alarm manager
service.
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".AlarmActivity"
android:label="@string/app_name" >
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
package de.vogella.android.alarm;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class AlarmActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JAVA
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 12/17
5.3. Validate implementation
Run your application on the device. Set your time and start
the alarm. After the defined number of seconds a Toast
should be displayed. Keep in mind that the vibration alarm
does not work on the Android emulator.
setContentView(R.layout.main);
}
public void startAlert(View view) {
EditText text = (EditText)
findViewById(R.id.time);
int i =
Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this,
MyBroadcastReceiver.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(
this.getApplicationContext(),
234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager)
getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + "
seconds",
Toast.LENGTH_LONG).show();
}
}
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 13/17
6. Dynamic broadcast receiver
registration
6.1. Dynamically registered receiver
Receiver can be registered via the Android manifest file.
You can also register and unregister a receiver at runtime
via the Context.registerReceiver()and
Context.unregisterReceiver()methods.

Do not forget to unregister a dynamically
registered receiver by using
Context.unregisterReceiver()method. If
you forget this, the Android system reports a
leakedbroadcastreceivererror. For
instance, if you registered a receive in
onResume()methods of your activity, you
should unregister it in the onPause()
method.
6.2. Using the package manager to disable
static receivers
You can use the PackageManagerclass to enable or disable
receivers registered in your AndroidManifest.xml file.
6.3. Sticky (broadcast) intents
An intent to trigger a receiver ( broadcast intent ) is not
available anymore after it was sent and processed by the
ComponentName receiver = new ComponentName(context,
myReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
JAVA
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 14/17
system. If you use the sendStickyBroadcast(Intent)
method, the corresponding intent is sticky, meaning the
intent you are sending stays around after the broadcast is
complete.
The Android system uses sticky broadcast for certain
system information. For example, the battery status is send
as sticky intent and can get received at any time. The
following example demonstrates that.
// Register for the battery changed event
IntentFilter filter = new
IntentFilter(Intent.ACTION_BATTERY_CHANGED);
/ Intent is sticky so using null as receiver works
fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null,
filter);
// Are we charging / charged?
int status =
batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS,
-1);
boolean isCharging = status ==
BatteryManager.BATTERY_STATUS_CHARGING
|| status == BatteryManager.BATTERY_STATUS_FULL;
boolean isFull = status ==
BatteryManager.BATTERY_STATUS_FULL;
// How are we charging?
JAVA
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 15/17
You can retrieve that data through the return value of
registerReceiver(BroadcastReceiver,IntentFilter)
`.Thisalsoworksforanull`BroadcastReceiver.
In all other ways, this behaves just as
sendBroadcast(Intent).
Sticky broadcast intents typically require special
permissions.
7. About this website
Support free
content
(http://www.vogella.com/support.html)
Questions and
discussion
(http://www.vogella.com/contact.html)
Tutorial & code
license
(http://www.vogella.com/license.html)
Get the source
code
(http://www.vogella.com/code/index.html)
8. Links and Literature
8.1. Android Resources
Android Development Tutorial
(http://www.vogella.com/tutorials/Android/article.html)
Android ListView and ListActivity
(http://www.vogella.com/tutorials/AndroidListView/article.html)
Android Location API and Google Maps
(http://www.vogella.com/tutorials/AndroidLocationAPI/article.html)
Android Intents
(http://www.vogella.com/tutorials/AndroidIntent/article.html)
Android and Networking
(http://www.vogella.com/tutorials/AndroidNetworking/article.html)
Android Background processing with Threads and
Asynchronous Task
(http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html)
// How are we charging?
int chargePlug =
batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED
, -1);
boolean usbCharge = chargePlug ==
BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug ==
BatteryManager.BATTERY_PLUGGED_AC;
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 16/17
(http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html)
Remote Messenger Service from Google
(http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample)
8.2. vogella GmbH training and consulting
support
TRAINING
(http://www.vogella.com/trai
ning/)
SERVICE & SUPPORT
(http://www.vogella.com/con
sulting/)
The vogella company
provides comprehensive
training and education
services
(http://www.vogella.com/traini
ng/)
from experts in the areas
of Eclipse RCP, Android,
Git, Java, Gradle and
Spring. We offer both
public and inhouse
training. Whichever
course you decide to take,
you are guaranteed to
experience what many
before you refer to as “The
best IT class I have ever
attended”
(http://www.vogella.com/traini
ng/)
.
The vogella company
offers expert consulting
(http://www.vogella.com/consu
lting/)
services, development
support and coaching. Our
customers range from
Fortune 100 corporations
to individual developers.
Appendix A: Copyright and License
Copyright © 2012-2017 vogella GmbH. Free use of the
software examples is granted under the terms of the EPL
License. This tutorial is published under the Creative
Commons Attribution-NonCommercial-ShareAlike 3.0
Germany
(http://creativecommons.org/licenses/by-nc-sa/3.0/de/deed.en)
license.
See Licence (http://www.vogella.com/license.html).
10/3/2017 Android BroadcastReceiver - Tutorial
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 17/17
See Licence (http://www.vogella.com/license.html).
Version 3.1
Last updated 2017-07-11 22:37:35 +02:00

More Related Content

Similar to Android broadcast receiver tutorial

MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx34ShreyaChauhan
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介easychen
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialDanish_k
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifestma-polimi
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialmaster760
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recieversUtkarsh Mankad
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callmaamir farooq
 
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsDiego Grancini
 
Android tutorial ppt
Android tutorial pptAndroid tutorial ppt
Android tutorial pptRehna Renu
 
Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKAjay Chebbi
 

Similar to Android broadcast receiver tutorial (20)

MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxxMAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
MAD Unit 5.pptxxxxxxxxxxxxxxxxxxxxxxxxxx
 
Unit2
Unit2Unit2
Unit2
 
Android Basic- CMC
Android Basic- CMCAndroid Basic- CMC
Android Basic- CMC
 
Android应用开发简介
Android应用开发简介Android应用开发简介
Android应用开发简介
 
Ppt 2 android_basics
Ppt 2 android_basicsPpt 2 android_basics
Ppt 2 android_basics
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifest
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone call
 
Android App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgetsAndroid App Development - 13 Broadcast receivers and app widgets
Android App Development - 13 Broadcast receivers and app widgets
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Activity
ActivityActivity
Activity
 
Android Development Basics
Android Development BasicsAndroid Development Basics
Android Development Basics
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial ppt
Android tutorial pptAndroid tutorial ppt
Android tutorial ppt
 
Push Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDKPush Notification in IBM MobileFirst Xamarin SDK
Push Notification in IBM MobileFirst Xamarin SDK
 

More from maamir farooq (20)

Ooad lab1
Ooad lab1Ooad lab1
Ooad lab1
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 02
Lesson 02Lesson 02
Lesson 02
 
Php client libray
Php client librayPhp client libray
Php client libray
 
Swiftmailer
SwiftmailerSwiftmailer
Swiftmailer
 
Lect15
Lect15Lect15
Lect15
 
Lec 7
Lec 7Lec 7
Lec 7
 
Lec 6
Lec 6Lec 6
Lec 6
 
Lec 5
Lec 5Lec 5
Lec 5
 
J query 1.7 cheat sheet
J query 1.7 cheat sheetJ query 1.7 cheat sheet
J query 1.7 cheat sheet
 
Assignment
AssignmentAssignment
Assignment
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Lec 3
Lec 3Lec 3
Lec 3
 
Lec 2
Lec 2Lec 2
Lec 2
 
Lec 1
Lec 1Lec 1
Lec 1
 
Css summary
Css summaryCss summary
Css summary
 
Manual of image processing lab
Manual of image processing labManual of image processing lab
Manual of image processing lab
 
Session management
Session managementSession management
Session management
 
Data management
Data managementData management
Data management
 
Content provider
Content providerContent provider
Content provider
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Android broadcast receiver tutorial

  • 1. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 1/17 Android BroadcastReceiver - Tutorial Lars Vogel (c) 2014, 2016 vogella GmbH – Version 3.1,  27.06.2016 Table of Contents 1. Broadcast receiver 2. System broadcasts 3. Automatically starting Services from a Receivers 4. Exercise: Register a receiver for incoming phone calls 5. Exercise: System services and receiver 6. Dynamic broadcast receiver registration 7. About this website 8. Links and Literature Appendix A: Copyright and License Using Broadcast receivers in Android. This tutorial describes how to create and consume broadcast receivers in Android. 1. Broadcast receiver 1.1. De nition A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. For example, applications can register for the ACTION_BOOT_COMPLETEDsystem event which is fired once the Android system has completed the boot process. 1.2. Implementation A receiver can be registered via the AndroidManifest.xml file. Alternatively to this static registration, you can also register a receiver dynamically via the
  • 2. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 2/17 register a receiver dynamically via the Context.registerReceiver()method. The implementing class for a receiver extends the BroadcastReceiverclass. If the event for which the broadcast receiver has registered happens, the onReceive()method of the receiver is called by the Android system. 1.3. Life cycle of a broadcast receiver After the onReceive()of the receiver class has finished, the Android system is allowed to recycle the receiver. 1.4. Asynchronous processing Before API level 11, you could not perform any asynchronous operation in the onReceive()method, because once the onReceive()method had been finished, the Android system was allowed to recycle that component. If you have potentially long running operations, you should trigger a service instead. Since Android API 11 you can call the goAsync()method. This method returns an object of the PendingResulttype. The Android system considers the receiver as alive until you call the PendingResult.finish()on this object. With this option you can trigger asynchronous processing in a receiver. As soon as that thread has completed, its task calls finish()to indicate to the Android system that this component can be recycled. 1.5. Restrictions for de ning broadcast receiver As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage ▸ Application ). This is an additional security feature as the user can be sure that only the applications he started will receive broadcast intents.
  • 3. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 3/17 NOW Hiring (http://www.vogella.com/job QUICK LINKS 09 OCT - RCP Training (http://www.vogella.com 23 OCT - Android Development (http://www.vogella.com vogella Training (http://www.vogella.com vogella Books (http://www.vogella.com SHARE broadcast intents.  This does not mean the user has to start the application again after a reboot. The Android system remembers that the user already started it. Only one start is required without a forced stop by the user. 1.6. Send the broadcast to your application for testing You can use the following command from the adb command line tool. The class name and package names which are targeted via the command line tool need to be as defined in the manifest. You should send the intent you generated to your specific component, for example if you send a general ACTION_BOOT_COMPLETED broadcast, this will trigger a lot of things in an Android system. 1.7. Pending Intent A pending intent is a token that you give to another application. For example, the notification manager, alarm manager or other 3rd party applications). This allows the other application to restore the permissions of your application to execute a predefined piece of code. To perform a broadcast via a pending intent, get a PendingIntentvia the getBroadcast()method of the PendingIntentclass. To perform an activity via a pending intent, you receive the activity via PendingIntent.getActivity(). 2. System broadcasts # trigger a broadcast and deliver it to a component adb shell am activity/service/broadcast -a ACTION -c CATEGORY -n NAME # for example (this goes into one line) adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n package_name/class_name JAVA Tutorials (http://www.vogella.com/tutorials/) Training (http://www.vogella.com/training/) Consulting (http://www.vogella.com/consulting/) Downloads (http://www.vogella.com/downloads/) Books (http://www.vogella.com/books/) Company (http://www.vogella.com/company/) Donate (http://www.vogella.com/support.html) Contact us (http://www.vogella.com/contact.html) (http://www.vogella.com) Search
  • 4. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 4/17 2. System broadcasts Several system events are defined as final static fields in the Intentclass. Other Android system classes also define events, e.g., the TelephonyManagerdefines events for the change of the phone state. The following table lists a few important system events. Table 1. System Events Event Description Intent.ACTION_BOOT_COM PLETED Boot completed. Requires the android.permission.RECE IVE_BOOT_COMPLETED permission Intent.ACTION_POWER_CO NNECTED Power got connected to the device. Intent.ACTION_POWER_DI SCONNECTED Power got disconnected to the device. Intent.ACTION_BATTERY_L OW Triggered on low battery. Typically used to reduce activities in your app which consume power. Intent.ACTION_BATTERY_O KAY Battery status good again. 3. Automatically starting Services from a Receivers A common requirement is to automatically start a service after a system reboot, i.e., for synchronizing data. For this you can register a receiver for the android.intent.action.BOOT_COMPLETEDsystem event. This requires the android.permission.RECEIVE_BOOT_COMPLETED permission. The following example demonstrates the registration for
  • 5. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 5/17 The following example demonstrates the registration for the BOOT_COMPLETEDevent in the Android manifest file. The receive would start the service as demonstrated in the following example code. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="de.vogella.android.ownservice.local" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETE D" /> <application android:icon="@drawable/icon" android:label="@string/app_name" > <activity android:name=".ServiceConsumerActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyScheduleReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> <receiver android:name="MyStartServiceReceiver" > </receiver> </application> </manifest> XML import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent JAVA
  • 6. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 6/17  If your application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. In this case register it for the `android.intent.action.ACTION_EXTERNAL_ APPLICATIONS_AVAILABLE ` event.  Remember that as of Android API level 11 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events. 4. Exercise: Register a receiver for incoming phone calls 4.1. Target In this exercise you define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call, then our receiver will be notified and log a message. 4.2. Create project Create a new project called de.vogella.android.receiver.phone. Also create an activity. TIP:Remember that your receiver is only called if the user started it once. This requires an activity. 4.3. Implement receiver for the phone event Create the MyPhoneReceiverclass. public void onReceive(Context context, Intent intent) { // assumes WordService is a registered service Intent intent = new Intent(context, WordService.class); context.startService(intent); } }
  • 7. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 7/17 4.4. Request permission Add the android.permission.READ_PHONE_STATE permission to your manifest file which allows you to listen to state changes in your receiver. Also Register your receiver in your manifest file. The resulting manifest should be similar to the following listing. package de.vogella.android.receiver.phone; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.TelephonyManager; import android.util.Log; public class MyPhoneReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { String state = extras.getString(TelephonyManager.EXTRA_STATE); Log.w("MY_DEBUG_TAG", state); if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { String phoneNumber = extras .getString(TelephonyManager.EXTRA_INCOMING_NUMBER); Log.w("MY_DEBUG_TAG", phoneNumber); } } } } JAVA <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="de.vogella.android.receiver.phone" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <uses-permission XML
  • 8. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 8/17 4.5. Validate implementations Install your application and simulate a phone call via the Android Device Monitor. Validate that your receiver is called and logs a message to the LogCatview. 5. Exercise: System services and receiver 5.1. Target In this chapter we will schedule a receiver via the Android alert manager system service. Once called, it uses the Android vibrator manager and a popup message (Toast) to notify the user. 5.2. Implement project Create a new project called de.vogella.android.alarm with the activity called AlarmActivity. <uses-permission android:name="android.permission.READ_PHONE_STATE" > </uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyPhoneReceiver" > <intent-filter> <action android:name="android.intent.action.PHONE_STATE" > </action> </intent-filter> </receiver> </application> </manifest>
  • 9. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 9/17 Create the following layout. Create the following broadcast receiver class. This class will get the vibrator service. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr oid" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="Number of seconds" android:inputType="numberDecimal" > </EditText> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startAlert" android:text="Start Counter" > </Button> </LinearLayout> XML package de.vogella.android.alarm; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Vibrator; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Don't panik but your JAVA
  • 10. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 10/17 Register this class as a broadcast receiver in AndroidManifest.xml and request authorization to vibrate the phone. Toast.makeText(context, "Don't panik but your time is up!!!!.", Toast.LENGTH_LONG).show(); // Vibrate the mobile phone Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(2000); } } <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/andr oid" package="de.vogella.android.alarm" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <uses-permission android:name="android.permission.VIBRATE" > </uses-permission> <application XML
  • 11. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 11/17 Change the code of your AlarmActivityclass to the following. This activity creates an intent to start the receiver and register this intent with the alarm manager service. <application android:icon="@drawable/icon" android:label="@string/app_name" > <activity android:name=".AlarmActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyBroadcastReceiver" > </receiver> </application> </manifest> package de.vogella.android.alarm; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class AlarmActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); JAVA
  • 12. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 12/17 5.3. Validate implementation Run your application on the device. Set your time and start the alarm. After the defined number of seconds a Toast should be displayed. Keep in mind that the vibration alarm does not work on the Android emulator. setContentView(R.layout.main); } public void startAlert(View view) { EditText text = (EditText) findViewById(R.id.time); int i = Integer.parseInt(text.getText().toString()); Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234324243, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (i * 1000), pendingIntent); Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show(); } }
  • 13. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 13/17 6. Dynamic broadcast receiver registration 6.1. Dynamically registered receiver Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context.registerReceiver()and Context.unregisterReceiver()methods.  Do not forget to unregister a dynamically registered receiver by using Context.unregisterReceiver()method. If you forget this, the Android system reports a leakedbroadcastreceivererror. For instance, if you registered a receive in onResume()methods of your activity, you should unregister it in the onPause() method. 6.2. Using the package manager to disable static receivers You can use the PackageManagerclass to enable or disable receivers registered in your AndroidManifest.xml file. 6.3. Sticky (broadcast) intents An intent to trigger a receiver ( broadcast intent ) is not available anymore after it was sent and processed by the ComponentName receiver = new ComponentName(context, myReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); JAVA
  • 14. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 14/17 system. If you use the sendStickyBroadcast(Intent) method, the corresponding intent is sticky, meaning the intent you are sending stays around after the broadcast is complete. The Android system uses sticky broadcast for certain system information. For example, the battery status is send as sticky intent and can get received at any time. The following example demonstrates that. // Register for the battery changed event IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); / Intent is sticky so using null as receiver works fine // return value contains the status Intent batteryStatus = this.registerReceiver(null, filter); // Are we charging / charged? int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL; // How are we charging? JAVA
  • 15. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 15/17 You can retrieve that data through the return value of registerReceiver(BroadcastReceiver,IntentFilter) `.Thisalsoworksforanull`BroadcastReceiver. In all other ways, this behaves just as sendBroadcast(Intent). Sticky broadcast intents typically require special permissions. 7. About this website Support free content (http://www.vogella.com/support.html) Questions and discussion (http://www.vogella.com/contact.html) Tutorial & code license (http://www.vogella.com/license.html) Get the source code (http://www.vogella.com/code/index.html) 8. Links and Literature 8.1. Android Resources Android Development Tutorial (http://www.vogella.com/tutorials/Android/article.html) Android ListView and ListActivity (http://www.vogella.com/tutorials/AndroidListView/article.html) Android Location API and Google Maps (http://www.vogella.com/tutorials/AndroidLocationAPI/article.html) Android Intents (http://www.vogella.com/tutorials/AndroidIntent/article.html) Android and Networking (http://www.vogella.com/tutorials/AndroidNetworking/article.html) Android Background processing with Threads and Asynchronous Task (http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html) // How are we charging? int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED , -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
  • 16. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 16/17 (http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html) Remote Messenger Service from Google (http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample) 8.2. vogella GmbH training and consulting support TRAINING (http://www.vogella.com/trai ning/) SERVICE & SUPPORT (http://www.vogella.com/con sulting/) The vogella company provides comprehensive training and education services (http://www.vogella.com/traini ng/) from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended” (http://www.vogella.com/traini ng/) . The vogella company offers expert consulting (http://www.vogella.com/consu lting/) services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers. Appendix A: Copyright and License Copyright © 2012-2017 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany (http://creativecommons.org/licenses/by-nc-sa/3.0/de/deed.en) license. See Licence (http://www.vogella.com/license.html).
  • 17. 10/3/2017 Android BroadcastReceiver - Tutorial http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html 17/17 See Licence (http://www.vogella.com/license.html). Version 3.1 Last updated 2017-07-11 22:37:35 +02:00