- Local Broadcast, less overhead and secure in Android
- Basics of Broadcast
- Register Broadcast
- Receive Broadcasts
- Problem with global broadcast
- What is LocalBroadcastManager?
- Implementation
- How to secure broadcasts
- Restrict your app to receive broadcast
- Control receiver of your broadcast
- Conclusion
- Android BroadcastReceiver — Tutorial
- 1. Broadcast receiver
- 1.1. Definition
- 1.2. Implementation
- 1.3. Life cycle of a broadcast receiver
- 1.4. Asynchronous processing
- 1.5. Restrictions for defining broadcast receiver
- 1.6. Send the broadcast to your application for testing
- 1.7. Pending Intent
- 2. System broadcasts
- 3. Automatically starting Services from a Receivers
- 4. Exercise: Register a receiver for incoming phone calls
- 4.1. Target
- 4.2. Create project
- 4.3. Implement receiver for the phone event
- 4.4. Request permission
- 4.5. Validate implementations
- 5. Exercise: System services and receiver
- 5.1. Target
- 5.2. Implement project
- 5.3. Validate implementation
- 6. Dynamic broadcast receiver registration
- 6.1. Dynamically registered receiver
- 6.2. Using the package manager to disable static receivers
- 6.3. Sticky (broadcast) intents
Local Broadcast, less overhead and secure in Android
Apr 28, 2017 · 4 min read
Broadcast receiver is an Android component which allows you to send or receive Android system or application events. All the registered application are notified by the Android runtime once event happens.
It works similar to the publish-subscribe design pattern and used for asynchronous inter-process communication.
For example, applications can register for various system events like boot complete or battery low, and Android system sends broadcast when specific event occur. Any application can also create its own custom broadcasts.
Basics of Broadcast
Let’s discuss some basic concepts of broadcast receiver.
Register Broadcast
There are two ways to register broadcast receiver-
Manife s t-declared (Statically) : By this receiver can be registered via the AndroidManifest.xml file.
Context-registered (Dynamically) : By this register a receiver dynamically via the Context.registerReceiver() method.
Receive Broadcasts
To be able to receive a broadcast, application have to extends the BroadcastReceiver abstract class and override its onReceive() method.
If the event for which the broadcast receiver has registered happens, the onReceive() method of the receiver is called by the Android system.
Problem with global broadcast
It is good practice to use broadcast receivers when you want to send or receive data between different applications. But if the communication is limited to your application then it is not good to use the global broadcast.
In this case Android provides local broadcasts with the LocalBroadcastManager class. Using global broadcast, any other application can also send and receives broadcast messages to and from our application. This can be a serious security thread for our application. Also global broadcast is sent system-wide, so it is not performance efficient.
What is LocalBroadcastManager?
For obvious reasons, global broadcasts must never contain sensitive information. You can, however, broadcast such information locally using the LocalBroadcastManager class, which is a part of the Android Support Library.
The LocalBroadcastManager is much more efficient as it doesn’t need inter-process communication.
Below are some of its benefits:
- Broadcast data won’t leave your app, so don’t need to worry about leaking private data.
- 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.
- It is more efficient than sending a global broadcast through the system.
- No overhead of system-wide broadcast.
Implementation
There is no additional support library dependency required in the latest version of Android Studio. However, if you want to implement local broadcasts in an old project, following dependency needs to be add in the app module’s build.gradle file:
Create a new instance of the LocalBroadcastManager
You can now send local broadcasts using the sendBroadcast() method like
Now create a broadcast receiver that can respond to the local-broadcast action:
Dynamically registered receivers must be unregistered when they are no longer necessary like:
You can find the reference code to implement Local Broadcast receiver from GitHub. In the sample code I have created an IntentService, which broadcasts current date and it is received by an Activity of the same application.
How to secure broadcasts
Restrict your app to receive broadcast
- Specify a permission parameter when registering a broadcast receiver then only broadcasters who have requested the permission can send an Intent to the receiver.
For example, receiving app has a declared SEND_SMS permission in the receiver as shown below:
- Set the android:exported attribute to “false” in the manifest. This restrict to receive broadcasts from sources outside of the app.
- Limit yourself to only local broadcasts with LocalBroadcastManager.
Control receiver of your broadcast
- You can specify a permission when sending a broadcast then only receivers who have requested that permission can receive the broadcast. For example, the following code sends a broadcast:
- In Android 4.0 and higher, you can specify a package with setPackage(String) when sending a broadcast. The system restricts the broadcast to the set of apps that match the package.
- Send local broadcasts with LocalBroadcastManager.
Conclusion
Hope you understand about the global and local broadcasts and their security consideration. To improve the performance of system Android O has changed the registration of broadcast receiver. From Android O you cannot register implicit broadcasts in your application manifest (few exceptions is there) but application can continue to register for explicit broadcasts in their manifests or at run-time. Read more on broadcast receiver at Android official document.
Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful. Stay tuned for upcoming articles. For any quires or suggestions, feel free to hit me on Twitter Google+ LinkedIn
Check out my blogger page for more interesting topics on Software development.
Источник
Android BroadcastReceiver — Tutorial
Using Broadcast receivers in Android. This tutorial describes how to create and consume broadcast receivers in Android.
1. Broadcast receiver
1.1. Definition
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_COMPLETED system 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 Context.registerReceiver() method.
The implementing class for a receiver extends the BroadcastReceiver class.
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 PendingResult type. 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 defining 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.
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 PendingIntent via the getBroadcast() method of the PendingIntent class. To perform an activity via a pending intent, you receive the activity via PendingIntent.getActivity() .
2. System broadcasts
Several system events are defined as final static fields in the Intent class. Other Android system classes also define events, e.g., the TelephonyManager defines events for the change of the phone state.
The following table lists a few important system events.
Event | Description | |
---|---|---|
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 MyPhoneReceiver class.
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.
4.5. Validate implementations
Install your application and simulate a phone call via the emulator controls. Validate that your receiver is called and logs a message to the LogCat view.
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.
Create the following layout.
Create the following broadcast receiver class. This class will get the vibrator service.
Register this class as a broadcast receiver in AndroidManifest.xml and request authorization to vibrate the phone.
Change the code of your AlarmActivity class to the following. This activity creates an intent to start the receiver and register this intent with the alarm manager service.
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.
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 leaked broadcast receiver error. 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 PackageManager class 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 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.
You can retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter) `. This also works for a null `BroadcastReceiver .
In all other ways, this behaves just as sendBroadcast(Intent) .
Sticky broadcast intents typically require special permissions.
Источник