My app use an AlarmManager that start a BroadcastReceiver.
The BroadcastReceiver generate a reminder notification to the user.
This is the MainActivity that start the Alarm
public class MainActivity extends ActionBarActivity {
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);
// Checking whether current hour is over 14
if (curHr >= 14)
{
// Since current hour is over 14, setting the date to the next day
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.HOUR_OF_DAY, 14);
// Schedule alarm manager
Intent myIntent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
And this is the BroadcastReceiver that generate the notification
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag");
//Acquire the lock
wl.acquire();
Log.v("ADebugTag", "It work!");
int mId = 0;
//Show the notification here.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_action_edit)
.setContentTitle("Diario Scolastico")
.setContentText("You have homeworks for tomorrow!")
.setAutoCancel(true)
.setDefaults(-1);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
//Release the lock
wl.release();
}
}
Manifest permissions:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
As you can see the alarm must start at 14 PM, but i receive the notification every time that i start the app.
There is something wrong in my code?
I use the Scheduling Repeating Alarms for setting the alarm every day at same hour, but don't work properly
The issue is you are setting the time to current day. So if you are opening your app after 14:00, your alarm manager will immediately fire.
You need to check whether the time is over 14:00 for the current day, if yes you need to change the date to the next day:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);
// Checking whether current hour is over 14
if (curHr >= 14)
{
// Since current hour is over 14, setting the date to the next day
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.HOUR_OF_DAY, 14);
// Schedule alarm manager
Related
I've looked a various of an example of how to make a scheduling task using Alarm Manager; source 1, source 2. But I'm a little bit confuse how to set the alarm at the specific time, because from what I understand its only have an interval of 15 minutes or a day from recurring. What I'm looking is I want it to recur at a specific time and repeating.
I found this, but it's recurred 2 minutes late from the time that I've specified. Below is what my code looks.
Activity
AlarmManager alarmManager = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(c, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(c, 0, intent, 0);
// Set the alarm to start at 3.46 PM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 46);
// setRepeating() lets you specify a precise custom interval--in this case,
// 1 day
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent);
BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
Toast.makeText(context, "triggered", Toast.LENGTH_LONG).show();
}
Already set <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> and <receiver android:name=".BroadCastRecevier"/> in AndroidManifest.
You can set exact time :
manager.setExact(AlarmManager.RTC, startTime.getTimeInMillis(), operation);
And if that time has passed today, set for tomorrow
if (Calendar.getInstance().after(startTime)) {
startTime.add(Calendar.DATE, 1);
}
Following permissions must be added first :
<uses-permission android:name="android.permission.WRITE_SETTINGS" ></uses-permission>
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" ></uses-permission>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" ></uses-permission>
Then:
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Set the alarm to start at 21:32 PM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 32);
// setRepeating() lets you specify a precise custom interval--in this case,
// 1 day
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
In this case, AlarmReceiver is the Broadcast Receiver and it already has a context, so you can directly set the ringer mode to silent from the Broadcast Receiver without starting an activity.
#Override
public void onReceive(Context context, Intent intent) {
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
In my app, I want to do a certain task everyday and after that task is completed I want to trigger multiple notifications at different times (these times will be calculated while doing that task).
After googling I found out that using AlarmManager is my best option:
This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.
My problems are:
1. Notification is shown only for that first time, not after that.
2. AlarmManager is triggered every time I restart that app and that past notification is shown.
PS.: I am a newbie in android and any help is appreciated
Here is what I tried:
Funtion in my activity from I am setting up this Alarm:
private void handleNotification() {
Intent alarmIntent = new Intent(this, AlarmReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
This is my AlarmReciever class:
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<String> times = new ArrayList();
GPSTracker gpsTracker = new GPSTracker(context);
//calculate the times arraylist
DateFormat format;
Date date = null;
for (String s : times) {
if (hour12) {
format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
try {
date = format.parse(s);
} catch (ParseException e) {
}
} else {
format = new SimpleDateFormat("hh:mm", Locale.ENGLISH);
try {
date = format.parse(s);
} catch (ParseException e) {
}
}
Intent alarmIntent = new Intent(context, NotificationReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Log.d(Constants.LOG_TAG, calendar.getTime().toString());
if (Build.VERSION.SDK_INT < 19) {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
}
}
And this is my NotificationReciever class:
public class NotificationReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Constants.D) Log.d(Constants.LOG_TAG, "NOTIFICATION RECIEVER");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.sc_logo_final)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setContentText(context.getResources().getString(R.string.app_name));
Intent resultIntent = new Intent(context, NavigationDrawerActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NavigationDrawerActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
In my AndroidManifest.xml,
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".AlarmReciever">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name=".NotificationReciever">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
First of all, this code is most likely setting up an alarm to happen at midnight of the current day, which is almost certainly in the past compared to the current time, which means you'll receive the alarm very quickly:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
According to the javadoc for setRepeating():
If the stated trigger time is in the past, the alarm will be triggered
immediately, with an alarm count depending on how far in the past the
trigger time is relative to the repeat interval.
Your Alarm does not repeat because you're using the flag INTERVAL_DAY, which only works with setInexactRepeating().
If you want to run something at midnight of the next day, you will need to add one day to the calendar. You might also consider setting the seconds field to 0 as well.
If you're registering the alarm every time the app starts, you'll keep getting that early alarm every time. Also according to the javadoc:
If there is already an alarm scheduled for the same IntentSender, it
will first be canceled.
The alarm is not repeating because you're passing an interval that is only valid for setInexactRepeating().
I try to set an alarm depending user chocies while setting alarm i want to send that alarm's unique notification id to reciever.java. I want to get data by this id on reciever.java.
I have a form with this form users are adding their pills and I'm saving every pill in different xml files for example pill1.xml pill2.xml. That saved pills have alarm and notification when alarm time came for example pill2.xml i will show pill2 datas in notirifacation bar.
that code on bottom is how i create alarm.
Long alertTime = new GregorianCalendar().getTimeInMillis()+10*1000;
Intent alertIntent = new Intent(ilac_hatirlatma.this, hatirlatma_detay.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(ilac_hatirlatma.this, NOTIF_ID, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
reciever.java
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "İlaç Hatırlatma", "8 saatte bir içmeniz gereken 'Arvelez' adlı ilacınız bulunmaktadır.", "İlacınzı Almayı Unutmayınız!");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, ilac_hatirlatma.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.app_icon).setContentTitle(msg).setTicker(msgAlert).setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
Here i prepare the alarm manager, every day at same hour
alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
// Set the alarm to start at some time.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);
// Checking whether current hour is over 15
if (curHr >= 15)
{
// Since current hour is over 15, setting the date to the next day
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 30);
// every day
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
And here i have the BroadcastReceiver that generate the notification
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//Partial_wake_lock only need CPU active
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag");
//Acquire the lock
wl.acquire();
int mId = 0;
//Show the notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_action_edit)
.setContentTitle("YOUR APP NAME")
.setContentText("TAKE THE PILLS!")
.setAutoCancel(true)
.setDefaults(-1);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
//Release the lock
wl.release();
}
}
The permissions of the manifest
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
And Receiver declaration in the manifest
<receiver android:name=".MyBroadcastReceiver" />
For setting your Alarm manager read documentation
If you need to pass data between AlarmManager and BroadcastReceiver use .putExtra() like how this post explain
Hope this helps!
I have a CalendarView that the user can touch and save school events.
I would check every day at 15:00 PM check if in the database there are some events saved like homeworks and generate a notification of that.
What i need for do this?
AlarmManager
BroadcastReceiver (??)
Service
The AlarmManager manage the when start a Service, and in the Service i make the query that if it returns something i make the notification.
I don't know if the BroadCastReceiver is needed.
It's all or i need something else?
Can someone tell me how do that?
Activity that manage the when case:
public class MainActivity extends ActionBarActivity {
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 40);
Intent myIntent = new Intent(MainActivity.this, MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
My BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag");
//Acquire the lock
wl.acquire();
Log.v("ADebugTag", "It work!");
int mId = 0;
//Show the notification here.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_action_edit)
.setContentTitle("Diario Scolastico")
.setContentText("Hai dei compiti da svolgere per domani!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
//Release the lock
wl.release();
}
}
Manifest Permissions
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<receiver android:name=".MyBroadcastReceiver" />
Now i get notification but not in the established time and i don't know why!
The most appropriate use for your particular case would be the AlarmManager and a corresponding BroadcastReceiver as they were specifically created for situations like this. You don't need a service just for showing a notification.
Some problems that might lead to your issue that I saw by glancing at your code were:
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
should be:
//It's better to use the setInexactRepeating, but this is your call
int MILLIS_IN_A_DAY = 1000 * 60 * 60 * 24; //You can use an actual calculator so you don't have to compute it every time at runtime; also, lower it to something like 10000 ms to actually check if it is working
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), MILLIS_IN_A_DAY, pendingIntent);
Then you'd want to acquire the wakelock in your BroadcastReceiver onReceive method by doing so:
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 'YOUR TAG');
//Acquire the lock
wl.acquire();
//You can show the notification here.
//Release the lock
wl.release();
}
Also, don't forget to register the BroadcastReceiver in your AndroidManifest.xml
Hello I have my Alarm Manager to show a Notification. The problem is that once the alarm is triggered and the notification is shown, when the code of MainActivity(super.onCreate) is executed, it always triggers the notification.
Here is my MainActivity which executes the Alarm.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initAlarm();
}
private void initAlarm(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 8);
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.DAY_OF_MONTH, 21);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
//Creo un intent que ejecutara el BroadcastReceiver
Intent myIntent = new Intent(MainActivity.this, AlarmBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
Here is the AlarmBroadcastReceiver which is supposed to be called only when the time of the AlarmManager expires.
public class AlarmBroadcastReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, AlarmService.class);
context.startService(startIntent);
}
}
The service launched by the BroadcastReceiver:
public class AlarmService extends Service{
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
generarNotificacion();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void generarNotificacion(){
Intent resultIntent = new Intent(this.getApplicationContext(), MainActivity.class);
android.support.v4.app.NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.texto_notificacion));
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
And finally I have added this code to the manifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".AlarmService"
android:enabled="true" />
<receiver android:name=".AlarmBroadcastReceiver"/>
...
</application>
It is obvious. You are calling initAalarm() in onCreate. To understand execute following test case with your code:
Lets say current date and time is 20 Sep 2015 1:00pm and
Alarm is set to future date say 15 min after current time i.e. 20 Sep 2015 1:15pm
Now to test it you can either wait for time to arrive or change system date-time. After doing this you will see notification is fired on same time.Now don't change anything in initAlarm() , close activity and again start it , you will see notification again. The reason behind this is if alarm is set to some past date with respect system time then it is immediately fired.
See documentation of Alarm Manager's set method
You Posted this in month of September which is 9th Month
where as
You are trying this in past date which is
calendar.set(Calendar.MONTH, 8);
change it with future date.