Android - Broadcast Receiver

Card Puncher Data Processing

About

A Broadcast Receiver is a component.

Declaration

In the manifest

<manifest>

    <application>
         <!-- Declaration of a service broadcast receiver as an intern class of a service. The path to the class may be relative -->
         <receiver
             android:name=".service.myService$myReceiver" 
             android:enabled="true" 
         />
    </application>
    
</manifest>         

Snippet

Call

In a UI element, an activity or a forecast

// The default intent
Intent alarmIntent = new Intent(getActivity(), myService.AlarmReceiver.class);
alarmIntent.putExtra(myService.KEY_VALUE, "value");
// Wrapping the default intent in a pending intent which only fires once.
PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0,alarmIntent,PendingIntent.FLAG_ONE_SHOT);//getBroadcast(context, 0, i, 0);

// Get the alarm manager
AlarmManager am=(AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
// Set the AlarmManager to wake up the system every 5 seconds.
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()  5000, pi);

Implementation

In the service class as an inner class

The onReceive method will get triggered when a Broadcast Intent is fired.

    static public class myReceiver extends BroadcastReceiver {
        
        // The onReceive method will get triggered when a Broadcast Intent is fired.    
        @Override
        public void onReceive(Context context, Intent intent) {
            // Implementation
            Intent sendIntent = new Intent(context, myService.class);
            sendIntent.putExtra(myService.KEY_VALUE, intent.getStringExtra(myService.KEY_VALUE));
            context.startService(sendIntent);
        }
        

Documentation / Reference





Discover More
Card Puncher Data Processing
Android - Broadcast (Message)

A broadcast is a message that any app can receive. The system delivers various broadcasts for system events, such as when the system boots up or the device starts charging. Se also:
Card Puncher Data Processing
Android - Service (background operation without UI interaction)

A Service is a component that performs operations in the background without a user interface. (such as download a file) You start a service by passing an intent. Default Services have a higher priority...



Share this page:
Follow us:
Task Runner