My application contains a SQLite database to store a person's information.
I store birthday as a long value. I want to show notification if someone has birthday today in the saved list. I am retrieving the long birthday value, setting it to a calendar and comparing it with current calendar month and day. But the problem is if someone has birthday matching with current day the the notification arises but shows that it is the birthday of the last person in the list whatever be the birthday of the last person. Please help. Thanks in advance.
Here are the codes
calendar_now = Calendar.getInstance();
calendar_now.setTimeInMillis(System.currentTimeMillis());
int month_now = calendar_now.get(Calendar.MONTH);
int day_now = calendar_now.get(Calendar.DAY_OF_MONTH);
//Set a specific time to the calendar
calendar_now.set(Calendar.HOUR_OF_DAY, 6);
calendar_now.set(Calendar.MINUTE, 0);
calendar_now.set(Calendar.SECOND, 0);
dbHelper = new DbHelper(this);
personArrayList = dbHelper.getPerson();
birth_calendar = Calendar.getInstance();
for (Person p : personArrayList) {
name = p.getName(); //Get the person's name
mobile = p.getMobile();
byte_image = p.getByteImage();
position = personArrayList.indexOf(p);
DoB = p.getDateOfBirth();
birth_calendar.setTimeInMillis(DoB);
int birth_month = birth_calendar.get(Calendar.MONTH);
int birthday = birth_calendar.get(Calendar.DAY_OF_MONTH);
if ((birth_month == month_now) && (birthday == day_now)) {
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar_now.getTimeInMillis(), pendingIntent);
} else {
Toast.makeText(this, "No birthday today", Toast.LENGTH_SHORT).show();
}
birth_calendar.clear();
}
NotificationReceiver.java
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
//Open PersonDetailsActivity on notification click
Intent resultIntent = new Intent(context, PersonDetailsActivity.class);
//Pass the values through intent to PersonDetailsActivity
resultIntent.putExtra("name", MainActivity.name);
resultIntent.putExtra("mobile", MainActivity.mobile);
resultIntent.putExtra("DoB", MainActivity.DoB);
resultIntent.putExtra("image", MainActivity.byte_image);
resultIntent.putExtra("position", MainActivity.position);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Birthday reminder")
.setContentText("It is " +MainActivity.name+ "'s birthday today, " +
"wish him/her \"Happy birthday!!\"")
.setVibrate(new long[]{250, 250, 250, 250})
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true);
notificationManager.notify(100, mBuilder.build());
}
}
if ((birth_month == month_now) && (birthday == day_now)) {
Intent intent = new Intent(this, NotificationReceiver.class);
Intent intent = new Intent(context , DocumentSubFolder.class);
intent.putExtra("name" , name);
intent.putExtra("mobile" , mobile);
intent.putExtra("Dob" , DoB);
intent.putExtra("image" , byte_image);
intent.putExtra("position" , position);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar_now.getTimeInMillis(), pendingIntent);
}
NotificationReceiver.java
resultIntent.putExtra("name", intent.getStringExtra("name));
resultIntent.putExtra("mobile", intent.getStringExtra("mobile));
resultIntent.putExtra("DoB", intent.getStringExtra("Dob));
resultIntent.putExtra("image", intent.getStringExtra("image));
resultIntent.putExtra("position", intent.getStringExtra("position));
Replace your code with this.
Related
I have RecyclerView that contains notes, when I add new note I want to add reminder for that particular note but when the notification appears and I click on it I want to navigate to that activity and open that note. Notification works properly but what I want is, when I clicked on the notification open that note I set reminder on it.
AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, ChecklistChildActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "alarmChannel")
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.drawable.alarm)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(123, builder.build());
}
}
setAlarm method:
private void setAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
I have an o'clock interface in RecyclerAdapter that I implemented in MainActivity:
#Override
public void onNoteClicked(int position, View itemView) {
Intent intent = new Intent(this, NoteDetail.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("id", noteAdapter.itemList.get(position).getId());
intent.putExtra("title", noteAdapter.itemList.get(position).getTitle());
intent.putExtra("content", noteAdapter.itemList.get(position).getContent());
intent.putExtra("date", noteAdapter.itemList.get(position).getDate());
intent.putExtra("backgroundColor", noteAdapter.itemList.get(position).getBackgroundColor());
startActivity(intent);
}
When I clicked on the notification this method somehow should be called. When I add the note I don't know which position it goes in order to pass that position with the intent, though if I know the position, the position may change when I add or remove another note.
Great, I have an idea, I assume your activity gets id and other data from intent. so we have to put data to alarm intent and read them from AlarmReceiver and put them again into the Activity Intent.
private void setAlarm() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("id", "myId");
intent.putExtra("title", "my title");
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}
and get that from the Receiver class:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, ChecklistChildActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("id", intent.getStringExtra("id"));
i.putExtra("title", intent.getStringExtra("title"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "alarmChannel")
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setSmallIcon(R.drawable.alarm)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
managerCompat.notify(123, builder.build());
}
that is a simple way but I suggest using the database in your activity and getting the note details in the onCreate method with id, so you need just add id in your intents and add get query in NoteDetail.java class.
in my program i set notifications with a string and its clock to get a notification with that string at its clock.(I mean user wants to get a notification with a string at demanding time, and user gave me a lot of strings and their clocks.) And if the user want to cancel that notification i don't know how to do it.
I tried alarmManager.cancel(pendingIntent) but I want to cancel the only one notification not all of them. Also, it doesn't cancel any notification too.
here is the code in the main
public void gecikmeliGoster(String plan, int yil, int ay, int gun, String saat){
NotificationCompat.Builder builder;
NotificationManager bildirimYoneticisi = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent ıntent = new Intent(HatirlaticiKur.this, AlarmReciever.class);
PendingIntent gidilecekIntent = PendingIntent.getActivity(this, 1, ıntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String kanalId = "kanalId";
String kanalAd = "kanalAd";
String kanalTanım = "kanalTanım";
int kanalOnceligi = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel kanal = bildirimYoneticisi.getNotificationChannel(kanalId);
if (kanal == null) {
kanal = new NotificationChannel(kanalId, kanalAd, kanalOnceligi);
kanal.setDescription(kanalTanım);
bildirimYoneticisi.createNotificationChannel(kanal);
}
builder = new NotificationCompat.Builder(this, kanalId);
builder.setContentTitle("Hatırlatıcı")
.setContentText(plan)
.setSmallIcon(R.drawable.hatirlatici)
.setAutoCancel(true)
.setContentIntent(gidilecekIntent);
} else {
builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Hatırlatıcı")
.setContentText(plan)
.setSmallIcon(R.drawable.hatirlatici)
.setContentIntent(gidilecekIntent)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH);
}
Intent broadcastIntent = new Intent(HatirlaticiKur.this, AlarmReciever.class);
broadcastIntent.putExtra("nesne", builder.build());
PendingIntent gidilecekBroadcast = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//long gecikme = SystemClock.elapsedRealtime() + 5000; //bu 5 saniyede bir bildirim gelmesi için falan
String[] noktasiz = saat.split(":");
int akrep = Integer.parseInt(noktasiz[0]);
int yelkovan = Integer.parseInt(noktasiz[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.YEAR, yil);
calendar.set(Calendar.MONTH, ay);
calendar.set(Calendar.DATE, gun);
calendar.set(Calendar.HOUR_OF_DAY, akrep);
calendar.set(Calendar.MINUTE, yelkovan);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 0, gidilecekBroadcast);
}
and here is the code in AlarmReceiver
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager bildirimYoneticisi = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification bildirim = intent.getParcelableExtra("nesne");
bildirimYoneticisi.notify(1,bildirim);
}
}
I want to cancel demanding notifications, i will appreciate your help
use used 0 id for setting alarm
PendingIntent gidilecekBroadcast = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
You need uniqueid for all notification set using alarmmanager
then based on uniqueid you can cancel alarm
PendingIntent gidilecekBroadcast =
PendingIntent.getBroadcast(getApplicationContext(), uniqueid , broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
alarmManager.cancel(gidilecekBroadcast);
I've set an Alarm in my app to trigger a notification every X minutes. The first time works, but then is not repeating.
The API I'm working on is API 18 (Android 4.3).
MainActivity.class
public void setAlarm(Consumo con){
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
int id = (int) con.getId();
calendar.add(Calendar.MINUTE, con.getTime());
Intent notification = new Intent(MainActivity.this, AlarmReceiver.class);
notification.putExtra("cadena", con.getName()+
" "+con.getQuantity()+" "+ con.getType()+" "+con.getPills()+" comprimidos");
notification.putExtra("id", id);
PendingIntent pendingNotif = PendingIntent.getBroadcast(MainActivity.this,
id, notification, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), calendar.getTimeInMillis(), pendingNotif);
}
AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver {
private static String CHANNEL_ID = "medicinas.android.unex.cum.es.app";
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
Bundle b = intent.getExtras();
int id = b.getInt("id");
notificationIntent.putExtra("id", id);
TaskStackBuilder tsb = TaskStackBuilder.create(context);
tsb.addParentStack(NotificationActivity.class);
tsb.addNextIntent(notificationIntent);
Intent tomada = new Intent(context, NotificationActivity.class);
tomada.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
tomada.putExtra("id", id);
PendingIntent pTomada = PendingIntent.getActivity(context, 155, tomada, PendingIntent.FLAG_ONE_SHOT);
PendingIntent pendingIntent = tsb.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
Notification notification = builder.setContentTitle("Control de Medicinas")
.setContentText(intent.getExtras().getString("cadena"))
.setTicker("¡Hora de tomar la medicina")
.setSmallIcon(R.mipmap.ic_launcher)
.addAction(android.R.drawable.btn_default, "Medicina tomada", pTomada)
.setContentIntent(pendingIntent).build();
notification.defaults = Notification.DEFAULT_SOUND;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"MedicinaNotificacion",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(id, notification);
}
}
RECEIVER AFTER MODIFICATIONS
public class AlarmReceiver extends BroadcastReceiver {
private static String CHANNEL_ID = "medicinas.android.unex.cum.es.app";
private Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
Bundle b = intent.getExtras();
mContext = context;
int id = b.getInt("id");
notificationIntent.putExtra("id", id);
Consumo con = new Consumo(id, b.getString("name"), b.getInt("quantity"),
b.getString("type"), b.getInt("pills"), true, b.getInt("time"));
TaskStackBuilder tsb = TaskStackBuilder.create(context);
tsb.addParentStack(NotificationActivity.class);
tsb.addNextIntent(notificationIntent);
Intent tomada = new Intent(context, NotificationActivity.class);
tomada.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
tomada.putExtra("id", id);
String cadena = b.getString("name")+
" "+b.getInt("quantity")+" "+
b.getString("type")+" "+b.getInt("pills")+" comprimidos";
PendingIntent pTomada = PendingIntent.getActivity(context, 155, tomada, PendingIntent.FLAG_ONE_SHOT);
PendingIntent pendingIntent = tsb.getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
Notification notification = builder.setContentTitle("Control de Medicinas")
.setContentText(cadena)
.setTicker("¡Hora de tomar la medicina")
.setSmallIcon(R.mipmap.ic_launcher)
.addAction(android.R.drawable.btn_default, "Medicina tomada", pTomada)
.setContentIntent(pendingIntent).build();
notification.defaults = Notification.DEFAULT_SOUND;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(CHANNEL_ID);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"MedicinaNotificacion",
NotificationManager.IMPORTANCE_DEFAULT
);
notificationManager.createNotificationChannel(channel);
}
setAlarm(con);
notificationManager.notify(id, notification);
}
public void setAlarm(Consumo con){
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
int id = (int) con.getId();
calendar.add(Calendar.MINUTE, con.getTime());
Intent notification = new Intent(mContext , AlarmReceiver.class);
notification.putExtra("cadena", con.getName()+
" "+con.getQuantity()+" "+ con.getType()+" "+con.getPills()+" comprimidos");
notification.putExtra("id", id);
notification.putExtra("name", con.getName());
notification.putExtra("quantity", con.getQuantity());
notification.putExtra("type", con.getType());
notification.putExtra("pills", con.getPills());
notification.putExtra("time", con.getTime());
Log.i("DEBUG RECEIVER: ", ""+con.getTime());
PendingIntent pendingNotif = PendingIntent.getBroadcast(mContext,
id, notification, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, con.getTime()*60*1000, pendingNotif);
}
}
If you need more of the code tell me, I'll add it quickly.
Thanks in advance.
try:
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), calendar.getTimeInMillis(), pendingNotif);
and then in onReceive(), call setAlarm() method to set the next alarm
I think issue is in this line :
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), calendar.getTimeInMillis(), pendingNotif);
Let's assume you want alarm to go off after every 2 minutes, it should be :
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 2*60*1000, pendingNotif);
In the above example, replace 2 with whatever minute you want the alarm to go off.
I've created a notification and it's just doesnt show up.
My code in the main activity: `boolean alarm = (PendingIntent.getBroadcast(this, 0, new Intent("ALARM"), PendingIntent.FLAG_NO_CREATE) == null);
if(alarm){
Intent itAlarm = new Intent("ALARM");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,itAlarm,0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 3);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
AlarmManager alarme = (AlarmManager) getSystemService(ALARM_SERVICE);
alarme.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),60000, pendingIntent);
}
my code in the Broadcast Reciver:
public class BroadcastManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
String yourDate = "04/05/2016";
String yourHour = "13:07:00";
Date d = new Date();
DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
DateFormat hour = new SimpleDateFormat("HH:mm:ss");
if (date.equals(yourDate) && hour.equals(yourHour)){
Intent it = new Intent(context, MainActivity.class);
createNotification(context, it, "new mensage", "body!", "this is a mensage");
}
}catch (Exception e){
Log.i("date","error == "+e.getMessage());
}
}
public void createNotification(Context context, Intent intent, CharSequence ticker, CharSequence title, CharSequence descricao){
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent p = PendingIntent.getActivity(context, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setTicker(ticker);
builder.setContentTitle(title);
builder.setContentText(descricao);
builder.setSmallIcon(R.drawable.web_hi_res_512);
builder.setContentIntent(p);
Notification n = builder.build();
//create the notification
n.vibrate = new long[]{150, 300, 150, 400};
n.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(R.drawable.web_hi_res_512, n);
//create a vibration
try{
Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone toque = RingtoneManager.getRingtone(context, som);
toque.play();
}
catch(Exception e){}
}
}
Above code will start alarm service on every 3 seconds and repeat on every 1 minute. If you want to generate notification on specific time then, You have to add,
calendar.add(Calendar.HOUR, 13);
calendar.add(Calendar.MINUTES, 07);
calendar.add(Calendar.SECONDS, 00);
and remove this line,
calendar.add(Calendar.SECOND, 3);
I hope it may work for you.
the notifications of my app open without a logical sense than the code that I wrote. I should receive a notification every day at the same time but if I open the app I get the same notification. This is the code in MainActivity:
public void setRepeatingAlarm() {
Intent intent = new Intent(this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),24*60*60*1000,pendingIntent);
}
And this is MyAlarmService:
public class MyAlarmService extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Locali Torino";
CharSequence message = "Visita le serate!";
Intent action = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
action, 0);
Notification notif = new Notification(R.drawable.disco,
"Visita le serate!", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(0, notif);
}
}
Why I get notifications when I open the app or at least not only at the set time?
EDIT
MyAlarmService:
public class MyAlarmService extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Locali Torino";
CharSequence message = "Visita le serate!";
Intent action = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
action, 0);
Notification notif = new Notification(R.drawable.disco,
"Visita le serate!", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(0, notif);
SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mPref.edit();
long time = System.currentTimeMillis();
mEditor.putLong("UPDATE_TIME", time);
mEditor.commit();
}And this is MainActivity:
public void setRepeatingAlarm() {
Intent intent = new Intent(this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
long startAt;
long period;
SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
long dif = System.currentTimeMillis() - mPref.getLong("UPDATE_TIME", 0);
if (dif >= UPDATE_PERIOD) {
startAt = 0;
period = UPDATE_PERIOD;
} else {
startAt = dif;
period = dif;
}
am.setRepeating(AlarmManager.RTC_WAKEUP, startAt, period,pendingIntent);
}
The service runs when you register it, so what you need to do is pass a boolean value with the intent when registering the service to prevent it from running when the application runs, but to run periodically thereafter.
In your activity add:
intent.putExtra("run", false);
Then in MyAlarmService:
private boolean run = true;
// ...
action.getBooleanExtra("run", run);
if(run) {
// notifications code
} else {
run = true;
}
Actually it works exactly as code is written. The cause of that behavior is your startAt parameter in setRepeating method.
am.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
24*60*60*1000,
pendingIntent);
calendar.getTimeInMillis() time in milliseconds that the alarm should first go off, using the appropriate clock (depending on the alarm type).
For example :
//send first alarm after 1 second and repeat it every 24 hours
am.setRepeating(AlarmManager.RTC_WAKEUP,
1000,
24*60*60*1000,
pendingIntent);
//send first alarm after 10 second and repeat it every 24 hours
am.setRepeating(AlarmManager.RTC_WAKEUP,
10000,
24*60*60*1000,
pendingIntent);
UPDATE :
You need to save your last update time :
public class MyAlarmService extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
//send alarm here
//...
SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mPref.edit();
mEditor.putLong("UPDATE_TIME", time);
mEditor.commit();
}
}
Then you can make your setRepeatingAlarm method like this :
public void setRepeatingAlarm() {
Intent intent = new Intent(this, MyAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
long startAt;
long period;
SharedPreferences mPref = context.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
long dif = System.currentTimeMillis() - mPref.getLong("UPDATE_TIME", 0);
if (dif >= UPDATE_PERIOD) {
startAt = 0;
period = UPDATE_PERIOD;
} else {
startAt = dif;
period = dif;
}
am.setRepeating(
AlarmManager.RTC_WAKEUP,
startAt,
period,
pendingIntent);
}