title: How to have control on the object that started a background process in android, after the application is closed?
body: <p>I used AlarmManager to schedule recurring background task. When an alarm is triggered, a Pending Intent is broadcast by the Android system. The receiver class simply displays a toast repeatedly, every 10 sec. I have created the intent in <strong>startAlarm</strong> method, and cancel in <strong>cancelAlarm</strong> method.
  My problem is: when I close the application after creating the alarm, the toast is getting displayed continuously, and when I reopen the app, I lose control on the object that created the background task, so I cannot cancel it. Help?</p>
  
  <p>Here are the methods that control the alarm :</p>
  
  <pre><code>public void startAlarm(Context context)
  {
      ser=(AlarmManager)context.getSystemService(context.ALARM_SERVICE);
      Intent serviceIntent = new Intent(context, AlarmReceiver.class);
      pi=PendingIntent.getBroadcast(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
      Calendar cal=Calendar.getInstance();
      cal.add(Calendar.SECOND, 10);
      ser.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pi);
  }
  public void cancelAlarm(Context context)
  {
      if (ser != null) 
      {
          ser.cancel(pi);
          ser=null;
          Toast.makeText(context, "Alarm Canceled", Toast.LENGTH_SHORT).show();
      }
  }
  </code></pre>
  
  <p>And here is the receiver class for the alarm:</p>
  
  <pre><code>public class AlarmReceiver extends BroadcastReceiver
  {
      @Override
      public void onReceive(Context arg0, Intent arg1)
      {
      Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
      }
  }
  </code></pre>