Search code examples
javaandroidalarmmanager

How to set some alarms using AlarmManager?


I'm making Alarm Application for Android. I wanna set more alarms using AlarmManager. How can I do it? As far as I know, I need to use PendingIntent with different request code to set some alarms. I was trying to increment a static variable and I did it but if user reload the application the variable has request code as zero. How can I set some alarms even after a reloading my application?

I have one activity

public class NewAlarmActivity extends AppCompatActivity {
private Calendar calendar;

private static int REQUEST_CODE_ALARM = 0;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_alarm);

    showTimePickerDialog();

    FloatingActionButton floatingActionButton = findViewById(R.id.fb_save_alarm);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveAlarm();
        }
    });
}

// set time for an alarm
private void showTimePickerDialog() {
    calendar = Calendar.getInstance();

    TimePickerDialog timePickerDialog = new TimePickerDialog(NewAlarmActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_DARK, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
        }
    }, Calendar.HOUR_OF_DAY, Calendar.MINUTE, true);

    timePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            finish();
        }
    });

    timePickerDialog.show();
}

// get full time like a '05:45'
private String getFullTime(int hour, int minute) {
    String h = String.valueOf(hour);
    String m = String.valueOf(minute);

    if (hour < 10) h = "0" + hour;
    if (minute < 10) m = "0" + minute;

    return h + ":" + m;
}

private void saveAlarm() {
    setAlarm();
    insertIntoSQLite();
    finish();
}

private void setAlarm() {
    Intent intent = new Intent(NewAlarmActivity.this, AlarmReceiver.class);
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), ++REQUEST_CODE_ALARM, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (alarmManager != null) {
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }
}

private void insertIntoSQLite() {
    DBHelper dbHelper = new DBHelper(NewAlarmActivity.this);
    SQLiteDatabase database = dbHelper.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put("time", getFullTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE)));
    contentValues.put("description", et_description.getText().toString());

    database.insert("alarm", null, contentValues);

    dbHelper.close();
    }
}

Solution

  • You can save small data to sharedPreference. To save your REQUEST_CODE_ALARM value do this

    SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
    editor.putInt("Request_code", REQUEST_CODE_ALARM);
    editor.apply()
    

    To retrieve it

    SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
    int Request_code = prefs.getInt("REQUEST_CODE_ALARM", 0); //0 is the default value.
    

    I dont suggest you to use SQL database for this purpose because SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through.