Вы находитесь на странице: 1из 15

Software for Mobile Devices

Broadcast Listeners, Processes & Threads


(Part1)
Lecture # 16

Online Group Piazza: https://piazza.com/fast_lahore/fall2018/cs440/home


Access Code: cs440
Android App Components

1. Intents
2. Alarm Managers & Job Schedulers
3. Content Providers
4. Notification Manager (Local Notifications & Push
Notifications)
5. Activity vs Fragments
6. Service
7. Broadcast Receiver
8. Contexts
Intro to Broadcasts
1. Applications can register for various system events (intents) like boot complete or battery low.

2. Android system sends broadcast when specific system events occur similar to publish-
subscribe pattern. System broadcasts are sent to all apps that are subscribed to receive the
event.

3. Apps can also send custom broadcasts, for example, to notify other apps of something that
they might be interested in (for example, some new data has been downloaded).

How to know which event we can listen?


• List of broadcast actions is located under the sdk/platforms//data/broadcast_actions.txt.
https://developer.android.com/guide/components/broadcasts
Types of Broadcasts

1. Normal Broadcasts
1. Context Registered Receivers (Global)
2. Manifest Registered Receivers (Global)
3. Local Broadcast

In non-ordered mode, broadcasts are sent to all interested receivers “at the same
time”. This basically means that one receiver can not interfere in any way with what
other receivers will do neither can it prevent other receivers from being executed.
One example of such broadcast is the ACTION_BATTERY_LOW one.

2. Ordered Broadcasts

In ordered mode, broadcasts are sent to each receiver in order (controlled by


the android:priority attribute for the intent-filter element in the manifest file that is
related to your receiver) and one receiver is able to abort the broadcast so that
receivers with a lower priority would not receive it (thus never execute).

They run on main thread!!!!


Implicit VS Explicit Broadcasts?!

What are implicit broadcasts?


An implicit broadcast is a broadcast that does not target that app specifically. For
example, SCREEN_ON is an implicit broadcast, since it is sent to all registered
listeners, letting them know that some device screen is turned on.

How to register to listen them?


• Always register implicit broadcasts from java code ( in any of the class).

What are explicit broadcasts?


Explicit broadcasts are those broadcasts that target your application specifically.
For example ACTION_MY_PACKAGE_REPLACED is an explicit broadcast that will be
sent to your application when it is upgrade.

How to register to listen them?


• Explicit broadcasts can be registered by just entering their detail in Android
Manifest.

They run on main thread!!!!


But why all these restrictions each time when new OS launch?!
It’s all about saving power!!

Apps were registering a lot of unnecessary implicit BroadcastReceivers in their manifest,


causing unwanted battery drain. For example, a lot of apps registered receivers for
the CONNECTIVITY_ACTION broadcast.

Imagine this:

• You have dozen apps that listen for connectivity change events. You
leave home to go grocery shopping.

• The connection for the home wifi drops once you exit your apartment.
Android system sends the CONNECTIVITY_ACTION broadcast,
and causes all of those dozen apps to wake up and react to that
change.

Since all those apps register for these broadcasts in their AndroidManifest,
they’re always woken up to receive these events. Even when they’re not in the
foreground or even running at all.
Registering Broadcasts

How to register for Broadcasts? (2 Ways)

1. Context registered receivers (Java Code)


2. Manifest declared receivers (Static Android Manifest Code)

With apps targeting Android O, all implicit BroadcastReceivers


registered in the manifest (except these) will stop working.

So, always check for behavior changes


https://developer.android.com/preview/behavior-changes.html

Implicit broadcasts exempted from restriction if targeting Oreo:


https://developer.android.com/guide/components/broadcast-exceptions
Broadcast Listeners?!
Steps to register for Broadcast listener (Implicit)
1. Declare your listener (class name) in manifest.

2. If your listener needs to access some resources which require permission,


then mention it as well in manifest.

3. Now create a separate class (Your broadcast Listener name which extends
from BroadcastReceiver)
Broadcast Listeners?!
Steps to register for Broadcast listener for system events(Implicit)
public class ScreenReceiver extends BroadcastReceiver {
@Override String TAG = "ScreenReceiver";
protected void onCreate(Bundle savedInstanceState) { @Override
super.onCreate(savedInstanceState); public void onReceive(Context context, Intent intent) {
setContentView(R.layout.main_activity);
if(intent.getAction() !=null) {
ScreenReceiver screenReceiver = new ScreenReceiver(); if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
IntentFilter intentFilter = new IntentFilter(); Log.i(TAG, "Screen is off now");
intentFilter.addAction(Intent.ACTION_SCREEN_ON); }else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
intentFilter.addAction(Intent.ACTION_SCREEN_OFF); Log.i(TAG, "Screen is on now");
registerReceiver(screenReceiver, intentFilter); }
} }
}
}
MainActivity
YourReceiver
@Override
public void onDestroy(){ It has maximum limit of 10secs, do not do any
super.onDestroy(); asynchronous operations which may take
unregisterReceiver(screenReceiver); more time, do not do heavy database operations or
} networking operations in broadcast.

Don’t forget to unregister receiver, otherwise No UI but can start an Activity


leak might occur. Runs on MAIN THREAD!!!!! 
Broadcast Listeners?!
Steps to register for Broadcast listener for other or our applications (Explicit)

@Override
protected void onCreate(Bundle savedInstanceState) { public class CustomListener extends BroadcastReceiver {
super.onCreate(savedInstanceState); String TAG = " CustomListener ";
setContentView(R.layout.main_activity); @Override
public void onReceive(Context context, Intent intent) {
CustomListener customListener = new CustomListener(); Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
IntentFilter intentFilter1 = new IntentFilter(); }
intentFilter1.addAction("smd.custom.listener"); }
registerReceiver(customListener, intentFilter1);
}
YourReceiver
//call on onclick (for testing)
public void sendBroadcast(View view) {
Log.i("sending..", "button clicked");
Intent localIntent = new Intent();
localIntent.addCategory(Intent.CATEGORY_DEFAULT); <receiver android:name=".ui.CustomListener">
localIntent.setAction("smd.custom.listener");
sendBroadcast(localIntent); <intent-filter>
} <action android:name="smd.custom.listener" />
<category
android:name="android.intent.category.DEFAULT" />
MainActivity </intent-filter>
</receiver>
If you use android: exported = "false“ attribute
in manifest, then no apps can communicate or
invoke your receiver Declare in Manifest
What is LocalBroadcastManager?

1. For obvious reasons, global broadcasts must never contain sensitive


information.

2. You can, however, broadcast such information locally using


the LocalBroadcastManager class, which is a part of the Android Support
Library. No Inter process communication.

3. A LocalBroadcastManager is used to send or receive events locally within


the current application only.

Below are some of its benefits:

1. Broadcast data won’t leave your app, so don’t need to worry about leaking private
data.
2. It is not possible for other applications to send these broadcasts to your app, so you
don’t need to worry about having security holes they can exploit.
3. It is more efficient than sending a global broadcast through the system.
4. No overhead of system-wide broadcast.
How to work with local broadcast?

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);

LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("smd.custom.listener"));

};

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {


@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
//onClick button
public void sendBroadcast(View view) {
Log.i("sending..", "button clicked");
Intent intent = new Intent("smd.custom.listener");
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
What are ordered broadcast receivers?

3 Receivers with same action which broadcast receiver will be called first??
Depending upon their “priority”, high priority means execution first. Priority is
set in their manifest tag.
Sending Ordered Broadcast
@Override
protected void onCreate(Bundle savedInstanceState) { public class CustomListener extends BroadcastReceiver {
super.onCreate(savedInstanceState); String TAG = " CustomListener ";
setContentView(R.layout.main_activity); } @Override
public void onReceive(Context context, Intent intent) {
//call on onclick (for testing) Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
public void sendBroadcast(View view) { }
}
Intent localIntent = new Intent();
localIntent.addCategory(Intent.CATEGORY_DEFAULT); public class CustomListener2 extends BroadcastReceiver {
localIntent.setAction("smd.custom.listener"); String TAG = " CustomListener2 ";
sendOrderedBroadcast(localIntent,null); @Override
} public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Clicked!!", Toast.LENGTH_SHORT).show();
} YourReceiver
}

<receiver android:name=".ui.CustomListener">
<intent-filter>
<action android:name="smd.custom.listener" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
MainActivity <receiver android:name=".ui.CustomListener2">
<intent-filter>
<action android:name="smd.custom.listener" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>

Declare in Manifest Declare in Manifest (Priority not set,


(Priority set) first one will call first)
Tutorial Links

YouTube Playlist (services):


https://www.youtube.com/watch?v=XqjWq7kuBHI&list=PLfuE3hO
AeWha9AWKnQTKP3YeZWfO1yamc

Services Code on Git:


https://github.com/AnilDeshpande/OrderedBroadcastSample

Home Exercise:

Try to execute the code by your hand from above tutorial.

For next lecture: What is anonymous inner class??

Вам также может понравиться