android alarm not getting received by the application - android

I am facing consistency issue while setting alarms inside my application wherein the alarm gets delivered sometimes but other times the pending intent does not gets delivered to my application.
The way I am trying to test is by changing my local device time and check if I am getting the alarm or not.
I can see the alarm getting triggered from the alarm manager because this log comes up
V AlarmManager: Triggering alarm #0: 0 when =1508253750804 package=com.x.xoperation =*walarm*:com.x.x/x.AlarmReceiver
Does android control the delivery of an alarm based upon whether the application is in the background or not? Any insights around this area would really help.
Code For AlarmManager
public static void SetNotification(int id, long delayMs, String title, String message, String ticker, int sound, int vibrate,
int lights, String largeIconResource, String smallIconResource, int bgColor, String bundle, String dataString)
{
Context currentActivity = UnityPlayer.currentActivity;
AlarmManager am = (AlarmManager)currentActivity.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(currentActivity, AlarmReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("ticker", ticker);
intent.putExtra("title", title);
String arr[] = new String[]{id+"", delayMs+"", title, message, ticker, sound+""};
String fStr = "";
for (String temp:arr
) {
fStr += temp+":";
}
Log.d(Constants.TAG, "Input message = "+fStr);
intent.putExtra("message", message);
intent.putExtra("id", id);
intent.putExtra("color", bgColor);
intent.putExtra("sound", sound == 1);
intent.putExtra("vibrate", vibrate == 1);
intent.putExtra("lights", lights == 1);
intent.putExtra("l_icon", largeIconResource);
intent.putExtra("s_icon", smallIconResource);
intent.putExtra("bundle", bundle);
intent.putExtra("dataString", dataString);
PendingIntent pendingIntent = PendingIntent.getBroadcast(currentActivity,
id, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
am.cancel(pendingIntent);
long finalTime = System.currentTimeMillis() + delayMs;
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,finalTime, pendingIntent);
Log.d(Constants.TAG, "event fired finalTime = "+ finalTime);
}
Is this because of the doze and app standby which android has introduced ? or is because of some issue on our side.

Related

Push notifications not opening correct screens

I have an app where I get GCM push notifications in a GcmListenerService(as given in the gcm android sample). Whenever I get the notification, I get some JSON with data related to showing the notification.
Now suppose I get a notification that "someone bookmarked me", for that I get the pk(identifier) of that user and when I click on the notification, it uses the pk received in the push notification to display that user's profile.
The issue : If I get 2 notifications of above mentioned kind, then no matter which notification I click, I always go the profile of the person whose notification I received most recently.
Does getting a notification on top of other, overrides the values of the previous notifications so that only the most recent one is valid? Does that mean I can show only one push notification from an app? I can post the code if that is needed.
Relevant code:
#Override
public void onMessageReceived(String from, Bundle data) {
tinyDB = new TinyDB(this);
if (tinyDB.getBoolean(AppConstants.LOGIN_STATE, false)) {
try {
Log.i("NOTIF", data.toString());
String screen = data.getString("screen");
String dataJson = data.getString("data");
String displayJson = data.getString("display");
String notification_id = data.getString("notif_id");
String priority = data.getString("priority");
String style = data.getString("style");
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
NotificationVal notificationVal = gson.fromJson(displayJson, NotificationVal.class);
String title = notificationVal.getTitle();
String text = notificationVal.getText();
String largeText = notificationVal.getLargeText();
String smallIcon = notificationVal.getSmallIcon();
String largeIcon = notificationVal.getLargeIcon();
Bitmap smallImage = null;
Bitmap largeImage = null;
if (!TextUtils.isEmpty(smallIcon)) {
smallImage = getBitmapFromURL(smallIcon);
}
if ("big_picture".equalsIgnoreCase(style) && (largeImage != null)) {
NotificationCompat.BigPictureStyle notificationStyle = new NotificationCompat.BigPictureStyle();
notificationStyle.setBigContentTitle(title);
notificationStyle.setSummaryText(text);
notificationStyle.bigPicture(largeImage);
Intent intent = NotificationIntentBuilder.get(this, dataJson, screen, smallIcon, largeIcon, notification_id);
TaskStackBuilder stackBuilder = NotificationStackBuilder.get(this, screen, dataJson);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.white_square);
mBuilder.setAutoCancel(true);
mBuilder.setColor(Color.parseColor("#fac80a"));
mBuilder.setLargeIcon(largeImage);
mBuilder.setContentTitle(title);
mBuilder.setContentText(text);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
mBuilder.setStyle(notificationStyle);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notification_id != null) {
mNotificationManager.cancel(Integer.parseInt(notification_id));
mNotificationManager.notify(Integer.parseInt(notification_id), mBuilder.build());
}
} else {
Log.i("GCM", "Dummy Notification");
}
} catch (Exception e) {
Log.i("NOTIF", "An exception occurred");
}
}
}
Other internal codes:
public class NotificationStackBuilder {
public static TaskStackBuilder get(Context context, String screen, String data) {
if ("IMAGE".equalsIgnoreCase(screen)) {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ImageActivity.class);
return stackBuilder;
} else {
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NewHomeActivity.class);
return stackBuilder;
}
}
}
public class NotificationIntentBuilder {
public static Intent get(Context context, String data, String screen, String smallIcon, String largeIcon, String notificationId) {
if ("IMAGE".equalsIgnoreCase(screen)) {
String pk = "";
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(data);
if (jsonObject.has("pk")) {
pk = jsonObject.getString("pk");
}
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(context, ImageActivity.class);
intent.putExtra("ID", pk);
intent.putExtra("notificationId", notificationId);
return intent;
} else if ("GALLERY".equalsIgnoreCase(screen)) {
String pk = "";
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(data);
if (jsonObject.has("pk")) {
pk = jsonObject.getString("pk");
}
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(context, GalleryActivity.class);
intent.putExtra("ID", pk);
intent.putExtra("notificationId", notificationId);
return intent;
} else {
return new Intent(context, NewHomeActivity.class);
}
}
}
Edit This issue is not happening with two notifications of different type(opening different activities), it is only happening with notifications opening the same screen.
Edit 1 Here is the value received in the push notification:
Bundle[{google.sent_time=1469254984538, priority=0, screen=IMAGE, data={"pk":650}, style=big_picture, google.message_id=0:1469254984541527%e07f0e28f9fd7ecd, notif_id=4267, display={"large_icon":"https:\/\/d2r0rrogy5uf19.cloudfront.net\/photos\/971c03f8-6a5d-30a3-9e49-0ab416cb8fa0.jpg","small_icon":"","text":"Random hi5'd your photo to 'Diwali'","title":"random","large_text":""}, collapse_key=do_not_collapse}]
This one has notificationId as 4267, now suppose I get another notification for same screen, with notificationId say, 4268, then when I log the notificationId received in the Image screen, I get 4268 on opening both the notifications.
Edit 2 I guess the issue is related to PendingIntent.FLAG_UPDATE_CURRENT. Here is what is written in the documentation:
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.
This is what was happening. The contents of intent extras were getting over-written by the latest notification's intent extras. So, I tried using FLAG_ONE_SHOT, but with that I am able to open the old intent but noting opens when I click the latest intent.
I want both notifications to be on the push notification list and that both of them should the respective screens with different values of intent extras.
You need to have unique request code for each notification or else it will be replaced with new one.
An excerpt from PendingIntent documentation :
The last intent in the array represents the key for the PendingIntent.
In other words, it is the significant element for matching (as done
with the single intent given to getActivity(Context, int, Intent,
int), its content will be the subject of replacement by send(Context,
int, Intent) and FLAG_UPDATE_CURRENT, etc. This is because it is the
most specific of the supplied intents, and the UI the user actually
sees when the intents are started.
So replace the below line:
PendingIntent resultPendingIntent = stackBuilder. getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
Assuming notification_id is unique integer, just replace it like below:
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(Integer.parseInt(notification_id)
, PendingIntent.FLAG_UPDATE_CURRENT);

Is it possible to change the content text or message of a repeating notification in android ? If yes, how?

I have a repeating notification in a broadcast receiver. I will like to replace the content text dynamically. The notification will show the user a different message the next time the notification is shown. I want to know if its possible. If yes, how ?
below is the class of my broadcast receiver
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
long pattern[] = {500, 500};
private Uri notifsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
private NotificationCompat.BigTextStyle contentStyle;
#Override
public void onReceive(Context context, Intent intent) {
String msg = "Drivers who sit higher feel as if they're driving slower. " +
"Thus, SUV drivers, who are already piloting the vehicles most prone to " +
"roll, drive faster because they feel like they're creeping along. " +
"So lower your seat to get the sensation of more speed.";
contentStyle = new android.support.v4.app.NotificationCompat.BigTextStyle();
contentStyle.bigText(msg);
contentStyle.setBigContentTitle("Lower Your Seat");
contentStyle.setSummaryText("AutoKit");
NotificationCompat.Builder builder;
builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("AutoKit")
.setContentText("Tip of the Day")
.setTicker("Daily Tip")
.setStyle(contentStyle)
.setSound(notifsound)
.setAutoCancel(true)
.setVibrate(pattern);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, builder.build());
}
}
here is the method is called in my mainactivity and ties the broadcast receiver to an alarm manager
public void setRepeatingAlarm(){ //user receives notifications every 24 hours at 7am
am = (AlarmManager)this.getSystemService(this.ALARM_SERVICE);
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 07);
calendar.set(Calendar.MINUTE, 00);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pi);
}
Modify a Notification
To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously.
The following snippet demonstrates a notification that is updated to reflect the number of events that have occurred. It stacks the notification, showing a summary:
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...
Taken from developer site. please refer, http://developer.android.com/training/notify-user/managing.html
here the changes I made in the broadcast receiver class.
public class TimeAlarm extends BroadcastReceiver {
NotificationManager nm;
long pattern[] = {500, 500};
private Uri notifsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
private NotificationCompat.BigTextStyle contentStyle;
private List contentTexts, contentTitles;
#Override
public void onReceive(Context context, Intent intent) {
contentTexts = new ArrayList<String>();
contentTitles = new ArrayList<String>();
prepareContentTitles();
prepareContentTexts();
SharedPreferences prefs = context.getSharedPreferences("notification_count", context.MODE_PRIVATE);
int count = prefs.getInt("notification_count", 0);
contentStyle = new android.support.v4.app.NotificationCompat.BigTextStyle();
contentStyle.bigText((CharSequence) contentTexts.get(count));
contentStyle.setBigContentTitle((CharSequence) contentTitles.get(count));
contentStyle.setSummaryText("AutoKit");
NotificationCompat.Builder builder;
builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("AutoKit")
.setContentText("Tip of the Day")
.setTicker("Daily Tip")
.setStyle(contentStyle)
.setSound(notifsound)
.setAutoCancel(true)
.setVibrate(pattern);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, builder.build());
if (count == contentTexts.size() - 1) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notification_count", 0);
editor.commit();
}
else {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notification_count", count + 1);
editor.commit();
}
}
public void prepareContentTexts() {
contentTexts.add("Drivers who sit higher feel as if they're driving slower. " +
"Thus, SUV drivers, who are already piloting the vehicles most prone to " +
"roll, drive faster because they feel like they're creeping along. " +
"So lower your seat to get the sensation of more speed.");
contentTexts.add("Manufacturers recommend replacing your blades every three months. " +
"Keep a spare set in your trunk. A product such as Rain Clear can also help " +
"minimize the work of your wipers; spray it onto the glass every few weeks. " +
"In some light rains, it makes the wipers almost unnecessary");
contentTexts.add("At the BMW Performance Driving School, instructor Jim Clark says " +
"these four words over and over: \"Slow in, fast out.\" When taking a corner," +
" you need to scrub as much of that speed as you can while the car is braking" +
" in a straight line, then you can accelerate out of the curve. The converse " +
"is \"Fast in, maybe no out.\"");
}
public void prepareContentTitles() {
contentTitles.add("Lower Your Seat");
contentTitles.add("Rainproof Your Windshield");
contentTitles.add("Maneuver Tight Corners ");
}
}
The notification displays different content texts every time it is fired

Android: Cannot save and read all values in the Bundle

I have following method which is saving three values into intent which is appended to created alarm.
public static Boolean setUniqueAlarm(Long alarmId, String occurenceTime, Context context) {
Boolean saveResult = null;
try {
DateTime dt = TimeHelper.getDateTimeObject(occurenceTime);
Logger.d("Year: " + dt.getYear() + ", month: " + dt.getYear() + ", day: " + dt.getDayOfMonth() + ", hour: " + dt.getHourOfDay() + ", minute: " + dt.getMinuteOfHour());
Logger.d("Occurrence time to save: "+occurenceTime);
AlarmManager alarmManager = (AlarmManager) context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, AlarmBroadcastReceiver.class);
// Pass the intent type and other additional values into bundle
Bundle bundle = new Bundle();
bundle.putString(Constants.Global.ALARM_TYPE, Constants.Global.ALARM_TYPE_UNIQUE);
bundle.putString(Constants.Global.ALARM_OCCURRENCE_TIME, "123456");
bundle.putLong(Constants.Global.ALARM_UNIQUE_ID, alarmId);
alarmIntent.putExtras(bundle);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, dt.getMillis(), pendingAlarmIntent);
saveResult = true;
} catch (Exception e) {
Logger.e(e.getMessage());
saveResult = false;
}
return saveResult;
}
In receiver i have following code:
#Override
public void onReceive(Context context, Intent intent) {
try {
Logger.d("ALARM RECEIVED!!!");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
// Device battery life will be significantly affected by the use of this API.
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
// Acquire the lock
wl.acquire();
//Release the lock
wl.release();
// Get the intent type (or stored variables)
Bundle extras = intent.getExtras();
mAlarmType = extras.getString(Constants.Global.ALARM_TYPE);
mAlarmId = extras.getLong(Constants.Global.ALARM_UNIQUE_ID, 0);
mOccurenceTime = extras.getString(Constants.Global.ALARM_OCCURRENCE_TIME, "nothing");
triggerActionBasedOnTheAlarmType(mAlarmType, mAlarmId, mOccurenceTime, context);
} catch (Exception e) {
TrackingEventLogHelper.logException(e, Constants.Global.EXCEPTION,
Constants.ExceptionMessage.EXC_CANNOT_PROCESS_RECEIVED_ALARM, true);
}
}
Problem is that variable mOccurenceTime is always null, rsp. "nothing".
I tried to get values from intent and from Bundle but still without the success. Is not bundle count of items limited?
How can i get value mOccurenceTime in the right way?
Many thanks for any advice.
This is the right way to do it - specify a flag !
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Instead of the:
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uniqueRequestCode, intent, 0);
Because the 0 for the flags is what will cause you a headache
This is probably such a popular problem because Google's sample code neglected to include Extra's in an Alarm.
Solved here:
Android cannot pass intent extras though AlarmManager

Android Notifications, loads only the latest intent when there are more than one notifications

I have an app which has 4 layers/stack, something like,
HomePage >> DetailPage >> MapPage >> ChatPage
I managed to create notifications whenever I received different chat messages (note that each conversation has its unique id, say ChatId)
for different conversation, I will create a notification using ChatId as the requestCode in the pendingIntent
The problem I am facing is that, whenever I received more than 1 notification, say ChatId1 comes first, followed by ChatId2. Then when I clicked on the ChatId1's notification, it will launch the latest intent which is ChatId2, making the conversations loaded in ChatPage are conversations of ChatId2.
Question is, how can I make it so that, when I clicked on ChatId1's notification, it loads messages of ChatId1, and when click on ChatId2, it loads messages of ChatId2.
Below is the snippet of the code where I create my notifications
public void createLocalNotification(String meetingIdLong, String countryCode, String phoneNumber, String contactName, String chatMessage) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, ChatLog.class);
long L = Long.parseLong(meetingIdLong);
int a = Integer.parseInt(meetingIdLong);
intent.putExtra("meetingId", L);
Intent intent1 = new Intent(this, HomePage.class);
Intent intent2= new Intent(this, MeetingDetailPage.class);
intent2.putExtra("meetingId", L);
Intent intent3 = new Intent(this, MapPage.class);
intent3.putExtra("meetingId", L);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ChatLog.class);
stackBuilder.addNextIntent(intent1);
stackBuilder.addNextIntent(intent2);
stackBuilder.addNextIntent(intent3);
stackBuilder.addNextIntent(intent);
PendingIntent pIntent = stackBuilder.getPendingIntent(a, PendingIntent.FLAG_UPDATE_CURRENT);
String notificationSound = _defPrefs.getString("pref_notification_tone", "");
NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
.setContentTitle(contactName)
.setContentText(chatMessage)
.setSmallIcon(R.drawable.noti_smallicon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.noti_smallicon))
.setSound(Uri.parse(notificationSound))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setNumber(++numberMsg)
.setAutoCancel(true)
.setContentIntent(pIntent);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[6];
events [numberMsg - 1] = new String(chatMessage);
// Sets a title for the Inbox style big view
inboxStyle.setBigContentTitle(contactName);
inboxStyle.setSummaryText(numberMsg + " new message(s)");
for (int i=0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
noti.setStyle(inboxStyle);
String isChatOpen, isChatOpenId;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
isChatOpen = preferences.getString("isChatOpen","");
isChatOpenId = preferences.getString("isChatOpenId","0");
if (!isChatOpenId.equals(meetingIdLong))
{
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(a, noti.build());
}
}
Use
intent.setAction(Long.toString(System.currentTimeMillis()));
for each your Intent you want to be unique. Its just a dummy action, but it helps.

Android notifications error

Im coding an android app for about 4 months now and im currently getting an error on system notifications.
The problem is that im adding proximity alerts from varius interest points, when it aproaches a specific point, it sends a system notification. But now, when im near of more than one point, it sends the correct amount of notifications but they are all the same, woth same title and text, and im passing different information on the intent.
My code is:
MainActivity:
private void addProximityAlert(double latitude, double longitude, String type, int id, String object) {
Intent intent = new Intent(PROX_ALERT_INTENT);
intent.putExtra("type", type);
intent.putExtra("id", id);
intent.putExtra("object", object);
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
locationManager.addProximityAlert(
latitude, // the latitude of the central point of the alert region
longitude, // the longitude of the central point of the alert region
POINT_RADIUS, // the radius of the central point of the alert region, in meters
PROX_ALERT_EXPIRATION, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
registerReceiver(new ProximityReceiver(), filter);
}
Proximity Receiver:
public class ProximityReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
int id = intent.getIntExtra("id", 0);
String type = intent.getStringExtra("type");
String name = intent.getStringExtra("object");
Log.d("NOTIFICATION", "NOME: " + name);
Log.d("NOTIFICATION", "ID: " + id);
Log.d("NOTIFICATION", "TYPE:" + type);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}else {
Log.d(getClass().getSimpleName(), "exiting");
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, InterestPoint_Description.class);
notificationIntent.putExtra("id", id);
notificationIntent.putExtra("type", type);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "LisbonRoutes", "You are near " + name + ", touch here to check it out!", pendingIntent);
notificationManager.notify(Config.NOTIFICATION_ID, notification);
Config.NOTIFICATION_ID++;
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.icon;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}
I hope i've explained it well :S
Thanks in advance
Your pending intents are overwriting one another because extras do not make them unique.
See http://developer.android.com/reference/android/app/PendingIntent.html
it is important to know when two Intents are considered to be the same for purposes of retrieving a PendingIntent. A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen.
Best way to fix this is to set the request code, probably to id
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, id, intent, 0);

Categories

Resources