I need help. Im new to android coding.
I have made task list, which I want to do specific things at time written in task.
Here is my task item
private long id;
private int mon;
private int tues;
private int wednes;
private int thurs;
private int fri;
private int satur;
private int sun;
private int profile;
Where I have days (monday,tuesday etc) which holds amount of minutes (for 10:00 its 600).
Following some tutorials I have alarm reciever
public class AlarmReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
try {
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm_message");
Intent newIntent = new Intent(context, AlarmActivity.class);
newIntent.putExtra("profile", message);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);
} catch (Exception e) {
Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
Its still unedited...
And then there is code which calls to make new tasks in alarm manager
// get a Calendar object with current time
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 5);
Intent intent = new Intent(ctx, AlarmReceiver.class);
intent.putExtra("alarm_message", "O'Doyle Rules!");
// In reality, you would want to have a static variable for the request code instead of 192837
PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
I dont understand how to specify in calendar, that I need new task repeating (for example) every monday at 10:00, and that when this happens, it calls new function, giving it "profile" variable to work with.
private void setProfile(Integer profile)
{
// Doing things with profile
}
take a look at the following code:
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent2 = new Intent(context, SampleAlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent2, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
// Set the alarm's trigger time to item hour
calendar.set(Calendar.HOUR_OF_DAY, NuevoItemActivity.hora.getCurrentHour());
calendar.set(Calendar.MINUTE, NuevoItemActivity.hora.getCurrentMinute());
// Set the alarm to fire , according to the device's clock, and to repeat once a day.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, (PendingIntent) alarmIntent);
As you can see in last line, you are able to indicate AlarmManager.INTERVAL_DAY to repeat the PendingIntent.
Related
I am new to android programming. I am developing an app which has a local notification. I am using Alarmmanager to set a local notification.
When I set the same time to Alarmmanager onReceive is called once for that time. My pending intent is also different.
Here how I am setting alarm:
for(int i = 0; i < dosageDtoList.size();i++)
{
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
DosageDto dosageDto = dosageDtoList.get(i);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String time = dosageDto.getReminderTime();
String dateTime = startDateStr + " " + time;
Date formattedDate = simpleDateFormat.parse(dateTime);
Calendar cal = Calendar.getInstance();
cal.setTime(formattedDate);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
notificationIntent.putExtra(Constants.POS,i);
notificationIntent.putExtra(Constants.END_DATE, endDateStr);
notificationIntent.putExtra(Constants.TITLE, userDrugDto.getUserName());
notificationIntent.putExtra(Constants.SUB_TITLE, userDrugDto.getDrugName());
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent broadcast = PendingIntent.getBroadcast(context, i, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if(alarmManager != null)
{
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, broadcast);
}
}
Here is my Receiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// generating notification
}
}
If I set an alarm for these two dates and time
1. 01-June-2018 15:10
2. 01-June-2018 15:10
With different pending intent ideally onReceive should be called twice but it getting called once.
Am I missing something?
i am developing a scheduling app in which user selects a time from listview like 9:30 P.M or any time which is in the list and hits the button stop schedule, what i want want to stop schedule at 9:30 when its 9:30 (i will cal update method in database and update the user end time) or which the user selects from the list, user can also stop multiple schedules at a same time, i tried to use Scheduling Repeating Alarms but did not find any solution.
Please help me how can i do this?.
This is code i am making alarm for specific time
#TargetApi(Build.VERSION_CODES.N)
public void scheduleAlarm(View view, String timeEnd,String id) {
StringTokenizer tokens = new StringTokenizer(timeEnd, ":");
String first = tokens.nextToken();
String second = tokens.nextToken();
StringTokenizer token = new StringTokenizer(second, " ");
String two = token.nextToken(); // just changing given time into like 9:30 to 9 and 30
AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
android.icu.util.Calendar calendar = android.icu.util.Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(android.icu.util.Calendar.HOUR_OF_DAY, Integer.parseInt(first));
calendar.set(android.icu.util.Calendar.MINUTE, Integer.parseInt(two));
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
intent.putExtra("ID",id);
intent.putExtra("EndTime",timeEnd);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
}
And this is the Broadcast Receiver its works but broadcast class trigger at same time when i give the time to alarm schedule not on the given time.
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SQLITEDBTABLE sqLiteDatabase = new SQLITEDBTABLE(context);
String id = intent.getStringExtra("ID");
String time_end = intent.getStringExtra("EndTime");
sqLiteDatabase.update(time_end, id);
/* sqLiteDatabase.deleteOlderData(laterId);
sqLiteDatabase.deleteInactive(laterId);
sqLiteDatabase.updateEmployee(laterId, "Inactive");*/
//Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();
}
}
Remove this line
calendar.setTimeInMillis(System.currentTimeMillis());
From the code..... Calendar.getInstance() is already up to date. So you have.
#TargetApi(Build.VERSION_CODES.N)
public void scheduleAlarm(View view, String timeEnd,String id) {
StringTokenizer tokens = new StringTokenizer(timeEnd, ":");
String first = tokens.nextToken();
String second = tokens.nextToken();
StringTokenizer token = new StringTokenizer(second, " ");
String two = token.nextToken(); // just changing given time into like 9:30 to 9 and 30
AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
android.icu.util.Calendar calendar = android.icu.util.Calendar.getInstance();
calendar.set(android.icu.util.Calendar.HOUR_OF_DAY, Integer.parseInt(first));
calendar.set(android.icu.util.Calendar.MINUTE, Integer.parseInt(two));
Intent intent = new Intent(getApplicationContext(), AlarmReciever.class);
intent.putExtra("ID",id);
intent.putExtra("EndTime",timeEnd);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
This is the code to set u and delete the notifications. please let me know if you need more details. The only solutions on stack overflow are about the pending intent to be same. I already tried that solution and it didn't work.
public void setAlarm () throws java.text.ParseException {
RealmResults<Reminder> realmResults = getAllLatest();
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Reminder reminder = getLatestReminder(realmResults);
int hour = convertTimeToHoursAndMinutes(reminder.getReminderTime()).getHours();
int minutes = convertTimeToHoursAndMinutes(reminder.getReminderTime()).getMinutes();
PendingIntent pendingIntent = getPendingIntentFromReminder(reminder);
Log.v("Reminder is: ", String.valueOf(reminder));
Calendar calendar = Calendar.getInstance();
//calendar.setTimeZone(TimeZone.getTimeZone());
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pendingIntent);
}
private PendingIntent getPendingIntentFromReminder(Reminder reminder) throws ParseException {
int hour = convertTimeToHoursAndMinutes(reminder.getReminderTime()).getHours();
int minutes = convertTimeToHoursAndMinutes(reminder.getReminderTime()).getMinutes();
Intent intent = new Intent(this, MyReceiver.class);
intent.setAction(reminder.getName());
Uri data = Uri.withAppendedPath(Uri.parse("TYS"),
String.valueOf(reminder.getId()));
intent.setData(data);
Calendar calendar = Calendar.getInstance();
//calendar.setTimeZone(TimeZone.getTimeZone());
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
//Log.v("Test", calendar.getTimeZone().toString());
// Log.v("Hours to show", String.valueOf(hour));
// Log.v("Minutes to show", String.valueOf(minutes));
intent.putExtra("reminderTitle", reminder.getName());
// Log.v("Reminder Name", reminder.getName());
intent.putExtra("notificationType", 1);
intent.putExtra("reminderId", String.valueOf(reminder.getId()));
intent.putExtra("reminderSubtitle", reminder.getSubTitle());
intent.setAction(Long.toString(System.currentTimeMillis()));
Log.v("set Alarm", String.valueOf(intent));
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
return alarmIntent;
}
public void deleteReminderIntent(Reminder reminder) throws ParseException {
Log.v("deleteReminderIntent", String.valueOf(reminder));
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent =getPendingIntentFromReminder(reminder);
alarmMgr.cancel(pendingIntent);
pendingIntent.cancel();
//alarmMgr.cancel(temp);
// alarmMgr.cancel(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}
In getPendingIntentFromReminder() you set the ACTION in the Intent to the current time. When you call the method to get a PendingIntent to cancel your alarm, the current time is different, so the ACTION will not match the PendingIntent you have used to set the alarm.
In order to cancel the alarm, you need to use an Intent that will match the Intent that you used to set the alarm. The following parameters in the Intent must match:
ACTION
CATEGORY
DATA
COMPONENT
Any "extras" in the Intent are ignored, so they do not need to match.
For more details see https://stackoverflow.com/a/29590084/769265 and
Is it possible to create multiple PendingIntents with the same requestCode and different extras?
I am trying this code to popup the alarm message. Its working when launching or opening the app, but it doesn't say any popup message while outside of the app.
I am so confused, i don't know what i am doing wrong.
String alarmtime = cur.getString(cur.getColumnIndex(DBDATA.LG_ALARMTIME));
//Reminder
String[] timesplit = alarmtime.split(":");
int hour = Integer.parseInt(timesplit[0]);
int minute = Integer.parseInt(timesplit[1]);
System.out.println(hour);
System.out.println(minute);
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ShortTimeEntryReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar alarm = new GregorianCalendar();
alarm.setTimeInMillis(System.currentTimeMillis());
alarm.set(Calendar.HOUR_OF_DAY, hour);
alarm.set(Calendar.MINUTE, minute);
alarm.set(Calendar.SECOND, 0);
System.out.println(System.currentTimeMillis());
System.out.println(alarm.getTimeInMillis());
if (System.currentTimeMillis() > alarm.getTimeInMillis()){
alarm.setTimeInMillis(alarm.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
alarmMgr.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(),pendingIntent);
}
else
{
alarmMgr.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(),pendingIntent);
}
I need to pop up the alarm message outside of the app(i.e) exactly like the alarm does.
Thanks for your help guys,
You probably need a BroadcastReceiver.
As you can read in this question : BroadcastReceiver not receiving an alarm's broadcast
You have to build the intent like this :
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, "CHECK_ALARM_CODE", alarmIntent, 0);
And receive the alarm like this :
public class AlarmReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
Log.d("OK", "AlarmReceiver.onReceive");
}
}
Don't forget to register your broadcast in your manifest file.
i tried to write a simple service for an android device. it looks like
public void onReceive(Context context, Intent intent) {
// do something
// new alarm
setNextAlarm(context);
}
public static void setNextAlarm(Context context) {
Intent myIntent = new Intent(context, MainReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// trigger
Calendar cal = Calendar.getInstance();
// here is possible that trigger time will be different by each call
long triggerTime = computeNextTriggerTime();
long triggerAtTime = cal.getTimeInMillis() + triggerTime;
alarmManager.setInexactRepeating(AlarmManager.RTC, triggerAtTime, triggerTime, pendingIntent);
}
Well, I noticed that it works, but sometimes it crashes after days or hours of using and I'm quite sure, that it is not because of the code, that do the logic and that I didn't post here.
The trigger time is between 10 and 30 minutes.
Every help will be appreciated :)