start NEW Activity from PendingIntent with unique extra - java

i trying do a "read more" after user click on notification.
What i need, start new Activity with unique extra content "id", "title" and "text".
My code:
void notificationSend(String id, String bar, String title, String text, String image, int delay) {
Bitmap bitmap = getBitmapFromURL(image, 130);
if(bitmap == null){
bitmap = getBitmapFromURL("https://pp.vk.me/c621316/v621316641/119d5/HB9s2z5mX-s.jpg", 130);
}
Intent notificationIntent = new Intent(this, SingleNewsActivity.class);
notificationIntent.putExtra("id", id);
notificationIntent.putExtra("title", title);
notificationIntent.putExtra("text", text);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_bitcoin_notification);
builder.setLargeIcon(bitmap);
builder.setTicker(bar);
builder.setContentTitle(title);
builder.setContentText(text);
builder.setWhen(System.currentTimeMillis());
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
try {
notificationManager.notify(new Integer(id), notification);
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And it do next thing, lets send 2 notifications, after i click on first, activity started but with extra data from second notification, why?

The issue is due to using : FLAG_UPDATE_CURRENT
if you see document for this flag:
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.
in your case, you are updating just extra and due to that, the value of extras get updated.
For solution of your issue, you should pass request code unique for all case:
Currant code:
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Actual:
PendingIntent.getActivity(this, unique_code, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

So The reason is that you are setting unique id to the notification, lets suppose id value is 1 when your 1st notification comes then the notification object is created with that id, when you second notification come then your id is again 1 so your notification is updated and when you click on it you get the second notification.
what you can do is set the different id for notifications. have a look at below code
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
write below code inside a function
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Random random = new Random();
int NOTIFICATION_ID = random.nextInt(9999 - 1000) + 1000;
Intent intent = new Intent(this, SingleNewsActivity.class);
Bundle bundle = new Bundle();
bundle.putExtra("id", id);
bundle.putExtra("title", title);
bundle.putExtra("text", text);
intent.putExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("TITLE")
.setStyle(new NotificationCompat.BigTextStyle().bigText("ASD"))
.setContentText("Summary").setAutoCancel(true);
mBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d("", "Notification sent suessfully.");
in the above code whenever you will receive notification you will get a unique code in NOTIFICATION_ID

Related

How Do I get Notification Intent Data

I want to show a notification at some event, that's working fine, I am also landing on an activity I want but problem is that, intent data is empty, please here, Here is the code
Intent resultIntent = new Intent(context, MovieDetailActivity.class);
resultIntent.putExtra(Constants.MOVIE_ID, cursor.getString(
cursor.getColumnIndexOrThrow(DatabaseHelper.ID)));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_download)
.setContentIntent(resultPendingIntent)
.setContentTitle(cursor.getString(
cursor.getColumnIndexOrThrow(DatabaseHelper.NAME)))
.setAutoCancel(true)
.setContentText(cursor.getString(
cursor.getColumnIndexOrThrow(DatabaseHelper.REALEASE_DATE)));
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build()
);
I am sending some data using intent, in this line.
resultIntent.putExtra(Constants.MOVIE_ID, cursor.getString(
cursor.getColumnIndexOrThrow(DatabaseHelper.ID)));
I am receiving data here but it Null.
Intent receivedIntent = getIntent();
mMovieId = receivedIntent.getIntExtra(Constants.MOVIE_ID, -1);
Please help, I have spent whole day on this.
You pass into intent String so you can't get Integer from intent, that's why you get null.
So change this line:
mMovieId = receivedIntent.getIntExtra(Constants.MOVIE_ID, -1);
to
mMovieId = receivedIntent.getStringExtra(Constants.MOVIE_ID);
// and simply parse string to integer
int id = Integer.parseInt(mMovieId);
You need change your PendingIntent for:
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0 , resultIntent, PendingIntent.FLAG_CANCEL_CURRENT);
I hope it solve your problem.

Create multi Notification With Different Intent

I will try to create multi local notification every time with different parameters this is my code to create the notification:
public void setNotficition(int Time,String ProdName,String ProdDesc,String ProdID){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
notificationIntent.putExtra("ProdName",ProdName);
notificationIntent.putExtra("ProdDesc",ProdDesc);
notificationIntent.putExtra("ProdID",ProdID);
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, Time);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),broadcast);
}
This is my Code for BroadcastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
String ProdName= intent.getStringExtra("ProdName");
String ProdDesc= intent.getStringExtra("ProdDesc");
String ProdID= intent.getStringExtra("ProdID");
int ID = Integer.parseInt(ProdID);
Intent notificationIntent = new Intent(context, NotificationActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle(ProdName)
.setContentText(ProdDesc)
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
}
Every time its take the last call
Notification id should be unique within your application.
If a notification with the same id has already been posted by your
application and has not yet been canceled, it will be replaced by the
updated information.
NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notiManager.notify(UNIQUE_ID, notification);
If you are using PendingIntent.getBroadcast() method, use different requestCode for different notification:
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
notificationIntent.putExtra("ProdName",ProdName);
notificationIntent.putExtra("ProdDesc",ProdDesc);
notificationIntent.putExtra("ProdID",ProdID);
PendingIntent broadcast = PendingIntent.getBroadcast(this, REQUEST_CODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Hope this will help!
You can create multiple notification by changing notification id, everytime.
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
The second parameter of the getBroadcast call is "notification id" (i.e. 100 in your case). Just use different different notification id in case of generating multiple Notifications.
Hope it will help u :-)
A notification is created and linked to a id, this id can be used to modify or update on existing notification, weather you are changing the intent or just the behavior of the stack.

Cancelled Notification being redelivered when other notification is touched. Android

I am having an issue where, no matter what notification the user touches, I am always receiving the same notification, even though it is cancelled.
The first notification a user touches is the only notification that will ever be delivered to my pending intent, until device reboot (then the first touched notification becomes the new Hotel California notification).
Here is how I am constructing the notifications:
final Bundle extras = new Bundle();
final int notificationId = Integer.parseInt(payload.getObjectId());
extras.putInt(NOTIFICATION_ID, notificationId);
final Intent intent = new Intent(context,
PushNotificationLauncherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(extras);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
builder.setContentTitle(context.getString(R.string.app_name));
builder.setContentText(payload.getText());
builder.setSmallIcon(R.drawable.icon_launcher);
builder.setAutoCancel(true);
final PendingIntent pIntent = PendingIntent.getActivity(context, 0,
intent, 0, extras);
builder.setContentIntent(pIntent);
final Notification notification;
if (Build.VERSION.SDK_INT < 16) {
notification = builder.getNotification();
} else {
notification = builder.build();
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationId, notification);
Then I have this in my PushNotificationLauncherActivity:
final Bundle extras = getIntent().getExtras();
final int notificationId = extras
.getInt(SocialcastGoogleCloudMessageReceiver.NOTIFICATION_ID);
final NotificationManager notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
// please go away
notificationManager.cancel(notificationId);
Log.d(PushNotificationLauncherActivity.class.getSimpleName(),
"Touched notification ID: " + String.valueOf(notificationId));
No matter which notification I touch, in the log Touched notification ID: 1234 will always show, even if the notification I touch on has an ID of 56789.
I highly doubt it is an issue with my test-device, but incase it helps; I am using a 2013 Nexus 7 with KitKat 4.4.4 with the Dalvik runtime (not ART) Build KTU84P.
Pass your notificationId as the request code here:
final PendingIntent pIntent = PendingIntent.getActivity(context, 0,
intent, 0, extras);
Change this to:
final PendingIntent pIntent = PendingIntent.getActivity(context, notificationId,
intent, 0, extras);
When comparing two Intent instances, the included Bundles are not compared. So, from android's point of view, the two intents are the same.
Interestingly, the reqCode (second argument in PendingIntent.getActivity(...)) is compared. And this should render your Intents unique.

How can I open activity when notification is touched?

I am building a notification for my Music Player, so it displays what music is playing.
But I want to add a function where, when I touch it. It opens my layout player.xml. Which is deployed through the MainActivity.class.
I have researched on Notifications on developer.android.com and found a way to deploy and activity upon clicking the notification. But it did't work.
Here is my current code -
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setContentTitle(songsList.get(songIndex).get("songTitle"));
builder.setContentText("NexPlay™");
builder.setTicker(songsList.get(songIndex).get("songTitle"));
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setSmallIcon(R.drawable.play_default);
builder.setAutoCancel(true);
builder.setPriority(0);
builder.setOngoing(true);
Notification notification = builder.build();
NotificationManager notificationManger =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManger.notify(01, notification);
Thanks to everyone for answering!
I added
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, NotificationToPlayer.class), 0);
builder.setContentIntent(pendingIntent);
to my notifications and it worked great !
Try this
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.android, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, ServiceLauncher.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.service_label),
text, contentIntent);
notification.defaults |= Notification.DEFAULT_SOUND;
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
nm.notify(R.string.service_started, notification);
}
Hope this will solve your problem
You need to add intent on ur code:-
int icon = R.drawable.app_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message.split(":::")[1], when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = null;
notificationIntent = new Intent(context, MessageDetail.class);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, message.split(":::")[1], intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
You'll also want to add an intent. Something like:
Intent actIntent = new Intent(this, do MyActivity.class);
Then in your builder:
.setContentIntent(PendingIntent.getActivity(MyActivity, 131314, actIntent,
PendingIntent.FLAG_UPDATE_CURRENT))

Multiple notification on same intent

I am writing an application and in this application I need to set multiple notification with same intent just like open my application whenever user tap on any notification.
All the notification comes on different time and date without having any data but the problem is, if I set two notification for 03:27 PM and 03:28 PM then the first notification (03:27 PM) is canceled (Overwritten by second) and second is working correctly.
I am currently using this code for achieving this goal:
this method is used to set notification from Activity:
public static void setNotificationOnDateTime(Context context, long fireTime)
{
int requestID = (int) System.currentTimeMillis();
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, NotificationReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, requestID, i, 0);
am.set(AlarmManager.RTC_WAKEUP, fireTime, pi);
}
and my NotificationReceiver class look like this:
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
Log.w("TAG", "Notification fired...");
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent;
Bundle bundle = intent.getExtras().getBundle("NotificationBundle");
if(bundle == null)
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, SplashScreen.class), 0);
}
else
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MenuScreen.class)
.putExtra("NotificationBundle", bundle), 0);
}
Notification notif = new Notification(R.drawable.ic_launcher,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, "Me", "Message test", contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
I alerady spend a lot time on googling and found some solutions but they didn't work for me here is the link of some of them:
android pending intent notification problem
Multiple notifications to the same activity
If any one knows how to do this please help me.
Quote:
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
But you're always using 1 for the id parameter. Use a unique ID when you post several notifications.
Update If that doesn't help, you can still create Intents which do not compare as being equal, while having an equal effect.
this may be helpful
notif.flags |= Notification.FLAG_ONGOING_EVENT;
the notification will never close...
Try to set as below :
contentIntent=PendingIntent.getActivity(p_context, i, new Intent(context, MenuScreen.class),PendingIntent.FLAG_CANCEL_CURRENT);
It might help you.

Categories

Resources