i have a little problem and i'll be very gratefull if you could help me. I have an app like a local database for client medicins, when adding an pill he has the posibility to add a reminder when he needs to take that specific pill. He can set only one hour(temporary) and select some days from the week. So the app is making an alarm for every day at that specific hour, that way my app is making many many alarms, I don't think it is the best way but yhea, that's the way I made it. If it's a beter way to do this please help me. But my main problem now is how can i store the pending intents so I can disable the alarms from respective pill when client wants to delete the medicine.
public class Home extends AppCompatActivity implements View.OnClickListener {
////////////////////DECLARARI///////////////////
LinearLayout[] med = new LinearLayout[11];
TextView[] name = new TextView[11];
TextView[] nr = new TextView[11];
TextView[] plus = new TextView[11];
TextView[] minus = new TextView[11];
TextView[] info = new TextView[11];
public static final String PREFS_NAME = "MyMeds";
////////////////////////////////////////////////
public void calendar(View view, final EditText dateMed){
final Calendar calendar = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String data = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(data, Locale.ENGLISH);
dateMed.setText(sdf.format(calendar.getTime()));
}
};
view.findViewById(R.id.dateMed).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(Home.this, date, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
public void clock(View view, final Calendar setat){
final TextView ora = (TextView)view.findViewById(R.id.clock);
ora.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar time = Calendar.getInstance();
int hour = time.get(Calendar.HOUR_OF_DAY);
int minute = time.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog;
timePickerDialog = new TimePickerDialog(Home.this, new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute){
if(selectedHour < 10 && selectedMinute >= 10) ora.setText("0"+selectedHour + ":" + selectedMinute);
if(selectedHour >= 10 && selectedMinute < 10) ora.setText(selectedHour + ":" + "0" + selectedMinute);
if(selectedHour < 10 && selectedMinute < 10) ora.setText("0" + selectedHour + ":" + "0" + selectedMinute);
if(selectedHour >= 10 && selectedMinute >= 10) ora.setText(selectedHour + ":" + selectedMinute);
setat.set(Calendar.HOUR_OF_DAY, selectedHour);
setat.set(Calendar.MINUTE, selectedMinute);
}
}, hour, minute, true);
timePickerDialog.setTitle("");
timePickerDialog.show();
}
});
}
public void setAlarm(int day , Calendar setat){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, day+1);
calendar.set(Calendar.HOUR_OF_DAY, setat.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, setat.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, 0);
long time = calendar.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
Log.d("day", String.valueOf(calendar.get(Calendar.DAY_OF_WEEK)));
Log.d("time", String.valueOf(setat.get(Calendar.HOUR_OF_DAY)) + ":" + String.valueOf(setat.get(Calendar.MINUTE)));
Log.d("actual", String.valueOf(Calendar.getInstance().get(Calendar.MINUTE)));
Intent intent = new Intent(getApplicationContext(), NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), Calendar.getInstance().get(Calendar.MILLISECOND), intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE);
if(calendar.getTimeInMillis() > System.currentTimeMillis())
Log.d("bigger", "yes");
else
Log.d("bigger", "no");
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
public void addMedNou(){
findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
View view = getLayoutInflater().inflate(R.layout.adddialog, null);
builder.setView(view);
final AlertDialog dialog = builder.create();
final EditText nameMed = (EditText)view.findViewById(R.id.nameMed);
final EditText nrMed = (EditText)view.findViewById(R.id.nrMed);
final EditText comm = (EditText)view.findViewById(R.id.comm);
final EditText dateMed = (EditText)view.findViewById(R.id.dateMed);
FrameLayout add = (FrameLayout)view.findViewById(R.id.add);
FrameLayout cancel = (FrameLayout)view.findViewById(R.id.cancel);
calendar(view, dateMed);
reminder(view);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!nameMed.getText().toString().isEmpty() && !nrMed.getText().toString().isEmpty()){
SharedPreferences valoriSalvate = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = valoriSalvate.edit();
int total = valoriSalvate.getInt("total", 0);
total++;
if(total <= 10){
edit.putInt("total", total);
edit.putString("nume" + total, nameMed.getText().toString());
edit.putInt("nr" + total, Integer.parseInt(nrMed.getText().toString()));
edit.putString("comm" + total, comm.getText().toString());
edit.putString("date" + total, dateMed.getText().toString());
}
edit.commit();
dialog.dismiss();
Intent repeat = new Intent(Home.this, Home.class);
startActivity(repeat);
}
else
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
}
public void reminder(final View view){
view.findViewById(R.id.reminder).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder reminder = new AlertDialog.Builder(Home.this);
final View layout = getLayoutInflater().inflate(R.layout.alarm, null);
reminder.setView(layout);
final AlertDialog dialog = reminder.create();
final Calendar setat = Calendar.getInstance();
clock(layout, setat);
layout.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox[] boxes = new CheckBox[8];
boxes[0] = (CheckBox)layout.findViewById(R.id.check0);
boxes[1] = (CheckBox)layout.findViewById(R.id.check1);
boxes[2] = (CheckBox)layout.findViewById(R.id.check2);
boxes[3] = (CheckBox)layout.findViewById(R.id.check3);
boxes[4] = (CheckBox)layout.findViewById(R.id.check4);
boxes[5] = (CheckBox)layout.findViewById(R.id.check5);
boxes[6] = (CheckBox)layout.findViewById(R.id.check6);
if(boxes[0].isChecked()) {setAlarm(1, setat);}
if(boxes[1].isChecked()) {setAlarm(2, setat);}
if(boxes[2].isChecked()) {setAlarm(3, setat);}
if(boxes[3].isChecked()) {setAlarm(4, setat);}
if(boxes[4].isChecked()) {setAlarm(5, setat);}
if(boxes[5].isChecked()) {setAlarm(6, setat);}
if(boxes[6].isChecked()) {setAlarm(7, setat);}
Toast.makeText(Home.this, "Alarm has been set!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
}
public void declarari(){
for(int i=1;i<=10;i++){
String mID = "m" + i;
String nrID = "nr" + i;
String nameID = "name" + i;
String plusID = "plus" + i;
String minusID = "minus" + i;
String infoID = "info" + i;
int resID = getResources().getIdentifier(mID, "id", getPackageName());
int resNrID = getResources().getIdentifier(nrID, "id", getPackageName());
int resNameID = getResources().getIdentifier(nameID, "id", getPackageName());
int resPlusID = getResources().getIdentifier(plusID, "id", getPackageName());
int resMinusID = getResources().getIdentifier(minusID, "id", getPackageName());
int resInfoID = getResources().getIdentifier(infoID, "id", getPackageName());
med[i] = ((LinearLayout)findViewById(resID));
nr[i] = ((TextView)findViewById(resNrID));
name[i] = ((TextView)findViewById(resNameID));
plus[i] = ((TextView)findViewById(resPlusID));
plus[i].setOnClickListener(this);
minus[i] = ((TextView)findViewById(resMinusID));
minus[i].setOnClickListener(this);
info[i] = ((TextView)findViewById(resInfoID));
info[i].setOnClickListener(this);
}
}
public void afisare(){
SharedPreferences valoriSalvate = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = valoriSalvate.edit();
int total = valoriSalvate.getInt("total", 0);
for(int i=1;i<=total;i++){
med[i].setVisibility(View.VISIBLE);
String keyNume = "nume" + i;
name[i].setText(valoriSalvate.getString(keyNume, null));
String keyNr = "nr" + i;
nr[i].setText(String.valueOf(valoriSalvate.getInt(keyNr, 0)));
}
edit.commit();
}
public void setari(){
findViewById(R.id.setari).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent setari = new Intent(Home.this, setari.class);
startActivity(setari);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
addMedNou();
setari();
declarari();
afisare();
}
@Override
public void onClick(View v){
int actual;
SharedPreferences valoriSalvate = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = valoriSalvate.edit();
AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
View info = getLayoutInflater().inflate(R.layout.infoo, null);
builder.setView(info);
AlertDialog dialog = builder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
TextView title = (TextView)info.findViewById(R.id.title);
TextView pastile = (TextView)info.findViewById(R.id.pastile);
TextView date = (TextView)info.findViewById(R.id.date);
TextView comentariu = (TextView)info.findViewById(R.id.comentariu);
Thanks a lot for the attention and I hope that you can help me a little bit, at least. Have a good day!
There are problems with this code. First off, you say you are setting multiple alarms. In order for you to set multiple alarms, you need to guarantee that each PendingIntent
is unique. You do this:
Intent intent = new Intent(getApplicationContext(), NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
Calendar.getInstance().get(Calendar.MILLISECOND), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
All of your alarms use the same parameters to the PendingIntent
, except for the requestId
parameter (2nd argument), for which you are using the Calendar.MILLISECOND
field. This is not unique. The Calendar.MILLISECOND
will give you a number between 0 and 999 representing the millisecond within the second of the specific timestamp. This is not guaranteed to be unique. It may be and it may not be.
You ask how you can store the PendingIntent
so that you can cancel the alarms. Actually, you don't need to store the PendingIntent
. You can recreate the PendingIntent
in order to cancel the alarm. Just do exactly the same as you did when you set the alarm in the first place. Like this:
Intent intent = new Intent(getApplicationContext(), NotificationService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
Calendar.getInstance().get(Calendar.MILLISECOND), intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Cancel the alarm
AlarmManager alarmManager = (AlarmManager)getApplicationContext()
.getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Now cancel the PendingIntent also (just to be sure)
pendingIntent.cancel();
The trick here is that the requestId
(2nd argument) to the PendingIntent.getBroadcast()
call will need to exactly match the requestId you used when you set the alarm. So you will have to store that. Since the millisecond part of the time isn't unique, you will need to find a better unique number to use as the requestId
. If you set only one alarm every day, you could use the day number as the requestId
, for example Calendar.DAY_OF_WEEK
, or you could use some other unique ID. Use the same value when you set and cancel the alarm.