- Android — Broadcast Receivers
- Creating the Broadcast Receiver
- Registering Broadcast Receiver
- Broadcast-Receiver
- Broadcasting Custom Intents
- Example
- 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
Android — Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. These messages are sometime called events or intents. For example, applications can also initiate broadcasts to let other applications know that some data has been downloaded to the device and is available for them to use, so this is broadcast receiver who will intercept this communication and will initiate appropriate action.
There are following two important steps to make BroadcastReceiver works for the system broadcasted intents −
Creating the Broadcast Receiver.
Registering Broadcast Receiver
There is one additional steps in case you are going to implement your custom intents then you will have to create and broadcast those intents.
Creating the Broadcast Receiver
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and overriding the onReceive() method where each message is received as a Intent object parameter.
Registering Broadcast Receiver
An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.
Broadcast-Receiver
Now whenever your Android device gets booted, it will be intercepted by BroadcastReceiver MyReceiver and implemented logic inside onReceive() will be executed.
There are several system generated events defined as final static fields in the Intent class. The following table lists a few important system events.
Sr.No | Event Constant & Description | |||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Step | Description |
---|---|
1 | You will use Android studio to create an Android application and name it as My Application under a package com.example.tutorialspoint7.myapplication as explained in the Hello World Example chapter. |
2 | Modify main activity file MainActivity.java to add broadcastIntent() method. |
3 | Create a new java file called MyReceiver.java under the package com.example.tutorialspoint7.myapplication to define a BroadcastReceiver. |
4 | An application can handle one or more custom and system intents without any restrictions. Every intent you want to intercept must be registered in your AndroidManifest.xml file using tag |
5 | Modify the default content of res/layout/activity_main.xml file to include a button to broadcast intent. |
6 | No need to modify the string file, Android studio take care of string.xml file. |
7 | Run the application to launch Android emulator and verify the result of the changes done in the application. |
Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have added broadcastIntent() method to broadcast a custom intent.
Following is the content of MyReceiver.java:
Following will the modified content of AndroidManifest.xml file. Here we have added tag to include our service:
Following will be the content of res/layout/activity_main.xml file to include a button to broadcast our custom intent −
Let’s try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment set-up. To run the app from Android studio, open one of your project’s activity files and click Run icon from the tool bar. Android Studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display following Emulator window −
Now to broadcast our custom intent, let’s click on Broadcast Intent button, this will broadcast our custom intent «com.tutorialspoint.CUSTOM_INTENT» which will be intercepted by our registered BroadcastReceiver i.e. MyReceiver and as per our implemented logic a toast will appear on the bottom of the the simulator as follows −
You can try implementing other BroadcastReceiver to intercept system generated intents like system boot up, date changed, low battery etc.
Источник
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.
Источник