No title in Amazon SNS GCM push notification - android

I am using Amazon SNS console to send android mobile push notification. I did receive push notification but only the body message is displayed, the title is not displayed.Also when the notification was touched the app was not opened. I am using Amazon AWS SDK for Unity.

It would be great if you share some code, but as i understand you want to receive push with title and body message, so you have to retrieve it first.
When you receive push intent in your Service you should call intent.getExtras().getString("title"). And if you want to open app when you click on push notif you should set it up in your notification Intent.
Here is a simple example how to do it:
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty() && messageType != null) {
switch (messageType) {
case GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR:
Toast.makeText(this, GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR, Toast.LENGTH_SHORT).show();
break;
case GoogleCloudMessaging.MESSAGE_TYPE_DELETED:
Toast.makeText(this, GoogleCloudMessaging.MESSAGE_TYPE_DELETED, Toast.LENGTH_SHORT).show();
break;
case GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE: // retrieve your data here
Log.d("onHandleIntent", "Message= " + extras.getString("message"));
Log.d("onHandleIntent", "Title= " + extras.getString("title"));
sendNotification(extras.getString(message), extras.getString(title));
}
}
PushBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg, String title) {
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, MainActivity.class); // activity wich you want to open when click on push notification
notificationIntent.putExtra(NOTIFICATION_TAG, msg);
notificationIntent.putExtra(NOTIFICATION_TITLE_TAG, title);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notifications)
.setContentTitle(title)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

As #Jarik said you would have to do that.
Also assuming youre facing the same problem i did, create a jar file whose class extends the gcm listener or whatever class the callbacks work with(dont remember the name right now, open their class file and you will find the java classes extending the gcm receivers), and then use intent for the notification touch that would open the application. Also this would let you use the title functionality. I found that somehow in amazon sns sdk class files, they have overwritten the title with a "" hence the title always seem to be blank.
Dont forget to put UnityPlayerProxyActivity in the Android manifest.

Related

Clicking on FCM notification opens currently closed activity not targeted activity

Here is my code, When my app is running in foreground it opens targeted activity but when app is closed or in background, it doesn't opens targeted activity, please help me to solve this problem
I want that by clicking on notification will open targeted activity even app is running / closed.
public void onMessageReceived(RemoteMessage remoteMessage) {
session = new Session(this);
// if (session.getBscloggedin() || session.getAdploggedin()) {
// Log.d(TAG, "FROM:" + remoteMessage.getFrom());
//Check if the message contains data
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data: " + remoteMessage.getData());
}
//Check if the message contains notification
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Mesage body:" + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
/**
* Dispay the notification
* #param body
*/
private void sendNotification(String body) {
//for CS101 announcement notification
if (body.contains("CS101")) {
Intent intent = new Intent(this, CS101noti.class);
intent.putExtra("body", body);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0/*Request code*/, intent, 0);
//Set sound of notifica tion
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("mine")
.setContentText(body)
.setAutoCancel(true)
.setSound(notificationSound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /*ID of notification*/, notifiBuilder.build());
}
Request code should be unique.
Generally people share with us example like giving request code 0(zero). I am the one of copy/paste developer sometimes. But recently I faced with error using this line.
PendingIntent.getActivity(myContext, 0, myIntent, 0);
Whenever app receives notification, intent activity receives old data because of requestCode. Here is the documentation about that method.
Returns an existing or new PendingIntent matching the given
parameters.
So second parameter(requestCode) should be unique to intent. If you use same request code for every notification, activity will be receive old data. So your requestCode should be unique.
There is also another solution.Use PendingIntent.FLAG_UPDATE_CURRENT as flag. The doc says that;
If the described PendingIntent already exists, then keep it but
replace its extra data with what is in this new Intent.
onMessageReceived callback is not called when you receive notification messages in background. If you receive this type of message in background, you can only handle that in a launcher activity.
The solution would be to either change the backend so that it sends only data messages and you handle them internally, or write some routing code inside your launcher activity.
use "click_action" attribute from your backend from which you are sending push notifications. in that attribute value, you have to pass the fully qualified class path of activity, which should be opened when you click on that notification.for more reference refer handling firebase push
Intent intent = new Intent(this, CS101noti.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
....

handle different types of notifications in android

I have 3 types of notifications in android.Audio/Video call and msg. How to differentiate based on notification type and open different activity on different notification. THis is hoW I open activity on click of notification.
private void sendNotification(long when,String msg) {
String notificationContent ="Notification Content Click Here to go more details";
String notificationTitle ="This is Notification";
//large icon for notification,normally use App icon
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
int smalIcon =R.drawable.hcp;
String notificationData="This is data : "+msg;
/*create intent for show notification details when user clicks notification*/
Intent intent =new Intent(getApplicationContext(), NotificationDetailsActivity.class);
intent.putExtra("DATA", notificationData);
/*create unique this intent from other intent using setData */
intent.setData(Uri.parse("http://www.google.com"));
/*create new task for each notification with pending intent so we set Intent.FLAG_ACTIVITY_NEW_TASK */
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.hcp)
.setContentTitle("GCM Notification")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(smalIcon)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setContentText(notificationContent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentIntent(pendingIntent);
;
Notification notification=mBuilder.build();
mBuilder.setContentIntent(pendingIntent);
mNotificationManager.notify((int) when, notification);
Log.d(TAG, "Notification sent successfully.");
}
Assuming that the data (msg) your receiving is from a web service. Now along with the msg parameter, you must be getting some other parameters by which you can distinguish that the following notification is Audio/Video call or message.
So you can create a method that will return the class name which can be used instead of NotificationDetailsActivity.class
private Class<?> getClassFromType(String type) {
if(type.equals("Audio")
return AudioActivity.class;
else if(type.equals("Video")
return VideoActivity.class;
else if(type.equals("Message")
return MessageActivity.class;
}
The final code will be something like this:
Intent intent =new Intent(getApplicationContext(), getClassFromType(type));
Here type will be the variable that distinguishes the notification.
Hope this will solve your problem.

Get unseen android notifications

I have a service that shows a notification PendingIntent each time it receives a new GCM message. The problem is that the GCM messages can be of different kinds. And if many notifications leave unread, I want not to show them separately but in groups like:
you have 3 unread messages of type A
you have 2 unread messages of type B
you have 4 unread messages of type C
As far as I understand, to get this effect I need to have an access to unread/unseen notifications. Each time when I new notification comes I can check, if there is another unread message of this type, and then decide, whether I create a new notification or update an old one.
My question is: is there a way to see, which notifications are unseen and get access to them?
For any case this is my method to create a message; if an argument notificationId is 0 a new notification should be created. Else - updated.
private int sendNotification(String msg, Integer notificationId) {
Log.d(TAG, "sending message with text: "+msg);
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Random random = new Random();
int notification_id = notificationId==0?random.nextInt(9999 - 1000) + 1000:notificationId;
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notification);
Intent intent = new Intent(this, MainActivity.class);
// Send data to NotificationView Class
intent.putExtra("text", msg);
PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("escos")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(pending);
mBuilder.setContent(remoteViews);
remoteViews.setTextViewText(R.id.notiftext, msg);
remoteViews.setImageViewResource(R.id.notifim, R.drawable.ic_launcher);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager.notify(notification_id, notification);
return notification_id;
}
For different Notification strip (A, B, C etc.) in your status bar, use different NOTIFICATION_ID for building the Notification on basis of your defined type or collapse_key received from GCM.
For determining unread and read messages, use a local variable (counter) in Shared Preferences and increment it each time a specific type of Notification comes (on basis of defined type or collapse_key).
Then generate the Notification with that particular NOTIFICATION_ID as Notification with particular NOTIFICATION_ID can override each other. So You can override the previous Notification with Iterative Numbered text in New Notification.
As soon as user click on any Notification or particular Notification, clear the notification and reset the value of (counter) in Shared Preferences.
Edit1 : When you click on Notification with particular Pending Intent, then in that Activity use this code for removing all the Notifications generated from your app :
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try {
nMgr.cancelAll();
} catch (Exception e) {
e.printStackTrace();
}
Note : Do remember to add Try-Catch before you call cancelAll() as cancelAll() may not be supported by the device model and will generate
java.lang.SecurityException: Permission Denial
error.
Edit 2:
You can also use nMgr.cancel(NOTIFICATION_ID); to clear a specific notification, pass NOTIFICATION_ID to particular intent via extras and get the extras in that activity to cancel a particular notification.
And as you click on any notification it will be cleared from status bar unless you have not set .setAutoCancel(false) in your Notification Builder.

To generate push notification based on user current device location in android

I am able to get push notification from server but my app should receive push notification when user device location change in latitude and longitude.
Case 1:
I have to send device latitude and longitude values to server and it has to send push notification whenever user device current location change.(Moves from Place A to Place B to get notification) even if the app is running in background,app needs to configure with system OS to get push.
Case 2:
Iam able to move to activity while clicking on push notification but i need like if i have received two push notification from server clicking on first notification it has to take FirstActivity and clicking on second push notification take to secondActivity.
How to identify which push notification is to redirect to activity.
code to show push notification in GCMNotificationIntentService:
private void createNotification(String msg){
Log.d(TAG, "Preparing to send notification...: " + msg);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.offer, "GCM Notification", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, FirstActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, NOTIFICATION_ID,notificationIntent, 0);
notification.setLatestEventInfo(this, "Message From GCM", msg, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_ID, notification);
NOTIFICATION_ID = NOTIFICATION_ID + 1;
}
1.You need to create service which will be runing in background. Also you need somehow send notification to the telephone from your server and handle it. But it could be achived without server, you could just listen to LocationListener.OnLocationChanged
2.According to second question you can prepare right Intent before displaying notification, assign it to the notification, and after clicking it, you will be moved directly to this activity.
Intent intent = //prepare your intent
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentIntent(contentIntent);
notificationManager.notify(notificationId, builder.build());

android NotificationCompat.Builder getNotification automatically sent notification

Hi I am trying to send a notification in BroadcastReceiver when receive a broadcast message. from Parse.com. But When call getNotification method from an instance of NotificationCompat.Builder, the notification automatically sent and displayed with a canned contextText. So when call mNotificationManager.notify, TWO notification shows up and one with specified content text and the other one without. I am on API level 16.
Following is my code in BroadcastReceiver, please help me. Thank you very much!
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
if (intent.getExtras() != null) {
JSONObject json = new JSONObject(intent.getExtras().getString(
"com.parse.Data"));
String text = json.getString("text");
String title = json.getString("title");
Long timestamp = json.getLong("timestamp");
String qid = json.getString("qid");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(text)
.setTicker("New Reply");
Intent resultIntent = new Intent(context,
QuestionViewActivity.class);
resultIntent.putExtra(QuestionViewActivity.EXTRA_QUESTION_ID,
qid);
TaskStackBuilder stackBuilder = TaskStackBuilder.from(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = mBuilder.getNotification();
mNotificationManager.notify(qid.hashCode(),
mBuilder.getNotification());
}
I finally got it:
For no build() method: It is caused by ActionBarSherlock using a old version of android-support-v4.jar. Just replace that jar with the updated one from /SDK/extras/android/support/v4/android-support-v4.jar
For the duplicated notification: It is caused by Parse(parse.com) service. When receiving any Push sent with parse notification lib with "title" in the JSON data, the service automatically shows the notification with canned contentText like "you received a notification". A trick here I used to disable the automatic notification is DO NOT use "title" and "text" in the JSON data of parse Push, instead use other names and then parse it in the customized broadcast receiver. It works fine now.
Thanks!
http://developer.android.com/reference/android/app/Notification.Builder.html#build()
getNotification() is deprecated. Why not use build() ?

Categories

Resources