Mobile Programming Broadcast Receivers.

Slides:



Advertisements
Similar presentations
Android 101 Application Fundamentals January 29, 2010.
Advertisements

System broadcasts and services. System broadcast events. EventDescription Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires the android.permission.RECE.
SMS. Short Message Service – Primarily text messages between mobile phones – First one sent December 3, 1982 “Merry Christmas” – In 2008 Approximately.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Broadcast intents.
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.
Mobile Programming Lecture 6
Mobile Application Development using Android Lecture 2.
로봇 모니터링 2/2 UNIT 21 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Broadcasting Service 2.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
Android - Broadcast Receivers
TCS Internal Maps. 2 TCS Internal Objective Objective :  MAPS o Integration of Maps.
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.
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
CMPE419 Mobile Application Development Asst.Prof.Dr.Ahmet Ünveren SPRING Computer Engineering Department Asst.Prof.Dr.Ahmet Ünveren
Cosc 4735 Nougat API 24+ additions.
Lab7 – Appendix.
Introduction to android
Google VR (gvr) CardBoard and DayDream With OpenGL
Android Application -Architecture.
Intents and Broadcast Receivers
Mobile Software Development for Android - I397
Lecture 3 Zablon Ochomo Android Layouts Lecture 3 Zablon Ochomo
Android Application Development 1 6 May 2018
CS499 – Mobile Application Development
Broadcast receivers.
CS371m - Mobile Computing Services and Broadcast Receivers
Adapting to Display Orientation
CS240: Advanced Programming Concepts
GUI Programming Fundamentals
Mobile Computing With Android ACST 4550 Intro to Android, Part 1
Android Mobile Application Development
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
Mobile Device Development
Android Programming Lecture 9
Developing Android Services
CIS 470 Mobile App Development
CIS 470 Mobile App Development
Android Notifications (Part 2) Plus Alarms and BroadcastReceivers
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CMPE419 Mobile Application Development
Chapter 1: Basics of Android, First App: HelloAndroid
Android Topics Android Activity Lifecycle and Experiment Toast
HNDIT2417 Mobile Application Development
Activities and Intents
CIS 470 Mobile App Development
CIS 470 Mobile App Development
CIS 470 Mobile App Development
Android Developer Fundamentals V2 Lesson 5
CIS 470 Mobile App Development
Mobile Programming Gestures in Android.
Android Project Structure, App Resources and Event Handling
Adding Components to Activity
BLP 4216 MOBİL UYGULAMA GELİŞTİRME-2
CMPE419 Mobile Application Development
CMPE419 Mobile Application Development
Chapter 5 Your Second Activity.
Activities, Fragments, and Intents
Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Mobile Programming Broadcast Receivers

Broadcasts in Android

Broadcasts in Android Broadcasts are messages sent by Android system and other Android apps, when an event of interest occurs. Broadcasts are wrapped in an Intent object. This Intent object’s contains the event details such as, action “android.intent.action.HEADSET_PLUG” is sent when a wired headset is plugged or unplugged. Some other examples are: android.intent.action.BATTERY_CHANGED:broadcast containing the charging state, level, and other information about the battery. android.intent.action.BATTERY_LOW:Indicates low battery condition on the device. android.intent.action.BOOT_COMPLETED :This is broadcast once, after the system has finished booting. android.intent.action.DATE_CHANGED : The date has changed android.net.conn.CONNECTIVITY_CHANGE : The mobile network or wifi connection is changed(or reset) android.provider.Telephony.SMS_RECEIVED: if an sms is received.

Types of broadcast: System broadcast Custom broadcast System broadcast are the messages sent by the Android system, when a system event occurs, that might affect your app. Few examples: An Intent with action, ACTION_BOOT_COMPLETED is broadcasted when the device boots. An Intent with action, ACTION_POWER_CONNECTED is broadcasted when the device is connected to the external power. Screen turning off, battery low, picture was captured, SMS is received Custom broadcast Custom broadcasts are broadcasts that your app sends out, similar to the Android system. For example, when you want to let other app(s) know that some data has been downloaded by your app, and its available for their use.

Sending a Custom Broadcast

Send a Custom Broadcast Syntax for sending a custom broadcast intent Intent intent = new Intent(); intent.setAction("com.mp.CUSTOM_INTENT"); sendBroadcast(intent);

Broadcast Receivers

Broadcast Receivers Broadcast receivers are app components. They register for various system broadcast and or custom broadcast. They are notified (via an Intent): By the system, when a system event occurs that your app is registered for. By another app, including your own if your app is registered for that custom event.

How to implement a Broadcast Receiver Create a subclass of Android’s BroadcastReceiver Implement the onReceive() method Register that broadcast receiver for a Broadcast Intent

Create a subclass of Android’s BroadcastReceiver public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Action: " + intent.getAction(), Toast.LENGTH_SHORT).show(); } Following are the two arguments of the onReceive() method: Context: This is used to access additional information, or to start services or activities. Intent: The Intent object is used to register the receiver.

Register for listening to a Broadcast Intent Broadcast receivers can be registered in two ways: Static receivers Registered in your AndroidManifest.xml, also called as Manifest-declared receivers. You do this if your app offers some kind of service around these events even when it is not open Dynamic receivers Registered using app or activities' context in your Java files, also called as Context- registered receivers. You register receivers like this if your app wants to react to state changes

Contd. Static Receiver Registration Dynamic Receiver Registration in onCreate() or onResume() Unregister Receiver in onDestroy() or onPause() <receiver android:name=".MyReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> IntentFilter filter = new IntentFilter(); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); MyReceiver myReceiver = new MyReceiver(); registerReceiver(myReceiver, filter); @Override protected void onPause() { unregisterReceiver(myReceiver); super.onPause(); }

What are Intent Filters Intent-filters specify the types of intents a broadcast receiver can receive. They filter the incoming intents based on the Intent values like action. To add an intent-filter: To your AndroidManifest.xml file, use <intent-filter> tag. To your Java file use the IntentFilter object.

Registration Restrictions Starting from Android 8.0 (API level 26), static receivers can't receive most of the system broadcasts. Use a dynamic receiver to register for these broadcasts. If you register for the system broadcasts in the manifest, the Android system won't deliver them to your app. A few broadcasts, are excepted from this restriction. See the complete list of implicit broadcast exceptions.

Example Code – Creating a broadcast receiver that listens to network change events <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.lab.pdoffice.systembroadcastapp"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <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" /> </intent-filter> </activity> <receiver android:name=".ConnectionReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest>

Contd. Broadcast Receiver public class ConnectionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (isConnected) { Toast.makeText(context, "Network is connected", Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Network is changed or reconnected", Toast.LENGTH_LONG).show(); } } }

Example Code 2 - Creating a broadcast receiver that listens to custom broadcasts public class MainActivity extends AppCompatActivity { MyReceiver receiver; IntentFilter intentFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); receiver = new MyReceiver(); intentFilter = new IntentFilter("com.mp.customintent"); registerReceiver(receiver,intentFilter); } public void sendCustomBroadcast(View v){ Intent i = new Intent("com.mp.customintent"); sendBroadcast(i); } @Override protected void onDestroy() { unregisterReceiver(receiver); super.onDestroy(); } } <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send Broadcast!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:onClick="sendCustomBroadcast"/> </android.support.constraint.ConstraintLayout>

Contd. Broadcast Receiver public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction()=="com.mp.customintent") { Toast.makeText(context, "custom intent received", Toast.LENGTH_LONG).show(); } }

Thank You!