Broadcast receivers.

Slides:



Advertisements
Similar presentations
WiFi in Android.
Advertisements

Cosc 5/4730 Android Services. What is a service? From android developer web pages: Most confusion about the Service class actually revolves around what.
Android 02: Activities David Meredith
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Lec 06 AsyncTask Local Services IntentService Broadcast Receivers.
BroadcastReceiver.  Base class for components that receive and react to events  Events are represented as Intent objects  Intents received as parameter.
System broadcasts and services. System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE.
Mobile Programming Pertemuan 6 Presented by Mulyono Poltek NSC Surabaya.
SMS. Short Message Service – Primarily text messages between mobile phones – First one sent December 3, 1982 “Merry Christmas” – In 2008 Approximately.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Broadcast intents.
Integrating with Android Services. Introduction  Android has numerous built-in functionality that can be called from within your applications  SMS/MMS.
Using Intents to Broadcast Events Intents Can be used to broadcast messages anonymously Between components via the sendBroadcast method As a result Broadcast.
Cosc 5/4730 Broadcast Receiver. Broadcast receiver A broadcast receiver (short receiver) – is an Android component which allows you to register for system.
Android ICC Part II Inter-component communication.
COMP 365 Android Development.  Perform operations in the background  Services do not have a user interface (UI)  Can run without appearing on screen.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
Mobile Programming Lecture 6
Erika Chin Adrienne Porter Felt Kate Greenwood David Wagner University of California Berkeley MobiSys 2011.
DUE Hello World on the Android Platform.
CS378 - Mobile Computing Intents.
로봇 모니터링 2/2 UNIT 21 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Broadcasting Service 2.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
10/10/2015 E.R.Edwards 10/10/2015 Staffordshire University School of Computing Introduction to Android Overview of Android System Android Components Component.
Android Programming-Activity Lecture 4. Activity Inside java folder Public class MainActivity extends ActionBarActivity(Ctrl + Click will give you the.
Android - Broadcast Receivers
COMP 365 Android Development.  Every android application has a manifest file called AndroidManifest.xml  Found in the Project folder  Contains critical.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
ANDROID L. Grewe Components  Java Standard Development Kit (JDK) (download) (latest version)  AndroidStudio.
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
Mobile Programming Midterm Review
Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.
Speech Service & client(Activity) 오지영.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
Mobile Software Development for Android - I397 IT COLLEGE, ANDRES KÄVER, WEB:
David Sutton SMS TELEPHONY IN ANDROID. OUTLINE  This week’s exercise, an SMS Pub Quiz  Simulating telephony on an emulator  Broadcast Intents and broadcast.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
Cosc 4735 Nougat API 24+ additions.
Android Application -Architecture.
Concurrency in Android
Intents and Broadcast Receivers
Mobile Software Development for Android - I397
CS499 – Mobile Application Development
CS371m - Mobile Computing Services and Broadcast Receivers
Basic Activities and Intents
Lecture 7: Service Topics: Services, Playing Media.
Mobile Application Development BSCS-7 Lecture # 6
Activities and Intents
Android Mobile Application Development
The Android Activity Lifecycle
Reactive Android Development
Broadcast Receivers A Android Component where you can register for system or application events, receive and react to broadcast intent. Each broadcast.
Mobile Software Development for Android - I397
Android Programming Lecture 9
Developing Android Services
Android Notifications (Part 2) Plus Alarms and BroadcastReceivers
HNDIT2417 Mobile Application Development
Activity Lifecycle.
Android Developer Fundamentals V2 Lesson 5
Service Services.
Lecture 7: Service Topics: Services, Broadcast Receiver, Playing Media.
SE4S701 Mobile Application Development
Activities and Fragments
Android Development Tools
Activities, Fragments, and Intents
Mobile Programming Broadcast Receivers.
Presentation transcript:

Broadcast receivers

Purpose of Receivers To receive notification of system events E.g., to receive ACTION_BOOT_COMPLETED event so you can start email sync service To notify and receive notifications between applications. To notify and receive notifications between components in the same application A background service notifies the activity that downloading a file is completed.

Registering a Receiver Static - Declaring in manifest.xml <manifest …> <application …> <receiver android:name=“edu.scranton.bi.OnBootCompletedReceiver” > <intent-filter> <action android:name=“android.intent.action.BOOT_COMPLETED”> </receiver> </application> </manifest> Dynamic – register/unregister receiver IntentFilter intentFilter = new IntentFilter(“android.intent.action.BOOT_COMPLETED”); OnBootCompletedReceiver mReceiver = new OnBootCompletedReceiver() context.registerReceiver(mReceiver, intentFilter); getActivity().unregisterReceiver(mReceiver); Where to register and unregister receiver onStart() and onStop() onResume() and onPause() onCreate() and onDestroy() Receivers for certain events must be registered dynamically E.g., Intent.ACTION_BATTERY_CHANGED Some events require appropriate permissions in Manifest.xml E.g., <uses-permissions android:name”android.permission.RECEIVE-BOOT_COMPLETED”/>

How to Create a Receiver Subclass BroadcastReceiver class OnBootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle data = intent.getExtras(); Intent aIntent = new Intent(context, EmailSyncService.class); context.startService(aIntent); } onReceive() is called on the main/UI thread of the process unless registerReceiver() specifies a handler. onReceive() should not have long-running operations. Otherwise Android may consider it to be blocked and a candidate to be killed.

Static vs Dynamic Static - Declaring in manifest.xml If your app provides services when certain events occur Ex. 1: Upon device boot completed, start sync email with server Ex. 2: Upon WIFI becoming available, check for news update Dynamic – register/unregister receiver If your app needs to react to occurrences of events Ex. 1: Upon receiving low battery event, lower the screen brightness of your game Ex. 2: Up the event of power connected, you increase the screen brightness. In both examples, register/unregister in onResume/onPause

Lifecycle of Receivers Once the onReceive() is completed, the system considers the object to be finished and no longer active The hosting process would be considered to be empty and may be aggressively killed by Android if the receiver was the only active component in the process

Broadcast Intent Broadcast events are encapsulated in Intent An broadcast intent may carry more data E.g., android.intent.action.PHONE_STATE // Manifest.xml <receiver android:name="MyPhoneEventReceiver"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE"></action> </intent-filter> </receiver> // receiver’s onReceive() void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); if (b != null) { String state = b.getString(TelephonyManager.EXTRA_STATE); if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) { String number = b.getString(TelephonyManager.EXTRA_INCOMING_NUMBER); }

Some System Broadcast Events Broadcast actions defined in Intent Value description ACTION_TIME_TICK* The current time has changed. Sent every minute ACTION_SHUTDOWN Device is shutting down ACTION_BATTERY_LOW Battery has become low ACTION_BATTERY_OKAY Battery has becomes okay after being low ACTION_BATTERY_CHANGED* Sticky#– changing state and level, etc *Receivers must be registered dynamically. # An intent of a normal event disappears after it is process. sticky event would stay. registeReceiver() returns the intent.

Custom Events and Receivers Applications can broadcast their events and define receivers Define receivers – in manifest.xml or programmatically <receiver android:name="MyCustomEventReceiver" > <intent-filter> <action android:name=“edu.scranton.bi.MY_CUSTOM_EVENT" /> </intent-filter> </receiver> Broadcast custom events Static final String CUSTON_EVENT = =“edu.scranton.bi.MY_CUSTOM_EVENT“; Intent intent = new Intent(CUSTOM_EVENT); intent.putExtra(“SOME_DATA”, mData); context.sendBroadcast(intent); // sendStickyBroadcast(intent); // broadcast a sticky event // removeStickyBroadcast(intent); // remove the sticky event

Local Broadcast and Receive Local intents are inside the same process Use LocalBroadcastManager to regsiter receiver and send broadcast MainActivity receives Event from Service The Receiver (MainActivity) mFeedbackIntentFilter = new IntentFilter(Constants.MY_BROADCAST_ACTION); mFeedbackReceiver = new FeedbackReceiver(this); LocalBroadcastManager.getInstance(this).registerReceiver(mFeedbackReceiver, mFeedbackIntentFilter); // the receiver class FeedbackReceiver extends BroadcastReceiver { private WeakReference<MainActivity> activityReference; public FeedbackReceiver(Activity activity) { activityReference = new WeakReference<MainActivity>((MainActivity) activity); } public void onReceive(Context context, Intent data) { // get the real reference from WeakReference MainActivity activity = activityReference.get(); // since the object could have be garbage collected, // so we should always check if the reference is null if (activity != null) { String feedbackMessage = data.getStringExtra(Constants.EXTRA_STATUS); activity.getTextView().setText("Feedback: " + feedbackMessage));

Local Broadcast and receiver The Broadcaster (Service) Class ServiceWithFeedback extends Service { Void onHandleIntent(Intent intent) { // process intent reportStatus(“Done Successfully”); } private void reportStatus(String message) { Intent intent = new Intent(Constants.BROADCAST_ACTION); intent.putExtra(Constants.EXTRA_STATUS, message); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); Log.i("INTENTSERVICE: ", "Feedback sent");

Types of Broadcast Events Normal broadcast Using sendBroadcast(intent) Asynchronous broadcast and handling Receivers are called in an undefined order OrderedBroadcast Using sendOrderedBroadcast(intent) Receivers are called in turn in the order of priority Receivers of the same priority run in an arbitrary order A receiver can pass result to next receiver and abort the broadcast Sticky Broadcast Using sendStickyBroadcast(intent) (removeStickyBroadcast()) It sticks around after broadcast is complete registerReceiver() returns the intent of the broadcast event Local Broadcast Broadcast events are inside the same application Using LocalBroadcastManager to register receivers and send broadcast events