notification is not working in android - android

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

Related

Changing a variable from Notification Method

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

Notification Missing From Intent on Android 7.0

I have an alarm set up to deliver an intent with a notification to a broadcast receiver which then fires the notification. Pre 7.0, the notification is present in the intent when received, on 7.0 it's missing.
Here's the code which generates the notification.
public static void scheduleNotification(Context context, String message, long delay,
MainDisplay.NotificationType type) {
Notification.Builder builder = new Notification.Builder(context).setSmallIcon(
R.drawable.ic_stat_o)
.setContentTitle(
"Title")
.setContentText(
message)
.setStyle(
new Notification
.BigTextStyle()
.bigText(
message));
final Intent notificationIntent = generateNotificationIntent(context);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, builder.build());
notificationIntent.putExtra(TYPE_KEY, type);
final PendingIntent pendingIntent = generatePendingIntent(context, notificationIntent);
final long futureInMillis = SystemClock.elapsedRealtime() + delay;
final AlarmManager alarmManager = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Here's the pending intent code.
public static PendingIntent generatePendingIntent(Context context, Intent notificationIntent) {
return PendingIntent.getBroadcast(context, 0, notificationIntent,
PendingIntent
.FLAG_UPDATE_CURRENT);
}
Here's the code that receives it.
public void onReceive(final Context context, Intent intent) {
final NotificationManager
notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
final Notification notification = intent.getParcelableExtra(NOTIFICATION);
final int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
Any ideas? Thanks!
I noticed that a serialized enum that I sent along was missing as well, I know there were changes in 7.0 with regards to intent transactions that were too large, but I'm not sure how that would apply here as no exceptions were thrown. I opted to simply send along the required info to construct the notification in onReceive.

How to repeat the alarm till particular date

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

Notifications not showing Android

I am trying to bring up a notification after set period of time using:
scheduleNotification(getNotification("Notification content..") differ);
and the following functions -
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
builder.setSmallIcon(R.drawable.icon);
return builder.build();
}
private void scheduleNotification(Notification notification, long delay) {
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
After logging the delay value, I get 57580 which is roughly 57 seconds, but even after this period of time, I do not get any notification on status-bar.
Please help.
You need a BroadcastReceiver to get notifications from the system.
public static class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
getNotification(String content);
}
}
And remember to declare the class in your AndroidManifest:
<receiver android:name=".AlarmReceiver" />

Alarm manager not triggering

I'm new to this, so I'm a bit lost.
I have built a notification and passed it to the alarm manager as a pendingIntent, however instead of waiting the interval to trigger the alarm and showing the notification, the notification is instantly shown.
What have I done wrong, that isn't allowing the alarm to be set properly?
public class NotificationController{
Context context;
public void createNotification(Context context){
this.context = context;
Notification notification = getNotification();
//creates notification
Intent intent = new Intent(context, NotificationReceiver.class);
intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
intent.putExtra(NotificationReceiver.NOTIFICATION, notification);
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//schedules notification to be fired.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000 , pIntent);
}
private Notification getNotification(){
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(context)
.setContentTitle("Reminder")
.setContentText("Car service due in 2 weeks")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent);
return builder.build();
}
}
my receiver
public class NotificationReceiver extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notification);
}
}
I have also registered with <receiver android:name=".NotificationReceiver" > in the AndroidManifest.
In this line
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 10000 , pIntent);
You specify that the alarm has to fire at 10 seconds after the device has been booted (which is in the past, so the alarm fires immediately). If you would want it 10 seconds after you set the alarm, you use the number of milliseconds since the device has been booted PLUS 10 seconds:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 10000 , pIntent);
Try this:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis()+10000 , pIntent);
For me old methods are killing after few hours . Please see my code that i am using for different OS versions. May be helpful.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(alarmTime, pendingIntent);
alarmManager.setAlarmClock(alarmClockInfo, pendingIntent);
}
else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
}
else {
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
}
Thanks
Arshad
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
and
Intent notifyIntent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, NotificationKeys.NOTIFICATION_ID, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.SECOND, 5);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmStartTime.getTimeInMillis(), pendingIntent);
If you want to set is at a excat time, you should use setExact. Unfortunalety there is no setExactRepating so you have to create this yourself. Schedule a new alarm after one executes or something like that
for more refer https://stackoverflow.com/a/30812993/8370216

Categories

Resources