About
A Broadcast Receiver is a component.
Articles Related
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);
}