I'm trying to set repeating alarm between two dates. for that I set repeating alarm first using starting date and then just setting a single alarm on last date, for that i'm using other broadcast receiver on the cancel date, so that when the last day came, it got cancelled. but my alarm is not getting inside the cancelling broadcast receiver even on the last date, in short it is not getting cancelled at all.
here is my main code where i'm setting both alarms:
Log.v("setting range alarm","key range id = " + keyIds[j] + "time = " + RangeTimes[j]);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// RangeTimes[] got the starting date
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, RangeTimes[j], AlarmManager.INTERVAL_DAY,
PendingIntent.getBroadcast(this, keyIds[j], alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Log.v("setting range alarm","key range id = " + keyIds[j] + "Cancel time = " + CancelRangeTimes[j]);
// setting the last date in alarm , cancelRangeTimes[] got the last date
Intent cancellationIntent = new Intent(this, CancelAlarmBroadcastReceiver.class);
cancellationIntent.putExtra("key", pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, CancelRangeTimes[j],
PendingIntent.getBroadcast(this, keyIds[j], cancellationIntent, PendingIntent.FLAG_UPDATE_CURRENT)); // for exact repeating THIS
now this is my normal broadcast reciver for generating notifications
public void onReceive(Context context, Intent intent) {
String[] myStrings = intent.getStringArrayExtra("strings");
String pleaseText = intent.getStringExtra("text");
int count = intent.getIntExtra("count", 0);
createNotification(context, pleaseText, "trying other option", "Alert");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert) {
final int _id = (int) System.currentTimeMillis(); // unique request code
PendingIntent notificationIntent = PendingIntent.getActivity(context,0, new Intent(context,MainActivity.class),0);
NotificationCompat.Builder mbuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.cast_ic_notification_play)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
mbuilder.setContentIntent(notificationIntent);
mbuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mbuilder.setAutoCancel(true); // noti dismisble when user swipe it away
NotificationManager notificationManager = (NotificationManager)
context.getSystemService((Context.NOTIFICATION_SERVICE));
notificationManager.notify(1, mbuilder.build()); // changes from 1 to _id
}
and this is my cancelling broadcast receiver
public class CancelAlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent pendingIntent = intent.getParcelableExtra("key");
Log.v("setting the cancel","inside broadCast reciver " + pendingIntent );
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
}
}
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 am trying to push notification at the certain time. To perform this I am triggering the alarm which eventually call the broadcast receiver that show the notifications.
private void setAlarmToCallNotificationService(Context context, int request_code, String notificationText, String notificationTitle) {
Log.i("Inside notification,","Yes");
Intent intent = new Intent(context, notificationService.class);
intent.putExtra("Notification_title",notificationTitle);
intent.putExtra("Notification_text",notificationText);
//hit the notification At the 8.00 in the morning
Calendar notificationCalendar=Calendar.getInstance();
notificationCalendar.set(Calendar.HOUR_OF_DAY,16);
notificationCalendar.set(Calendar.MINUTE,29);
notificationCalendar.set(Calendar.SECOND,0);
Long time=notificationCalendar.getTimeInMillis();
System.out.println("NOTIFICATION Time is "+notificationCalendar.get(Calendar.HOUR_OF_DAY)+" "+notificationCalendar.get(Calendar.MINUTE));
Log.i("Target",time.toString());
//final int _id = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, request_code, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
I checked that the alarm is firing up.
public class notificationService extends BroadcastReceiver {
public static String TAG="notificationService";
#Override
public void onReceive(Context context, Intent intent) {
String notificatioTitle=intent.getExtras().getString("Notification_title");
String notificationMsg=intent.getExtras().getString("Notification_text");
Log.i(TAG,"Notification title "+notificatioTitle);
Log.i(TAG,"Notification msg "+notificationMsg);
NotificationCompat.Builder notification=new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notificatioTitle)
.setContentText(notificationMsg);
NotificationManager mNotificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0,notification.build());
}
}
Manifest file:
<receiver android:name=".notificationService" />
Did your receiver receive intent at expected time?
I mean... did the code below print anything at all?
Log.i(TAG,"Notification title "+notificatioTitle);
Log.i(TAG,"Notification msg "+notificationMsg);
If no, check if you use Settings.System.AUTO_TIME in you device DateTimeSettings,
You may need to use NTP time to set alarm.
long currentTime = System.currentTimeMillis() - ntpTimeOffset;
long timeToWaitForTrigger = calendar.getTimeInMillis() - currentTime;
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeToWaitForTrigger, pendingIntent);
The user sets the date he wants to be notified in (receives a push notification that the movie is out) about a movie, for example. To do this I take the movie's id to set up the BroadcastReceiver and I also take the name of the movie; to use it as a text message for the broadcast receiver, for example, "movieName is out", with the method SetAlarm(). Note: my app doesn't have to do anything with movies, I'm speaking in general.
public void setAlarm(View view){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
Intent alertIntent = new Intent(this, AlertReceiver.class);
alertIntent.putExtra("id", mainId);
alertIntent.putExtra("name", name);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
PendingIntent.getBroadcast(this, 1, alertIntent,
PendingIntent.FLAG_UPDATE_CURRENT));
}
As you can see I'm passing with an intent the id and the name of the movie to the AlertReceiver class
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int id = intent.getIntExtra("id", 0);
String name = intent.getStringExtra("name");
createNotification(context, "Movie", name + " Now Out" , name, id);
}
public void createNotification(Context context, String msg, String msgText, String msgAlert, int id){
//intent for MainActivity
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setContentTitle(msg)
.setContentText(msgText)
.setTicker(msgAlert)
.setSmallIcon(R.mipmap.ic_launcher);
//the intent when the notification is clicked on
mBuilder.setContentIntent(notificIntent); //goes to MainActivity
//how the user will be notified
mBuilder.setDefaults(NotificationCompat.DEFAULT_LIGHTS);
//stop notification when it's clicked on
mBuilder.setAutoCancel(true);
//now to notify the user with NotificationManager
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, mBuilder.build());
}
}
It works perfectly, the user gets notified only when the app is still running in the background, but after closing it or reboot, the broadcast receiver still gets called; the user gets notified, that means no problem with the id, but the name is null, I get as a text message "null is out". So how can I save the name?
Use SharedPreference to save the user name.
SharedPreference,disk,database...
recommend SharedPreference
I want to show the user notifications everyday in the same time. For now I only have this code:
My TimeAlarm.class that shows the notifications:
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence from = "Nithin";
CharSequence message = "Crazy About Android...";
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(), 0);
Notification notif = new Notification(R.drawable.ic_launcher,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, from, message, contentIntent);
notif.sound = Uri.parse("android.resource://"
+ context.getPackageName() + "/" + R.raw.test);
// r.play();
nm.notify(1, notif);
}
}
And initialization of the notifications to show every 5 seconds:
public void setRepeatingAlarm() {
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(5 * 1000), pendingIntent);
}
Now my question is how should I modify this code to set the notification to repeat every day in certain time. Example every day in 14:36 o'clock?
The easy-but-inexact way is to change System.currentTimeMillis() to a calculation of 14:36 tomorrow, probably using a Calendar object:
Calendar cal=Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 14);
cal.set(Calendar.MINUTE, 36);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (cal.getTimeInMillis() < System.currentTimeMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
I say "easy-but-inexact" because Android 4.4 has changed the behavior of setRepeating() to be inexact, once your android:targetSdkVersion is 19 or higher. If you need exact alarms, you will need to use setExact() and do your own "repeating" (by calling setExact() again when the alarm goes off). You would still use the same Calendar sort of calculation, just on every setExact() call.
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