Android: Transferring Data via ContentIntent - android

I've got a problem with my Android Application. It receives Messages via Google Cloud Messaging and displays a Notification in the Notificationbar. I want to transfer some Data with the Notification. This Data comes via Google Cloud Messaging and should be attached to the Notification.
This is my Code to Display the Notification:
private void setNotification(String strTitle, String strMessage, int intPageId, int intCategorieId)
{
notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intentOpen = new Intent(this, NotificationClick.class);
intentOpen.putExtra("pageId", Integer.toString(intPageId));
intentOpen.putExtra("categorieId", Integer.toString(intCategorieId));
intentOpen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intentOpen, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.launcher_icon)
.setTicker(strTitle)
.setContentTitle(strTitle)
.setStyle(new NotificationCompat.BigTextStyle().bigText(strMessage))
.setContentText(strMessage);
notificationBuilder.setContentIntent(contentIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
notificationManager.notify(intCategorieId, notificationBuilder.build());
}
And my Code to get the Variables "intPageId" and "intCategorieId" in a other Activity(witch opens by clicking the Notification) back, is this:
Bundle intentExtras = new Bundle();
intentExtras = getIntent().getExtras();
Toast.makeText(this, "Page To Open: " + intentExtras.getString("pageId"), Toast.LENGTH_LONG).show();
Toast.makeText(this, "Page To Open: " + intentExtras.getString("kategorieId"), Toast.LENGTH_LONG).show();
But in both "Toast" Messages appears "null", or the value that was passed through at the first time, clicking on the Message.
For Example:
At the First time I send: intPageId=1.
The Toast says: "Page To Open: 1".
At the Second time I send: intPageId=2.
The Toast says: "Page To Open: 1".
I'm totally confused.

First Method :
Instead of below line :
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intentOpen, 0);
change it to this :
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intentOpen, PendingIntent.FLAG_UPDATE_CURRENT);
Second Method :
int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),iUniqueId, intentForNotification, 0);

Related

When Notification is Clicked all other notification are also gone

I am Generating Notification using Firebase ,suppose there are 3 notification if user clicks on any one all the notification are gone ,here what i need is that when user clicks on one notification than the other 2 should be there in notification here is my code wt i have done.
Intent intent;
if (pref.getString("id","").equals("")){
intent = new Intent(this, Login_Activity.class);
}else {
intent = new Intent(this, TicketListActivity.class);
}
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
String msgBody = remoteMessage.getData().get("body");
String ticketid = remoteMessage.getData().get("ticket_Id");
Notification notification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.app_launch)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("body")).setAutoCancel(true).setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getData().get("body")))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setOngoing(true)
.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
// manager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
manager.notify((int) System.currentTimeMillis(), notification);
some info about PendingIntent.FLAG_ONE_SHOT
Flag indicating that this PendingIntent can be used only once. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
If set, after send() is called on it, it will be automatically canceled for you and any future attempt to send through it will fail.
try to change this flag to FLAG_UPDATE_CURRENT
also avoid this line
(int) System.currentTimeMillis()
currentTimeMillis is long so someday it may throw exception- yes, I know we have a lot of time until this moment, but still... use "real" id as Integer - for PendingIntent you may just put 0, for manager.notify I would advise you to set some int id = 0; and increment it with every posted notification, so every next would have id = prevNotificationId + 1 (use e.g. SharedPreferences for storing last used id)

Coding problem about post notification on android

I need to Rewrite all the deprecated methods and class.
private void showNotification(Peer peer, int id) {
CharSequence text = getString(id) + " " + peer.getName();
Notification notification = new Notification(R.drawable.notification, text, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, IPsecToolsActivity.class); //intent.setAction(ACTION_NOTIFICATION);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, getText(R.string.native_service_label), text, contentIntent); //setLatestEventInfo method has been deprecated
// Send the notification.
mNM.notify(peer.getName(), R.string.notify_peer_up, notification);
}
Note that the Notification is deprecated, too old.
Cannot use setLatestEventInfo method.
I need help rewrite it in alternative way.
The way I rewrite this is as following: Please let me know if I was right or not.
private void showNotification(Peer peer, int id) {
CharSequence text = getString(id) + " " + peer.getName();
Context context = this;
Notification notification = new Notification.Builder(context)
.setContentText(text)
.setSmallIcon(R.drawable.notification)
.setWhen(System.currentTimeMillis())
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, IPsecToolsActivity.class);
//intent.setAction(ACTION_NOTIFICATION);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, 0);
// Send the notification.
mNM.notify(peer.getName(), R.string.notify_peer_up, notification);
}

Notification with multiple buttons

I need to display notification with two buttons. Different operation need to perform for each button.so for that I have written following code but when I'm getting multiple notification delete action is not performing.
Random NOTIFICATION_ID = new Random();
int CANCELNOTIFICATIONID = NOTIFICATION_ID.nextInt();
// define sound URI, the sound to be played when there's a notification
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Log.i("******* Service6", "" + msg);
// intent triggered, you can add other intent for other actions
Intent intent = new Intent(GcmIntentService.this, LoginActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(GcmIntentService.this, 0, intent, 0);
Intent deleteIntent = new Intent(GcmIntentService.this, DeleteArchiveLoopActivity.class);
deleteIntent.putExtra(LoopMeConstants.EXTRA_DELETE_ARCHIVE_LOOPS, "Delete loops");
Trace.i(TAG, "Looptype Delete loop");
deleteIntent.putExtra("DELETE_ARCHIVE_LOOP_ID", loopId);
deleteIntent.putExtra("NOTIFICATONID", CANCELNOTIFICATIONID);
deleteIntent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
// PendingIntent pDeleteIntent = PendingIntent.getActivity(this, 145623, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent archiveIntent = new Intent(GcmIntentService.this, DeleteArchiveLoopActivity.class);
Trace.i(TAG, "Looptype Archive loop");
archiveIntent.putExtra(LoopMeConstants.EXTRA_DELETE_ARCHIVE_LOOPS, "Archive loops");
archiveIntent.putExtra("DELETE_ARCHIVE_LOOP_ID", loopId);
archiveIntent.putExtra("NOTIFICATONID", CANCELNOTIFICATIONID);
archiveIntent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
// PendingIntent pArchiveIntent = PendingIntent.getActivity(this, 145623, archiveIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_launcher);
notificationBuilder.setContentTitle("Sample");
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(mPushtext));
notificationBuilder.setContentText(mPushtext);
notificationBuilder.setSound(soundUri);
notificationBuilder.addAction(R.drawable.delete, "Delete", PendingIntent.getActivity(this, 145623, deleteIntent, PendingIntent.FLAG_ONE_SHOT));
notificationBuilder.addAction(R.drawable.archive, "Archive", PendingIntent.getActivity(this, 145623, archiveIntent, PendingIntent.FLAG_UPDATE_CURRENT));
notificationBuilder.setAutoCancel(false);
// notificationBuilder.setContentIntent(pArchiveIntent);
Log.i("GCMIntent Srevice5", "" + msg);
notificationBuilder.setOngoing(true);
mNotificationManager.notify(CANCELNOTIFICATIONID, notificationBuilder.build());
How to solve this issue.
You need to use different requestCode in Pending intent
notificationBuilder.addAction(R.drawable.delete, "Delete", PendingIntent.getActivity(this, 1, deleteIntent, PendingIntent.FLAG_ONE_SHOT));
notificationBuilder.addAction(R.drawable.archive, "Archive", PendingIntent.getActivity(this, 2, archiveIntent, PendingIntent.FLAG_UPDATE_CURRENT));
In the below way i have solved it.
in the intent i have given two differentactivities
Intent deleteIntent = new Intent(GcmIntentService.this, DeleteLoopActivity.class);
Intent archiveIntent = new Intent(GcmIntentService.this, ArchiveLoopActivity.class);
notificationBuilder.addAction(R.drawable.delete, "Delete", PendingIntent.getActivity(this, CANCELNOTIFICATIONID, deleteIntent, 0));
notificationBuilder.addAction(R.drawable.archive, "Archive", PendingIntent.getActivity(this, CANCELNOTIFICATIONID, archiveIntent, 0));
The above code solves my problem
Thanks all

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

How to correctly open file on notification click

I'm donloading files from the Internet using IntentService and displaying a Notification while download is in progress. After download complete I need to be able to click on the notification to open downloaded file in appropriate application. Here's a code I'm using for this:
Intent intent = IntentUtils.getOpenFileIntent(task.getTargetFolder()
+ File.separator + task.getFileNode().getName());
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
taskStackBuilder.addParentStack(MainActivity.class);
taskStackBuilder.addNextIntent(intent);
PendingIntent pi = taskStackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pi);
And here's how I create the Intent:
public static Intent getOpenFileIntent(String path) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String extension = fileExt(path);
String type = mime.getMimeTypeFromExtension(extension);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, type);
return intent;
}
The issue is that tapping on the notification closes any of the currently opened app. I just need to display application chooser over the currently opened app. I think that the issue is in TaskStackBuilder usage but there's no other way to create PendingIntent instance for ACTION_VIEW Intent.
You need to create PendingIntent and set to your Notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_CANCEL_CURRENT)
Fore more information go to http://developer.android.com/guide/topics/ui/notifiers/notifications.html
private NotificationManager manager;
private Intent notiIntent;
/// id is integre value which in unique for notifications
notiIntent= new Intent(context, CurrentActiivty.class);
notiIntent.putExtra("id", id);
notiIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Notification notification = new Notification(R.drawable.icon, "your text on notification bar", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notiIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context,"text here", message, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notiIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
manager.notify(id, notification);
Now In calling actiivty write the following code
Bundle extras = getIntent().getExtras();
int id= extras.getInt("id");
NotificationManager notificationManager;
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(id);

Categories

Resources