Check Mobile App
Read now

Using Broadcast Reciever with Services

Save

A Broadcast Reciever is an android component which allows us to register the system or application events. A Broadcast Reciever is simply called as Reciever. When an event happens the all registered receivers are notified.

For example, ACTION_BOOT_COMPLETED system event which is fired once the Android system has completed the boot process.

We can register a Reciever via two ways: static and dynamic.

Registering via AndroidManifest.xml is the static way and for dynamic registration, we can use Context.registerReceiver() method.

For implementing receivers, extends the BroadcastReceiver class.

Android system calls the onReceive() method If the event for which the broadcast receiver has registered happens.

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.

 

Starting Services automatically  from a Receivers

On system reboot, data can be automatically  synchronized when a service started.  For this, we can register a receiver for the android.intent.action.BOOT_COMPLETED system event. This requires the android.permission.RECEIVE_BOOT_COMPLETED permission in AndroidManifest.xml.

 

Example

1. Adding permissions in AndroidManifest.xml

2. Code for performing actions:

 

3. Service 


 

If our application is installed on sd-card then register it for the android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE event.

“Android API level 11 the user needs to have started the application at least once before an application can receive android.intent.action.BOOT_COMPLETED events.”

Pending Intent

A pending intent is a token that you give to another application (e.g., notification manager, alarm manager or other 3rd party applications), which allows this other application to use 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().

 

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!

Deniel Kerr

Owner and Founder. Opencart

Talk to Sales
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home