Given your code sample, you can simply get back an identical PendingIntent with which you can set the alarm and cancel the alarm. The getBroadcast line that you listed will allow you to do this:
PendingIntent.getBroadcast(getApplicationContext(), 2, alarmintent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
For a more complete example, see the following IntentSender and AlarmReceiver classes:
public class IntentSender extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pending_intent);
Button setAlarmButton = (Button) findViewById(R.id.set_alarm_button);
Button cancelAlarmButton = (Button) findViewById(R.id.cancel_alarm_button);
setAlarmButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Intent alarmintent = new Intent(IntentSender.this, AlarmReceiver.class);
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final PendingIntent sender1 = getPendingIntent(alarmintent);
alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, sender1);
}
});
cancelAlarmButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Intent alarmintent = new Intent(IntentSender.this, AlarmReceiver.class);
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final PendingIntent sender1 = getPendingIntent(alarmintent);
alarmManager.cancel(sender1);
}
});
}
private PendingIntent getPendingIntent(final Intent alarmintent) {
return PendingIntent.getBroadcast(getApplicationContext(), 2, alarmintent, PendingIntent.FLAG_UPDATE_CURRENT |
Intent.FILL_IN_DATA);
}
}
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Received the broadcast!", Toast.LENGTH_SHORT).show();
}
}
And here's a layout with two buttons that you can click to set and cancel the alarm:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/set_alarm_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Alarm" />
<Button
android:id="@+id/cancel_alarm_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel Alarm" />
</LinearLayout>
Go ahead and try this out. Click the "Set Alarm" button, wait 2 seconds, and you should see a Toast. For a second test, click "Set Alarm" and then quickly click "Cancel Alarm". You should not see the Toast message.