Presentation is loading. Please wait.

Presentation is loading. Please wait.

Broadcast receivers.

Similar presentations


Presentation on theme: "Broadcast receivers."— Presentation transcript:

1 Broadcast receivers

2 Purpose of Receivers To receive notification of system events
E.g., to receive ACTION_BOOT_COMPLETED event so you can start 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.

3 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”/>

4 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, SyncService.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.

5 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 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

6 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

7 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); }

8 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.

9 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

10 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));

11 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");

12 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


Download ppt "Broadcast receivers."

Similar presentations


Ads by Google