Android - Broadcast Receiver

> Android

1 - About

A Broadcast Receiver is a component.

Advertising

3 - 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>         

4 - Snippet

4.1 - 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);

4.2 - 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);
        }
 

5 - Documentation / Reference

Advertising