Okay, it goes like this; DeviceListActivity initiates an alarm. Then, AlarmReceiver creates an activity which is called AlarmActivity to do some work and stop the alarm and terminate itself. But I could not manage to stop the alarm. My codes are given below.
DeviceListActivity:
public void startAlarm(View view) {
Calendar calNow = Calendar.getInstance();
calNow.set(Calendar.SECOND, calNow.get(Calendar.SECOND) + 1);
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calNow.getTimeInMillis(), pendingIntent);
}
AlarmReceiver:
public void onReceive(Context context, Intent intent) {
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
Intent alarmActivity = new Intent();
alarmActivity.setClassName(context.getPackageName(),AlarmActivity.class.getName());
alarmActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarmActivity);
}
AlarmActivity:
public void stopAlarm(View view) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
finish();
}