How to set reminders in android using background service? - android

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);

Related

Prevent notification when launching App

I have a AlarmManager in order to show notification. I don't want that I get a notification everytime I launch the app. I read a lot but nothing was satisfying. My method doNotification in MainActivity.java looks like this:
public void doNotification(){
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP ,calendar.getTimeInMillis(), 1000*60*60*24*30 , pending); //every month
}
This method is in the OnCreate of my MainActivity class.
I know, that this is the reason why I get a notification everytime I launch my app.
My goal was to fire a notification every month, starting from the Date where the app was launched the first time. E.g User launches app on 5. July then you will get a notification on every 5th of every month.
How can I achieve this?
Thank you.
EDIT: According to the comments I used SharedPreferences is that a right use of it. Here is the new code:
public void doNotification(){
boolean isFirstAlarm = getSharedPreferences("ALARMFIRSTTIME",MODE_PRIVATE).getBoolean("isFirstAlarm",false);
if(!isFirstAlarm) {
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24 * 30, pending); //every month
getSharedPreferences("ALARMFIRSTTIME", MODE_PRIVATE)
.edit()
.putBoolean("isFirstAlarm",true)
.apply();
}
}

AlarmManager gets send on initial setup

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.

date time pickers wrong values for alarm manager?

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.

How to start notification at custom timing?

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);

Set notification to specific time

I would like my notification to run at 12:00pm everyday. How do you replace the when value with a time?
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification(R.drawable.icon,"Its Time to Eat",when);
Context context = GrubNOWActivity.this;
CharSequence title = "Its Time to Eat";
CharSequence details = "Click Here to Search for Restaurants";
Intent intent = new Intent(context,Search.class);
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
notify.setLatestEventInfo(context, title, details, pending);
nm.notify(0,notify);
You can use an alarm manager
Intent myIntent = new Intent(ThisApp.this , myService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent); //set repeating every 24 hours
and put the notification inside myService class!
The when parameter is for sorting the notifications in the status bar. You should code your app such that it fires the notification at the desired time.

Categories

Resources