android notification shows just the last notificatoin - android

I have application android which gives data from server, i want to make notifications, one notification for each row of data, I want when the user press on the notification, an activity is triggered, i want to do all that using android service, i could do all of that.
my problem is that whatever the notification the user press, it just shows the last row of data.
code:
lient client = new Client(Configuration.getServer());
String str = client.getBaseURI("offers");
try {
JSONArray json = new JSONArray(str);
for (int i = 0; i < json.length(); i++) {
JSONObject oneOffer = json.getJSONObject(i);
int offerID = oneOffer.getInt("ID");
String offerDescriptoin = oneOffer.getString("Description");
String endDate = oneOffer.getString("EndDate");
String startDate = oneOffer.getString("StartDate");
JSONObject restaurant = oneOffer.getJSONObject("Restaurant");
int restaruantID = restaurant.getInt("ID");
String restaurantName = restaurant.getString("Name");
Offer offer = new Offer(offerID, startDate, endDate,
offerDescriptoin, new Restaurant(restaruantID,
restaurantName));
Log.d("DES", offerDescriptoin);
Offer.getAllOffers().put(offer.getID(), offer);
Intent intent = new Intent(this, OfferNotification.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0,
intent, 0);
Uri soundUri = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.addAction(R.drawable.ic_launcher, "call", pIntent)
.addAction(R.drawable.ic_launcher, "more", pIntent)
.addAction(R.drawable.ic_launcher, "add more", pIntent)
.setContentTitle("Offer from " + restaurantName)
.setContentText(offerDescriptoin).setSound(soundUri);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, OfferNotification.class);
resultIntent.putExtra("offerID", offer.getID());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(OfferNotification.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(offer.getID(), mBuilder.build());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Make sure in the following call
mNotificationManager.notify(offer.getID(), mBuilder.build());
the ID passed is unique otherwise any pending notifications with matching ID will be replaced.
Check the documentation too
http://developer.android.com/reference/android/app/NotificationManager.html

Related

Android notification may open twice (or even more) the app

My app sets a notification with the following code:
private void defineAndLaunchNotification(String apppack,String title, String ContentText)
{
Context context = getApplicationContext();
PackageManager pm = context.getPackageManager();
Intent LaunchIntent = null;
String name=null;
try {
if (pm != null)
{
ApplicationInfo app = context.getPackageManager().getApplicationInfo(apppack, 0);
name = (String) pm.getApplicationLabel(app);
LaunchIntent = pm.getLaunchIntentForPackage(apppack);
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Intent intent = LaunchIntent;
if (ContentText.equals("filesystemfullnotification"))
{
intent.putExtra("start", "fullsystem");
}
else
{
intent.putExtra("start","incorrecttime");
}
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder builder=null;
NotificationChannel notificationChannel=null;
int NOTIFICATION_ID = 12345;
if (Build.VERSION.SDK_INT<26) {
builder =
new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true)
.setContentTitle("title
)
.setContentText("Content Text");
}
else
{
int importance=NotificationManager.IMPORTANCE_HIGH;
notificationChannel=new NotificationChannel("mychannel", "channel", importance);
builder =
new NotificationCompat.Builder(getBaseContext(),"mychannel")
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true)
//.setStyle(new NotificationCompat.BigTextStyle().bigText(StaticMethods.giveStringAccordingtoLanguage(title,language)))
.setContentTitle(StaticMethods.giveStringAccordingtoLanguage(title, language))
.setContentText(StaticMethods.giveStringAccordingtoLanguage(ContentText, language));
}
builder.addAction(R.drawable.notification_icon, "OK", pIntent);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);
builder.setVibrate(new long[]{0, 1000, 1000, 1000, 1000});
builder.setContentIntent(pIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=26) {
nManager.createNotificationChannel(notificationChannel);
}
nManager.notify( (int) ((new Date().getTime() +Math.round(Math.random()*5000) / 1000L) % Integer.MAX_VALUE), builder.build());
}
That code sucessfully shows a notification whenever is called, but problem is that if the notification is tapped twice (or more) times it will open as many instances of my application as that number of times.
This happens even though I have defined in my AndroidManifest.xml my application tag with android:launchMode="singleInstance".
What could I do so the notificacion just reacts to the first tap or only one instance of the app appears?
The way you have build the intent you passed into your pending intent could be the problem. Consider building your intent this way:
Intent intent = new Intent(context.getApplicationContext(), <Activity to launch>.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("start", "fullsystem");
By your code you're actually calling to launch the whole application that is why its creating several instances of the application.
You are supposed to launch a particular part of your application, an entry activity to your application.

Local notification in android from database

my requirement is to generate local notification when current time matches with the values in the database.But now the problem is that when I am clicking on the notification it should take me to the specific product details using the product id.
I have generated the notification but how can I get the product title/id to the product details page.
Code----------------
for (int i=0;i < alertList.size();i++) {
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
msg=alertList.get(i).getProf_name()+" have to take "+alertList.get(i).getMed_name()+" ;"+alertList.get(i).getMed_id();
Log.d("MediMSg",""+msg);
Log.d("MediMSg",""+msg);
Intent notificationIntent = new Intent(context, MedicineNotificationActivity.class);
notificationIntent.putExtra("pushmsg",msg);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MedicineNotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(100, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Test")
.setContentText(msg)
.setTicker("Notification from Test")
.setSmallIcon(getNotificationIcon())
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true)
.setColor(0x0091ea)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(m,notification);
Log.d("Random",""+m);
}
When you generate the notification, but the product title/id in the intent as extras. Then in your activity which is started byclicking the notification. You can access these extras.
You can create an array outside the loop, if you have multiple ids, like this:
int[] ids = new int[alertList.size()];
Then in the loop, iterate and set the id for each one on their respective indices.
for (int i=0;i < alertList.size();i++) {
ids[i] = YOUR_ID;
//OTHER Code
}
Lastly, put extra like this:
notificationIntent.putExtra("ids", ids);

How to group pushnotifications in android?

I have implemeted push notification in android,and it comes perfectly as per needed,But only one problem is it displaying as individualy ,I want it in grouping,means if 5 notifications are there,it should display "5 messages" not a list of notification(which is currentl[y coming),My code is as belo,I have found solution that style can do this,and have tried but no change,
code
#SuppressWarnings("null")
public void sendNotification(String title, String description) {
Random random = new Random();
int id = random.nextInt(50);
NotificationCompat.Builder myNotification = null;
NotificationManager notificationManager = null;
notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent myIntent = new Intent(context, ActivityHome.class);
myIntent.putExtra("push", "push");
TaskStackBuilder taskbuiler = TaskStackBuilder.create(this);
taskbuiler.addParentStack(ActivityHome.class);
taskbuiler.addNextIntent(myIntent);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
myNotification = new NotificationCompat.Builder(context);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
// Moves events into the expanded layout
for (int i = 0; i < events.length; i++) {
inboxStyle.addLine(events[i]);
}
// Moves the expanded layout object into the notification object.
myNotification.setStyle(inboxStyle);
myNotification.setStyle(new NotificationCompat.InboxStyle());
myNotification.setContentTitle(title);
myNotification.setContentText(description);
myNotification.setContentIntent(pendingIntent);
myNotification.setDefaults(Notification.DEFAULT_SOUND);
myNotification.setAutoCancel(true);
myNotification.setSmallIcon(R.drawable.app_icon);
myNotification.build();
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, myNotification.build());
}
Check this out:
https://developer.android.com/training/wearables/notifications/stacks.html
Maybe this helps.

GCM start background operations (make post to server) on notification click

I'm using Google Play Services lib for GCM and all works great.
Now I implement 2 buttons (actions) in my notificationCompat.Builder:
- One open app.
- Other one delete some unread messages: for this operation I post some dato to server.
How can I launch a post to my server on notification action click without open any activity in front of user?
Thank you very much!!!!!
Here my code:`Intent openIntent = new Intent();
Intent cancelIntent = new Intent();
if (has1Id) {
//go details!
openIntent = new Intent(this, NotificationActivity.class);
openIntent.putExtra("id", ids.get(0));
//cancell intent: start async operation in background
cancelIntent = new Intent(this, HomeActivity.class);
cancelIntent.putExtra("id", ids.get(0));
}else{
//go home!
openIntent = new Intent(this, HomeActivity.class);
//cancell intent: start async operation in background
cancelIntent = new Intent(this, HomeActivity.class);
cancelIntent.putExtra("id", ids);
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent cancelNotificationIntent = PendingIntent.getActivity(this, 0,
cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long[] vibrationPattern = {0, 200, 800, 200, 100, 500};
Uri soundUri = Uri.parse("android.resource://"+ getPackageName() + "/" + R.raw.jingle1);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setContentTitle(title) //set title
.setContentInfo(numNotRead) //number of unread content
.setAutoCancel(true)
.setContentText(msgs.get(0)+"...")
.setVibrate(vibrationPattern)
.setSound(soundUri)
.setLights(Color.rgb(255, 165, 00), 800, 800)
.setContentIntent(contentIntent).addAction(R.drawable.ic_notification, getString(R.string.open_app), contentIntent)
.setContentIntent(cancelNotificationIntent).addAction(android.R.drawable.ic_delete, getString(R.string.mark_read), cancelNotificationIntent);
if (has1Id) {
NotificationCompat.BigTextStyle bigTextStyle =new NotificationCompat.BigTextStyle().bigText(msgs.get(0));
mBuilder.setContentTitle(getString(R.string.notification_new_content));
//get only 1 long text: the description of content
mBuilder.setStyle(bigTextStyle);
}else{
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(getString(R.string.notification_new_contents));
for (int i=0; i < msgs.size(); i++) {
inboxStyle.addLine(msgs.get(i));
}
mBuilder.setStyle(inboxStyle);
}
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());`
You should use another class as the intent receiver for cancelIntent, like a BroadcastReceiver and handle the intent there with no UI.
public class MyIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(MY_INTENT)) {
// TODO Handle a notification
}
}
}
You also can use a Activity with no UI as the intent, but I think previous option is better.
More info:
Android Activity with no GUI

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.

Categories

Resources