I am using AlarmManager to set alarm and i want to save its id in my sqlite db, whenever i set the alarm, it fires immediately, i googled the solution, but did'nt find according to my requirement, may be i am getting wrong date and time from my date time picker widgets,
I am using date and time pickers as:
final DatePicker datePicker = (DatePicker)dialog.findViewById(R.id.datePicker);
final TimePicker timePicker = (TimePicker)dialog.findViewById(R.id.timePicker);
Then a dialoge appears, i change date and time, and then then get it as :
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
timeSetForAlert = calendar.getTimeInMillis()/1000;
And then i pass this to service handler like,
Intent myIntent = new Intent(thisContext, MyReceiver.class);
myIntent.putExtra("timeSetForAlert", timeSetForAlert);
pendingIntent = PendingIntent.getBroadcast(thisContext, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, timeSetForAlert, pendingIntent);
I am skipping broadcast receiver here which takes intent and start alarm service, while alarm service is as:
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
long timeSetForAlert = intent.getLongExtra("timeSetForAlert", 0);
mManager = (NotificationManager) thisContext.getSystemService(thisContext.NOTIFICATION_SERVICE);
Intent intent1 = new Intent(thisContext,MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", timeSetForAlert);
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( thisContext,0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(thisContext, "Notification..", "This is a test message!", pendingNotificationIntent);
mManager.notify(startId, notification);
Toast.makeText(thisContext, startId+"", Toast.LENGTH_SHORT).show();
}
Please suggest:
1) - Why alarm fires immediately
2) - where should i save it in my db
try using this
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
timeSetForAlert = calendar.getTimeInMillis();//try without dividing with 1000
ya it can be solved like this.
accept both the answers..
code:
Instead of this
pendingIntent = PendingIntent.getBroadcast(thisContext, 0, myIntent,0);
PendingIntent pi = PendingIntent.getBroadcast(
getApplicationContext(), uniqueValue, intent, 0);
instead of "0" use unique value as second parameter to get multipleBroadcast.
Related
I am having trouble with my app, that on first launch i want to setup an alarmintent and I want the alarm manager to send me a notification every 24 hour at a specific time.
Every thing about it works, except when i launch the app for the first time (when data is cleared from the app), then there is send a notification right away, which it should not do until the next time the clock hits 09:00.
Here is the function that setup the alarm (only called the very first time the app is running)
public void setAlarm(){
Toast.makeText(this, "setAlarm()", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent alarmIntent = new Intent(this, AlertReceiver.class);
if(PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_ONE_SHOT) != null){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
And here is the notification function of the broadcast receiver
public void createNotification(Context context, String msg, String msgText, String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(R.drawable.ic_stat_dmq_notification_icon);
mBuilder.setTicker(msgAlert); //Ticker!
mBuilder.setWhen(System.currentTimeMillis());
mBuilder.setContentTitle(msg); //Title:
mBuilder.setContentText(msgText); //Text
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(uniqueId, mBuilder.build());
I have been looking at this for days, and I cannot seem to figurer it out nor can i find a solution. If anyone can help I would be a happy man!
Is it past 9am in your area. That might be the source of your error. An Alarm set to a time in the past in android fires off right away. Try:
calendar.set(Calendar.YEAR, 2017);
Insane just for testing
Okay i manage to figure it out after all.
Only thing needed to be added was after alle the calendar.set was
if(calendar.getTimeInMillis() < System.currentTimeMillis()){
Toast.makeText(this,"1 day have been added", Toast.LENGTH_SHORT).show();
calendar.add(Calendar.DATE, 1);
}
It basically just check to see if the time was in the past, and if it was, then it adds another day, so the alarm will go off the next day.
I'm trying to make an an app that sends multiple scheduled alarms, shown through a notification according to a specific time (not time interval, but time) every day.
I already implemented the AlarmReceiver.class that fires the notifications at each intent, but the problem is that I don't get any notification. I tried to show a Log inside the onReceiver() method, but the message hasn't been shown, so the alarm hasn't been reached.
This is the setAlarm() function, that sets the hour and the time to the Calendar I instantiated:
public void setAlarm()
{
SharedPreferences pref = this.getSharedPreferences("NOTIFICATION_CODE", Context.MODE_PRIVATE);
String mName = NameFld.getText().toString();
String mFormat = FormatSpn.getSelectedItem().toString();
Date date = new Date();
Calendar calendar = Calendar.getInstance();
Calendar current = Calendar.getInstance();
current.setTime(date);
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, picker_hour);
calendar.set(Calendar.MINUTE, picker_minute);
calendar.set(Calendar.SECOND, 0);
if(current.before(calendar))
{
calendar.add(Calendar.DATE, 1);
}
medName = mName;
medFormat = mFormat;
int _reqCode = pref.getInt("reqCode", -1);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, _reqCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);
aManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);
editor = pref.edit();
editor.putInt("reqCode", ++_reqCode);
editor.commit();
}
To set the time, I implemented a TimePickerDialog and I stored hour and minute values to picker_hour and picker_minute.
Since I have to send multiple alarms, I use SharedPreferences to store the reqCode used then to identify the PendingIntent every time one is sent.
This is the AlarmReceiver.class that fire a notification for each intent received. Every notification is identified through the same reqCode of the PendingIntent:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String[] data = AddMedicine.getData();
SharedPreferences pref = context.getSharedPreferences("NOTIFICATION_CODE", context.MODE_PRIVATE);
int reqCode = pref.getInt("reqCode", -1);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
builder.setTicker("It's pill time!");
builder.setContentTitle(data[0]);
builder.setContentText(data[1]);
builder.setSmallIcon(R.drawable.ic_launcher);
Notification notification = builder.build();
NotificationManager nManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
nManager.notify(reqCode, notification);
Log.i("NOTIFICATION", "FIRED!");
}}
P.s. The alarm is set every time the user creates it, in order to schedule them through the reqCode.
So, anyone knows how to send multiple alarms according by time? Thank you in advance!
Hi I am working on a application where I am getting reminder details from user as reminder Date and reminder name and storing those in database. Now I want to know how can I start reminder through background service? Or Is there any other way if yes please tell me. What should I do? Please help me. Suggest something or tutorial will be great idea.
Thanks in advance!
For this you will require two things
Alarm manager: To set the time for notification or alarm (daily, weekly basis)
Service: To launch your notification when alarm manager goes off
Do this in your activity class where you want to set the reminder
Intent myIntent = new Intent(this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
//get time from database and initialise the variables.
int minute;
int hour;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.AM_PM, Calendar.AM); //set accordingly
calendar.add(Calendar.DAY_OF_YEAR, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
This will trigger Alarm each day at your set time.
Now, you should create a Service as NotifyService and put the following code in its onCreate():
#Override
public void onCreate() {
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Notify Alarm strart", System.currentTimeMillis());
Intent myIntent = new Intent(this , MyActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "Notify label", "Notify text", contentIntent);
mNM.notify(NOTIFICATION, notification);
I want to set my notification in android on particular date and time, I am trying it by using date in java, but my notification is fired before time. so what can I go to get it fired on specified time. Thanks in advance!
Here is my code for notification:
Calendar cal = java.util.Calendar.getInstance();
cal.set(2012, 00, 30);
Date date = cal.getTime();
date.setHours(17);
date.setMinutes(30);
date.setSeconds(15);
long time = date.getTime();
Log.e("date is",""+date);
long when = time;
Notification notification = new Notification(notificationIcon,tickerText,date.getTime());
notification.when = date.getTime();
RemoteViews contentView = new RemoteViews("com.LayoutDemo",R.layout.userscreen);
notification.contentView= contentView;
Intent intent = this.getIntent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.contentIntent= contentIntent;
notification.flags= Notification.FLAG_AUTO_CANCEL;
int NOTIFICATION_ID =1;
nManager.notify(NOTIFICATION_ID,notification);
The field "when" of a notification is used to sort the notification in the status bar. It is not used to fire the notification at the specified time.
If you want to trigger an action at a specified time use AlarmManager: http://developer.android.com/reference/android/app/AlarmManager.html
use Android alarm services and in that set pending intent
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
hi ia m new to android..
i have developed a programme to set notification onspecific time
but the problem is it shows notification only of date before october 2011
if i enter any date of november its not showing any notification..
seems strange but really stuck here....
main activity..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calendar cal = Calendar.getInstance(); // for using this you need to
cal.set(Calendar.MONTH, 11);
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.DAY_OF_MONTH, 25);
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 28);
Intent alarmintent = new Intent(getApplicationContext(),
AlarmReceiver.class);
alarmintent.putExtra("title", "Title of our Notification");
alarmintent.putExtra("note", "Description of our Notification");
int HELLO_ID = 1;
PendingIntent sender = PendingIntent.getBroadcast(
getApplicationContext(), HELLO_ID, alarmintent,
PendingIntent.FLAG_UPDATE_CURRENT |
Intent.FILL_IN_DATA);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
and the alarm reciever activity...
public class AlarmReceiver extends BroadcastReceiver {
private static final String NotificationManager = null;
private static int NOTIFICATION_ID = 0;
#Override
public void onReceive(Context context, Intent intent) {
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager manger = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"Combi Note", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context,
NOTIFICATION_ID, new Intent(context,
AlarmReceiver.class), 0);
Bundle extras = intent.getExtras();
String title = extras.getString("title");
String note = extras.getString("note");
notification.setLatestEventInfo(context, note, title, contentIntent);
notification.flags = Notification.FLAG_INSISTENT;
notification.defaults |= Notification.DEFAULT_SOUND;
manger.notify(NOTIFICATION_ID, notification);
}
};
Calendar.set(Calendar.MONTH, month)
Expects a 0-based value. 11 is december.
You are setting an alarm for 5/5/2011, this date has passed so it is executed immediately.
When you receive a instance of Calendar, I think that the system automatically fills in the current date & time. So change only what you need to change (I.E if you want to send a notification in 5 days, change the day only in the calendar instance)
By the way, when clicking the notification it will, again, call your BroadcastReceiver and this time the intent won't have the extras you have put in it while in the activity. When clicking the notification, you should launch an activity - not a broadcast receiver.