bharathi bharathi - 1 year ago 170
Android Question

Android-Broadcast Receiver

I am new to android. I what to know the difference between

. I am more confused with

Please help me out. Simple code will be helpful.

Answer Source

Ok, I will explain it with an example.

Let's suppose I want to create an app to check subway status from it's webpage. I also want a system notification if the subway is not working ok.

I will have:

  • An Activity to show results.
  • A Service to check if the subway is working and show a notification if it's not working.
  • A Broadcast Receiver called Alarm Receiver to call the service every 15 minutes.

Let me show you some code:

/* */
public class AlarmReceiver extends BroadcastReceiver {
    public static final String ACTION_REFRESH_SUBWAY_ALARM =

    public void onReceive(Context context, Intent intent) {
        Intent startIntent = new Intent(context, StatusService.class);

Explanation: As you can see you can set an alarm. and when the alarm is received we use an intent to start the service. Basically the intent is a msg which can have actions, an serialized stuff.

public class StatusService extends Service {

    public void onCreate() {
        mAlarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intentToFire = new Intent(AlarmReceiver.ACTION_REFRESH_ALARM);
        mAlarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);

    public void onStart(Intent intent, int arg1) {
        super.onStart(intent, arg1);
        Log.d(TAG, "SERVICE STARTED");
        Log.d(TAG, "Performing update!");
        new SubwayAsyncTask().execute();

    private void setAlarm() {
        int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
        mAlarms.setInexactRepeating(alarmType, SystemClock.elapsedRealtime() + timeToRefresh(),
                    AlarmManager.INTERVAL_HALF_DAY, mAlarmIntent);



The service starts and:

  • Set the alarm for the next call. (Check the intent it's used. Just a msg)
  • Calls an AsyncTask which takes care of updating an notifying the Activity

It doesn't make sense to paste the AsyncTask but when it finished it calls:

private void sendSubwayUpdates(LinkedList<Subway> subways) {
      Intent intent = new Intent(NEW_SUBWAYS_STATUS);
      intent.putExtra("subways", subways);


This creates a new Intent with a certain NEW_SUBWAYS_STATUS action, put inside the intent the subways and sendBroadcast. If someone is interested in getting that info, it will have a receiver.

I hope I made myself clear.

PS: Some days ago someone explained broadcast and intents in a very cool way. Someone wants to share his beer, so he sends a broadcast with an intent having action:"FREE_BEER" and with an extra: "A glass of beer".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download