So my program is supposed to set off a notification a few hours after the application has been stopped (minutes are being used just now for testing). It does this, however the problem with it is that if the code is executed a second time before a notification has been pushed, then no notification is pushed at all.
Override
public void onStop() {
super.onStop();
Calendar calendar = Calendar.getInstance();
int alarmTime = (calendar.get(Calendar.MINUTE)) + 3;
calendar.set(Calendar.MINUTE,alarmTime);
Intent intent3 = new Intent(getApplicationContext(),timeReceiver.class);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(),100,intent3,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent3);
}
#Override
protected void onRestart() {
super.onRestart();
//this.onCreate(null);
}
This is what my broadcast receiver class looks like...
public class timeReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, RepeatingActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(android.R.drawable.arrow_up_float);
builder.setContentTitle("Timer Notification");
builder.setContentText("blaaah blaaah blah");
builder.setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
}
My expectation is that the alarm would reset and trigger 3 minutes after the last execution of the onStop() method, but this does not happen. I don't really understand why it doesn't, if anyone could give me insight/ a possible solution I would be grateful. Also the SDK version is 24.
You can schedule your notification with NotificationCompat.Builder#setWhen(long), no need for alarm manager.
int notification1Id = 56748;
Calendar calendar = Calendar.getInstance();
int alarmTime = (calendar.get(Calendar.MINUTE)) + 2;
calendar.set(Calendar.MINUTE,alarmTime);
long timeMs = calendar.getTimeInMillis();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notifications
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelID);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(android.R.drawable.arrow_up_float);
builder.setContentTitle("It's been a while...");
builder.setContentText("Remember to keep track of your calories using the calorie counter");
builder.setAutoCancel(true);
builder.setWhen(timeMs);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification1Id, builder.build());
Related
I added a notification feature to my app, when the user clicks on the notification it sends him to a certain activity in my app, but I also want it to change an integer variable number, I tried defining the variable static and do:
ActivityName.Variable = ActivityName.Variable + 1 or ActivityName.Variable++;
And it actually worked! but only when I change the date on my phone manually, so when the user sees the notification after waiting 1 day (the notification is daily) and clicks on it...he get to the activity but with no increase in the variable.
here's the notification codes:
public void setNotificationOn() { //This method sets the notification...so after 24h it will be triggered
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 24);
Intent intent = new Intent(getApplicationContext(), NotificationReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
package com.example.wordspuzzlejsontest;
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
LevelActivity.stars++; //This is the variable which I'm trying to increase
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, LevelsListActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity
(context, 100, repeating_intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.star_big_off)
.setContentTitle("Collect your daily star")
.setContentText("Click to collect your daily star")
.setAutoCancel(true)
.setColor(Color.BLUE);
notificationManager.notify(100, builder.build());
}
}
I have written a code that is supposed to display notifications. I am choosing hour and minute from TimePicker component (notifications popping up every day at given time), then create an intent for Notification receiver. The database is updated with proper info and everything is being set with the AlarmManager. The request code ("code" variable) is unique for each notification. I am pasting code snippets below:
SettingActivity class:
findViewById(R.id.buttonNotification).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
int hour, minute, id;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
calendar.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
Intent intent = new Intent(getApplicationContext(),Notifcation_receiver.class);
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
if(extra!=null){
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),extra.getInt("Code"),intent,PendingIntent.FLAG_UPDATE_CURRENT);
intent.putExtra("Code",extra.getInt("Code"));
db.updateNotification(hour,minute,extra.getInt("ID"));
}
else{
int code= Notification.getID();
intent.putExtra("Code",code);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),code,intent,PendingIntent.FLAG_UPDATE_CURRENT);
db.insertNotification(hour,minute);
}
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
startActivity(new Intent(SettingActivity.this, NotificationActivity.class));
}
});
}
Notification receiver class:
public class Notifcation_receiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int code = intent.getIntExtra("Code",0);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context,MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,code,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.arrow_up_float)
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(false);
notificationManager.notify(code,builder.build());
}
}
I can't seem to find the problem, causing the lack of planned notifications. Thank You for any help.
The problem was, as Mehmed mentioned, no channel set for the NotificationService.
Logcat log:
"E/NotificationService: No Channel found for pkg=com.example.kuba.quizapp, channelId=null"
It worked on API 22, but for 25 and higher the notification must be build with extra channel info.
I'm trying to do a simple Alarm manager, and although I'm adding a delay of 5 second,
the alarm in my phone goes off immediately.
I'm aware that in my receiver the alarm says to go off now,
but I understood that you set the delay to when you want it to go off at the pending intent.
what am I doing wrong ?
here is my alarm intent:
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent (AlarmClockScreen.this, AlarmNotificationReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+5000,pendingIntent);
and here is my Receiver
public class AlarmNotificationReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(android.R.mipmap.sym_def_app_icon)
.setContentTitle("Alarm TITLE")
.setContentText("I will finish, What you started")
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
fixed it by adding
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
and then using time.getTimeInMillis()
i have an android with a date picker.
i would like to choose a date and save it with an action bar item.
at this moment, it should be set an notification with the selected date.
this is my first time with notifications.
can everybody tell me, how i realize this?
i use min. SDK 15
i try something like this, but with this the notification start directly:
intent = new Intent(this, Overview.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
long[] pattern = {200,200,200,200,200,200,200,200,200};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification n = new Notification.Builder(this)
.setContentTitle("My Titel")
.setContentText("This is the Body")
.setSmallIcon(R.drawable.ic_notification_appicon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setLights(Color.GREEN, 500, 500)
.setVibrate(pattern)
.setSound(alarmSound)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
if you want to set a notification it should notify at n date you need to use a broadcast receiver and because a broadcast receiver up only for a short time its a better practice to use also intent service here you have a example how to do it.
this is the broadcast receiver class.
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
}
and register it in the manifest.
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false" >
</receiver>
this is the intent service class.
public class MyNewIntentService extends IntentService {
private static final int NOTIFICATION_ID = 3;
public MyNewIntentService() {
super("MyNewIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("My Titel");
builder.setContentText("This is the Body");
builder.setSmallIcon(R.drawable.ic_notification_appicon);
builder.setAutoCancel(true);
builder.setLights(Color.GREEN, 500, 500);
Intent notifyIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notificationCompat = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}
}
and register it in the manifest.
<service
android:name=".MyNewIntentService"
android:exported="false" >
</service>
and then in your activity set the alarm manger to start the broadcast receiver at a specific date like this this example use the date picker to help you with that:
DatePicker datePicker= (DatePicker)timeDialogView.findViewById(R.id.yourid);
and:
Calendar now = Calendar.getInstance();
Calendar current = Calendar.getInstance();
now.set(now.get( datePicker.getYear()), now.get(datePicker.getMonth()), now.get(datePicker.getDayOfMonth()), the hour, and the minute);
if(now.compareTo(current)<=0){
Toast.makeText(MainActivity.this,"invalid time",Toast.LENGTH_LONG).show();
}
else{
Intent notifyIntent = new Intent(context, MyReceiver.class);
notifyIntent.putExtra("title",item.getText());
PendingIntent pendingIntent = PendingIntent.getBroadcast
(context, NOTIFICATION_REMINDER, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC,now.getTimeInMillis(), pendingIntent);
}
i hope this will help you!
I'm trying to send a notification to a user at a specific time using an Alarm Manager. Basically, nothing happens at all and to me the code looks fine. My code for the Alarm Manager is below:
/** Notify the user when they have a task */
public void notifyAtTime() {
Intent myIntent = new Intent(PlanActivity.this , Notification.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(PlanActivity.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 17);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);
}
The code for the notification, which is in the "Notification" class is below:
public class Notification extends Service {
#Override
public void onCreate() {
Toast.makeText(this, "Notification", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,PlanActivity.class);
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Football")
.setContentText("Don't forget that you have Football planned!")
.setContentIntent(pending);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The Toast which is set in the Notification class also doesn't come up. I don't know if it's something really silly that I'm missing but any help would be greatly appreciated! :)
This is your receiver class :
public class OnetimeAlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
// try here
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
In Second Activity to set Alerm :
private void setAlarm(){
Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + alarm_time , pendingIntent);
System.out.println("Time Total ----- "+(System.currentTimeMillis()+total_mili));
}
I would like to recommend this tutorial How to send notification
Try to put your notification code in the onStartCommand function instead of onCreate.
Writing the alarmmanager code in the onCreate method of the LAUNCHER activity of the app solved my problem