I wanted to create a few number of alarms which has different times and canceled them one by one when I select each. I could create few alarms. But I have no idea how to cancel them when I select.
Currently, alarm canceling process is working for the last alarm which I put.
This is my work,
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TimePicker myTimePicker;
Button buttonstartSetDialog;
Button buttonCancelAlarm;
TextView textAlarmPrompt;
Button buttonstartSetDialogOne;
Button buttonstartSetDialogTwo;
Button buttonstartSetDialogThree;
TextView textAlarmPromptOne;
TextView textAlarmPromptTwo;
TextView textAlarmPromptThree;
TimePickerDialog timePickerDialog;
int RQS_1 = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textAlarmPrompt = (TextView) findViewById(R.id.alarmprompt);
textAlarmPromptOne = (TextView) findViewById(R.id.alarmpromptOne);
textAlarmPromptTwo = (TextView) findViewById(R.id.alarmpromptTwo);
textAlarmPromptThree = (TextView) findViewById(R.id.alarmpromptThree);
buttonstartSetDialog = (Button) findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textAlarmPrompt.setText("");
openTimePickerDialog(false);
}
});
buttonstartSetDialogOne = (Button) findViewById(R.id.startSetDialogOne);
buttonstartSetDialogOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RQS_1=2;
textAlarmPromptOne.setText("");
openTimePickerDialog(false);
}
});
buttonstartSetDialogTwo=(Button) findViewById(R.id.startSetDialogTwo);
buttonstartSetDialogTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RQS_1=3;
textAlarmPromptTwo.setText("");
openTimePickerDialog(false);
}
});
buttonstartSetDialogThree=(Button) findViewById(R.id.startSetDialogThree);
buttonstartSetDialogThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RQS_1=4;
textAlarmPromptThree.setText("");
openTimePickerDialog(false);
}
});
buttonCancelAlarm = (Button) findViewById(R.id.cancel);
buttonCancelAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
cancelAlarm(RQS_1);
}
});
}
private void openTimePickerDialog(boolean is24r) {
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
MainActivity.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24r);
timePickerDialog.setTitle("Set Alarm Time");
timePickerDialog.show();
}
TimePickerDialog.OnTimeSetListener onTimeSetListener
= new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if (calSet.compareTo(calNow) <= 0) {
//Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet,RQS_1);
}
};
private void setAlarm(Calendar targetCal,int RQS) {
if(RQS==1){
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}else if(RQS==2){
textAlarmPromptOne.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}else if(RQS==3){
textAlarmPromptTwo.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}else if(RQS==4){
textAlarmPromptThree.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
}
private void cancelAlarm(int RSQ) {
if(RSQ==1){
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm Cancelled! \n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RSQ, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}else if(RSQ==2){
textAlarmPromptOne.setText(
"\n\n***\n"
+ "Alarm Cancelled! \n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RSQ, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}else if(RSQ==3){
textAlarmPromptTwo.setText(
"\n\n***\n"
+ "Alarm Cancelled! \n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RSQ, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}else if(RSQ==4){
textAlarmPromptThree.setText(
"\n\n***\n"
+ "Alarm Cancelled! \n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RSQ, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
}
AlarmReceiver.java
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;
import android.support.v4.app.NotificationCompat;
/**
* Created by PC2 on 1/18/2017.
*/
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_LONG).show();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("New Alarm")
.setContentText("Countdown").setSound(alarmSound)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(0, mNotifyBuilder.build());
}
}
Have any about my problem ?
Too much of a code,your code seems to work fine
To cancel all alarams use must cancel them one by one and would need all request codes
private void cancelAlarm(int RSQ) {
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm Cancelled! \n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RSQ, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
And then use to cancel each one individually
cancelAlarm(1);
cancelAlarm(2);
cancelAlarm(3);
cancelAlarm(4);
To cancel all
for(int i=1;i<5;i++)
{
cancelAlarm(i);
}
Related
I'm trying 1 month now to make a feature witch sends to the user one notification daily at the time the user has selected but when the onTimeSet() called i'm getting only this error below and the Notification is not coming to the user
I try these solutions below:
removing all code from onTimeSet() & startAlarm() inside my activity
changing this to SetNotificationActivity.this
Invalidate chaches / restart
Error:
E/InputDispatcher: Window handle Window{838da5a u0 com.george.igrow/com.george.igrow.SetNotificationActivity} has no registered input channel
SetNotificationActivity.java:
public class SetNotificationActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notification);
final Button setAlarm = findViewById(R.id.buttonAlarm);
final Button skip_btn = findViewById(R.id.button4);
setAlarm.setOnClickListener(v -> {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
});
skip_btn.setOnClickListener(v -> {
finish();
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
startAlarm(c);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance()))
c.add(Calendar.DATE, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
}
}
AlertReceiver.java:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SplashScreenActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Send notification for the current Alarm
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
//nb.setContentIntent(pendingIntent);
notificationHelper.getManager().notify(1, nb.build());
}
}
I'm trying to make my app issue a notification at a specific time(using timePicker) and repeat it daily(using setRepeat method).
Everything is working fine until I cancel the alarm to check if cancellation works or not. But after canceling the alarm if I set the alarm again to issue a notification, it just doesn't work unless my app is running.
I've turned an activity into a dialog and starting with startActivityForResult, getting time setting on the calendar which alarm manager uses. Thanks in advance.
NotificationCenter.class (java file of the activity cum dialog):
// IMPLEMENTATION OF TIME PICKER'S TIME CHANGE EVENT
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
savedHour = hourOfDay;
savedMinute = minute;
}
});
// IMPLEMENTATION OF SAVE BUTTON
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//using this for couple of reasones
Boolean isNotification = notificationSwitch.isChecked();
editor.putBoolean("isNotification", isNotification);
editor.putInt("saved_hour", savedHour);
editor.putInt("saved_minute", savedMinute);
editor.putBoolean("hasTimeSaved", true);
editor.apply();
//sending this intent to mainActivity as a result
Intent result = new Intent();
result.putExtra("saved_hour", savedHour);
result.putExtra("saved_minute", savedMinute);
setResult(2, result);
finish();
}
});
MainActivity.xml
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To remove status bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
// ALARM SERVICE FOR NOTIFICATION
alarmService = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar = Calendar.getInstance();
preferences = PreferenceManager.getDefaultSharedPreferences(this);
alertIntent = new Intent(this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// GET THE NOTIFICATION LINEAR LAYOUT AND SET AN ON CLICK LISTENER TO IT
LinearLayout notificationManager = (LinearLayout) findViewById(R.id.notification_manager);
notificationManager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(new Intent(getApplicationContext(), NotificationCenter.class), 11);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 11) {
Toast.makeText(this,"request_code_ok", Toast.LENGTH_SHORT).show();
if (resultCode == 2) {
Toast.makeText(this,"result_code_ok", Toast.LENGTH_SHORT).show();
if (preferences.getBoolean("isNotification", false)) {
Toast.makeText(this, "true", Toast.LENGTH_SHORT).show();
int savedHour = data.getIntExtra("saved_hour", 0);
int savedMinute = data.getIntExtra("saved_minute", 0);
calendar.set(Calendar.HOUR_OF_DAY, savedHour);
calendar.set(Calendar.MINUTE, savedMinute);
calendar.set(Calendar.SECOND, 1);
Intent alertIntent = new Intent(this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmService.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
} else {
alarmService.cancel(pendingIntent);
Toast.makeText(this,"alarm_cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}
MyBroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// NOTIFICATION
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setTicker("Alert!")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, ChapterOne.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ChapterOne.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setPriority(2);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify( 0,mBuilder.build());
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="false"/>
<service android:name=".NotificationService" android:enabled="true" android:exported="false"/>
I am having an Calendar Event with start date as (24hrs format) 27-Apr-2016 11:00:00 and end date as 29-Apr-2016 11:00:00. I am having three timings 10:45:00, 10:30:00 and 10:15:00 which are calculated for alerting the event prior to the actual set timings (i.e 15 mins, 30 mins and 45 mins early to the start date).
Also the alarm must repeat daily for the same prior timings till the end date is reached.
Here is how i tried to do it, How ever the below code does not invoke the alarm nor it repeats daily
In the MainActivity.java
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, Broadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(2016,03,27,11,00,00);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*15), pendingIntent); // subtract for 15 mins prior alarm time
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*30), pendingIntent); // subtract for 30 mins prior alarm time
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*45), pendingIntent); // subtract for 45 mins prior alarm time
In the Broadcast.java
Log.i("Alarm", "Alarm Manager is called");
Toast.makeText(context, new Date().toString(), Toast.LENGTH_SHORT).show();
How can I achieve this? Please help
Here is my sample code, Try this:
Modify the date and time as your need in the below code.
public static int REPEAT_NOTIFICATION1 = 201;
public static int REPEAT_NOTIFICATION2 = 202;
public static int REPEAT_NOTIFICATION3 = 203;
private void repeatNotification() {
final DateTime dateTime1 = DateTime.now();
dateTime1.hourOfDay().setCopy(7);
dateTime1.minuteOfHour().setCopy(30);
dateTime1.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime1 = Calendar.getInstance();
calendarNotifiedTime1.set(Calendar.HOUR, dateTime1.getHourOfDay());
calendarNotifiedTime1.set(Calendar.MINUTE, dateTime1.getMinuteOfHour());
calendarNotifiedTime1.set(Calendar.SECOND, dateTime1.getSecondOfMinute());
calendarNotifiedTime1.set(Calendar.AM_PM, Calendar.AM);
final DateTime dateTime2 = DateTime.now();
dateTime2.hourOfDay().setCopy(12);
dateTime2.minuteOfHour().setCopy(30);
dateTime2.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime2 = Calendar.getInstance();
calendarNotifiedTime2.set(Calendar.HOUR, dateTime2.getHourOfDay());
calendarNotifiedTime2.set(Calendar.MINUTE, dateTime2.getMinuteOfHour());
calendarNotifiedTime2.set(Calendar.SECOND, dateTime2.getSecondOfMinute());
calendarNotifiedTime2.set(Calendar.AM_PM, Calendar.PM);
final DateTime dateTime3 = DateTime.now();
dateTime3.hourOfDay().setCopy(6);
dateTime3.minuteOfHour().setCopy(30);
dateTime3.secondOfMinute().setCopy(00);
final Calendar calendarNotifiedTime3 = Calendar.getInstance();
calendarNotifiedTime3.set(Calendar.HOUR, dateTime3.getHourOfDay());
calendarNotifiedTime3.set(Calendar.MINUTE, dateTime3.getMinuteOfHour());
calendarNotifiedTime3.set(Calendar.SECOND, dateTime3.getSecondOfMinute());
calendarNotifiedTime3.set(Calendar.AM_PM, Calendar.PM);
Intent intent1 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent1.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime1.getHourOfDay() + ":" + dateTime1.getMinuteOfHour() + ":" + dateTime1.getSecondOfMinute());
Intent intent2 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent2.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime2.getHourOfDay() + ":" + dateTime2.getMinuteOfHour() + ":" + dateTime2.getSecondOfMinute());
Intent intent3 = new Intent(EmptyActivity.this, NotificationReceiver.class);
intent3.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime3.getHourOfDay() + ":" + dateTime3.getMinuteOfHour() + ":" + dateTime3.getSecondOfMinute());
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION1, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION2, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION3, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
cancelNotification(REPEAT_NOTIFICATION1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent1);
cancelNotification(REPEAT_NOTIFICATION2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2);
cancelNotification(REPEAT_NOTIFICATION3);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime3.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent3);
}
Cancel Notification:
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(getApplicationContext(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadCast Receiver:
public class NotificationReceiver extends BroadcastReceiver {
public static String NOTIFICATION_MESSAGE = "notificationMessage";
public static int REPEAT_NOTIFICATION1 = 201;
public static int REPEAT_NOTIFICATION2 = 202;
public static int REPEAT_NOTIFICATION3 = 203;
Context context;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
//Assume StartDate = yesterday.
DateTime startDate = DateTime.now().minusDays(1);
//Assume EndDate = tomorrow
DateTime endDate = startDate.plusDays(2);
DateTime today = DateTime.now();
if (today.isBefore(endDate) || today.isEqual(endDate)) {
String message = intent.getStringExtra(NOTIFICATION_MESSAGE);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, EmptyActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
final DateTime dateTime = DateTime.now();
int color = 0xffffaa00;
// int color1 = context.getColor(R.color.notificatinBackgroundColor);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.festi_push_message_small);
builder.setContentIntent(pendingIntent);
builder.setContentTitle("Notification Sample");
builder.setAutoCancel(true);
builder.setContentText(message + ", Current Time : " + dateTime.getHourOfDay() + ":" + dateTime.getMinuteOfHour() + ":" + dateTime.getSecondOfMinute());
builder.setSound(soundUri);
builder.setLights(Color.RED, 1000, 1000);
builder.setColor(color);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(102938, notification);
} else {
cancelNotification(REPEAT_NOTIFICATION1);
cancelNotification(REPEAT_NOTIFICATION2);
cancelNotification(REPEAT_NOTIFICATION3);
}
}
public void cancelNotification(int requestCode) {
try {
Intent notificationIntent = new Intent(context, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest.xml
<receiver android:name=".NotificationReceiver" />
I'm creating an alarm clock using AlarmManager and I have some troubles:
How to stop sounding of notification when I open Notification?
How to make alarm for a certain day of week (or the whole week), not for the certain date?
private void restartNotify()
{
Calendar calendar = Calendar.getInstance();
// current Month - 1
calendar.set(Calendar.MONTH, 5);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 28);
calendar.set(Calendar.HOUR_OF_DAY, 1);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
Intent timeIntent = new Intent(MainActivity.this, TimeNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, timeIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
public class TimeNotification extends WakefulBroadcastReceiver
{
#Override
public void onReceive(final 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();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class AlarmService extends IntentService
{
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent)
{
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg)
{
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.abc_btn_radio_material)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
}
I am having some problem when trying to cancel AlarmManager in Android. I am calling this retrieveBudget() onCreate:
public void retrieveBudget() {
txtDisplayMonthlyExpenses = (TextView) findViewById(R.id.txtDisplayMonthlyExpense);
txtDisplayBudget = (TextView) findViewById(R.id.txtDisplayBudget);
cbDisplayReminderNotify = (CheckBox) findViewById(R.id.cbDisplayReminderNotify);
cbDisplayReminderNotify.setEnabled(false);
DatabaseAdapter mDbHelper = new DatabaseAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
TransactionRecController trc = new TransactionRecController(
mDbHelper.open());
currentMonthExpense = trc.getThisMonthDebit();
txtDisplayMonthlyExpenses.setText("$ "
+ formatter.format(currentMonthExpense));
BudgetController bc = new BudgetController(mDbHelper.open());
BudgetModel bm = bc.getBudget();
if (bm.getBudgetAmount() != 0 && bm.getReminderNotify() != null) {
budget = bm.getBudgetAmount();
txtDisplayBudget.setText("$ " + formatter.format(budget));
if (bm.getReminderNotify().equals("Y")) {
cbDisplayReminderNotify.setChecked(true);
} else {
cbDisplayReminderNotify.setChecked(false);
}
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = null;
if (bm.getReminderNotify().equals("Y")
&& currentMonthExpense > budget) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
notificationCount = notificationCount + 1;
Intent notificationIntent = new Intent(context,
BudgetAlarm.class);
notificationIntent.putExtra("NotifyCount", notificationCount);
pi = PendingIntent.getBroadcast(context, notificationCount,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60000, pi);
} else {
mgr.cancel(pi);
}
} else {
txtDisplayBudget.setText("No budget record yet");
}
mDbHelper.close();
}
And inside my budgetAlarm class, it just simply setting the notification. So my problem is it did execute the notification every minute. But after I changed my reminderNotify to "N" instead of "Y", it does not cancel the alarm manager. I wonder why is it so because after my update SQL statement, I am calling this retrieveBudget() again.
Thanks in advance.
EDIT
These are the codes where I update the budget part. I am calling the the retrieveBudget() once again when the Okay from dialogue box was clicked.
public void onEditBudgetClicked(View view) {
AlertDialog.Builder EditDialog = new AlertDialog.Builder(this);
EditDialog.setTitle("Edit Budget");
// Get the components from XML file
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.edit_budget, null);
txtEditBudgetAmount = (EditText) dialogView
.findViewById(R.id.txtEditBudgetAmount);
cbEditReminderNotify = (CheckBox) dialogView
.findViewById(R.id.cbEditReminderNotify);
// Retrieve budget record
DatabaseAdapter mDbHelper = new DatabaseAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
BudgetController bc = new BudgetController(mDbHelper.open());
BudgetModel bm = bc.getBudget();
if (bm.getBudgetAmount() != 0 && bm.getReminderNotify() != null) {
txtEditBudgetAmount.setText(Float.toString(bm.getBudgetAmount()));
if (bm.getReminderNotify().equals("Y")) {
cbEditReminderNotify.setChecked(true);
editReminderNotify = "Y";
} else {
cbEditReminderNotify.setChecked(false);
}
}
mDbHelper.close();
cbEditReminderNotify.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (cbEditReminderNotify.isChecked()) {
editReminderNotify = "Y";
} else {
editReminderNotify = "N";
}
}
});
EditDialog.setView(dialogView);
EditDialog.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
onEditBudgetSubmitClicked();
dialog.dismiss();
retrieveBudget();
}
});
EditDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
EditDialog.show();
}
The value of notification count used while initializing the pending intent at the time creation and cancellation of the alarm manager should be same.
Use same value of requestFalg in the pending intent.
Replace this part:
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = null;
if (bm.getReminderNotify().equals("Y")
&& currentMonthExpense > budget) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
notificationCount = notificationCount + 1;
Intent notificationIntent = new Intent(context,
BudgetAlarm.class);
notificationIntent.putExtra("NotifyCount", notificationCount);
pi = PendingIntent.getBroadcast(context, notificationCount,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60000, pi);
} else {
mgr.cancel(pi);
}
with
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context,
BudgetAlarm.class);
PendingIntent pi = null;
if (bm.getReminderNotify().equals("Y")
&& currentMonthExpense > budget) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
notificationCount = notificationCount + 1;
notificationIntent.putExtra("NotifyCount", notificationCount);
pi= PendingIntent.getBroadcast(context, 1,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60000, pi);
} else {
pi= PendingIntent.getBroadcast(context, 1,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.cancel(pi);
}
if you changed the value of requestFlag (in your case notificationcount)while initializing the pending intent after launching the alarm, you won't be able to cancel it.
Use same value of requestFlag in the pending intent while creating and cancelling the alarm. Here, I am using 1.
Since you are changing the value of notificationFlag after launching the alarm manager, don't use notificationFlag as a requestFlag. Use a constant integer value as a requestFlag while initializing pi inside both if and else part.
pi= PendingIntent.getBroadcast(context, CONSTANT_INTEGER,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
check the link below:
PendingIntent getBroadcast (Context context, int requestCode, Intent intent, int flags)
http://developer.android.com/reference/android/app/PendingIntent.html#getBroadcast%28android.content.Context,%20int,%20android.content.Intent,%20int%29
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = null;
if (bm.getReminderNotify().equals("Y")
&& currentMonthExpense > budget) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
notificationCount = notificationCount + 1;
Intent notificationIntent = new Intent(context,
BudgetAlarm.class);
notificationIntent.putExtra("NotifyCount", notificationCount);
pi = PendingIntent.getBroadcast(context, notificationCount,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60000, pi);
} else {
notificationCount = notificationCount + 1;
Intent notificationIntent = new Intent(context,
BudgetAlarm.class);
notificationIntent.putExtra("NotifyCount", notificationCount);
pi = PendingIntent.getBroadcast(context, notificationCount,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.cancel(pi);
}