简体   繁体   中英

How to set alarm based on date and time saved in database android

I am using a custom event to store data in the database, I have subject, description, date, and time. Is it possible to set an alarm based on the date and time inserted in the database? I am trying to retrieve all of dates and time to match up on the current day and exact time. Do you have any idea how to do this?

First you need to get date from db.

String dateTime = row.getString(row.getColumnIndexOrThrow(COLUMN_INDEX));

This, returns a string, parse it and reformat to your local format and time zone:

DateFormat yourDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = yourDateFormat.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing date time failed", e);
}

now set a alarm using below code

Calendar cal = Calendar.getInstance();
cal.setTime(date);

Calendar current = Calendar.getInstance();
if(cal.compareTo(current) <= 0)
{
//The set Date/Time already passed
    Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show();
}
else{
    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
    }

Yes, you can do it by using BroadcastReceiver class in android. You must search and read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM