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() ?
Related
I guess it is hard to explain just by reading the title of this question. I am coding an app that gets ambient factors alerts (temperature, etc) sent by a known server to GCM, and then GCM sends it back to the phone. The whole GCM works well. The problem is when notifications arrive. It is thought to send notifications to the phone when an alert happens (a trigger). Then clicking on the alert launches the activity to display the alert. That is OK, but if there is 2 or more alerts on waiting to be clicked, it will only process one, ignoring the rest ("mensaje"). This is how my notification inside a class that extends extends GcmListenerService looks like.
public static void showAlerts(Context context, String mensaje)
{
Intent notificationIntent = new Intent(context.getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("mensaje", mensaje);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
Random r = new Random();
PendingIntent pendingIntent = PendingIntent.getActivity(context, r.nextInt(),
notificationIntent, 0);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentText("Nueva alerta recibida")
.setSmallIcon(R.drawable.termometrorojo)
.setNumber(UtilidadesGCM.num_notificaciones++)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setDefaults(Notification.DEFAULT_LIGHTS)
.setAutoCancel(true).build();
notificationManager.notify(0, notification);
}
Then in MainActivity, I have the code to process this, and open the activity to display the alert
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String nuevaAlerta = intent.getExtras().getString("mensaje");
procesaAlerta(nuevaAlerta);
//mDisplay.append(nuevaAlerta + "\n");
}
};
public void procesaAlerta (String alerta)
{
Intent intent = new Intent(this, Alertas.class);
intent.putExtra("mensaje" , alerta);
startActivity(intent);
}
The Alertas class will parse the message fine and display it in its activity, but will only do that once. If there are more than 2 alerts stacked to be read, it only process one. If there is one, it works ok. Sorry if I odn't explain better, but it hard not showing all the code.
Thanks!
Try with writing this line
notificationManager.notify( new Random().nextInt(), notification);
instead of
notificationManager.notify(0, notification);
Your notification id is every time same so your last notification only work. Every new notification id is replaced by id 0. So i use random id instead of fixed id 0. I think above code will work for you
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.
I setup GCM and it works fine. I get notifications from the server and they are shown to the client. The problem is, GCM creates its own notification and wont let me make a custom one. I followed this guide: https://github.com/codepath/android_guides/wiki/Google-Cloud-Messaging.
Here is my service code:
public class GcmMessageHandler extends GcmListenerService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
createNotification(from, message);
}
private void createNotification(String title, String body) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true);
Intent resultIntent = new Intent(this, RouteActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(RouteActivity.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(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}
Anything helps.
from the docs
Message payload is optional. If you are including a payload in the message, use the data parameter to include your custom key/value
pairs. The client app handles the data payload for display or other
processing purposes.
The notification parameter with predefined options indicates that GCM
will display the message on the client app’s behalf if the client app
implements GCMListenerService on Android, or whenever the notification
message is sent to an iOS device. The app server can send a message
including both notification and data payloads. In such cases, GCM
handles displaying the notification payload and the client app handles
the data payload. For more information and examples, see
in other words if you send in your payload a notification tag GCM will create a notification for your app
https://developers.google.com/cloud-messaging/server
Custom layout for notifications in Android, if that's what you mean: Create custom notification, android
I have a server with some data and in my app I want to show this data via push-notification, so the problem is I didn't get how to cooperate notification number in status bar with my notifiсations. In my app I get notifications as ArrayList from my server. For each notification I should use a "Notification builder", in which I'll put notify fields like icon, name, desc etc, and at least I should call "NotificationManager.notify" for each of them, but how I can show that I've just gotten 3 messages for example in my status bar(one icon with indicator of 3, NOT 3 icons), and don't multiply a notification sound, but still show all of them when I open a status bar.
My code:
public void sendNotifications(ArrayList<Message> messages){
int notifyID = 0;
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
for(Message message:messages){
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
Resources res = getApplicationContext().getResources();
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, messages.media))
.setTicker("Got a new message")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(message.titile)
.setContentText(message.text);
Notification notification = builder.getNotification();
mNotificationManager.notify(notifyID, notification);
notifyID++;
}
}
UPD
For more understanding what i want to i've added an images
-pic1 When i send notifications - icon shows me how much i got
-pic2 When i opened a status bar it shows me all my notifies
It is possible to do that?
You cannot do that - Combine 3 notification into one.
Either you create a single notification combining all the notifications or like this only.
It is not necessary that you will get 3 notifications. You can get 1 or 2 also.
I don't see the issue here. If there are 3 notifications, you will see 3 icons in the status bar.
Each icon represents an entry in the pull down notification bar- having one icon represent multiple entries wouldn't really make sense.
Notification.Builder has method setNumber to set number of notifications. It's described in Notification docs in Updating notifications section.
You can use Big view notification.
Check here : Notifications
Notification Id must be a constant. If notification id is different it will show as different notifications. So your code must be like this, declare ID and count as field variable:
public static final int NOTIFICATION_ID = 1;
private int notificationCount = 1;
and change the method like this:
public void sendNotifications(ArrayList<Message> messages){
int notifyID = 0;
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
for(Message message:messages){
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(notificationIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent contentIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_CANCEL_CURRENT);
Resources res = getApplicationContext().getResources();
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, messages.media))
.setTicker("Got a new message")
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(message.titile)
.setContentText(message.text);
.setNumber(notificationCount++);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
Thanks
I have a problem. What I want to do is, I just want to display a message in notification bar at frequent time of interval. For that I used two notification methods they are:
Notification notification = new Notification(icon, message, when);
......
notification.setLatestEventInfo(context, title, subTitle, intent);
Currently I am using API level 19. So I came to know above ones are deprecated. I was suggested to use Notification.builder. But after using that I am not getting proper output. Can anyone show me the code how to use Notification.Builder for above 2 statements...
Any help will be appreciated.
you can use this...
public static void createNotification(Context context, Long data) {
Random rnd = new Random();
int i = rnd.nextInt();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.app_icon)
.setContentTitle("Logo").setContentText("text");
mBuilder.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, activity.class);
resultIntent.putExtra(StringUtils.SESSIONID, data);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(activity.class);
// stackBuilder.editIntentAt(index);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(i, mBuilder.build());
Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setSubText(subTitle)
.setContentIntent(pendingIntent)
.build();
This is example is from here: Notification.Builder
To set the time you could use the method setWhen(long timestamp);