I have a method which receives text from a push notification, via the Parse API, and packages it into a notification object. Pretty standard stuff. My problem is that I'm trying to use a BigTextStyle to display my notification in the list, but it refuses to do so, and only shows one line of text and the two-finger gesture does not cause it to expand.
However, if I tap the notification, which opens the app, then return to the notification list, it is displayed in the BigTextStyle and is responsive to gestures. So, my guess is that somehow tapping on the notification is activating it and allowing the BigTextStyle code to kick in.
I like that tapping on the notification opens the app, but I don't want to force my users to open the app then close it again to see the full text of my messages. So is there a way I could either make the notification display in the BigTextStyle format from the start, or to make it so that the first click "activates" the notification, allowing the full message text to be seen, and then a second click opens the app? Any help would be appreciated.
Here is my code from the Notification method:
public void receiveNotification() {
NotificationCompat.BigTextStyle bts = new NotificationCompat.BigTextStyle();
bts.bigText(SplashActivity.globalDataString);
bts.setSummaryText("Tap to open app, swipe to dismiss message");
NotificationCompat.Builder m = new NotificationCompat.Builder(this);
m.setContentTitle("New Push Notification")
.setContentText(SplashActivity.globalDataString)
.setSmallIcon(R.drawable.app_icon)
.setStyle(bts)
.build();
Intent openApp = new Intent(this, MenuActivity.class);
// This ensures that navigating backward from the Activity leads out of
// the application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MenuActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(openApp);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
m.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(pushMessageID, m.build());
pushMessageID++;
//reset notification
flag1 = false;
}
EDIT: I think my problem is with where I'm calling my receiveNotification() method from. Right now I have it in the onCreate() method of my app's starting activity, which doesn't make much sense looking back. Should I put it in my broadcastReceiver class, or would there be a better place to put it?
Yes, the creation and display of the notification is usually done either in the broadcast receiver, or in an intent service started by the broadcast receiver. Only when the user taps the notification, the relevant activity is launched. You can see Google's client code sample here.
Related
I have the following notification logic inside a class that extends GcmListenerService, and gets called when one notification arrives. Then, when clicked, the app takes you to MainActivity where the notification is displayed properly.
public static void mostrarAvisoBarraEstado(Context context, String alerts)
{
Intent notificationIntent = new Intent(context.getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("alerts", alerts);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, new Random().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("Alert received")
.setSmallIcon(R.drawable.nubeazul)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setGroup(GRUPO_ALERTAS)
.setGroupSummary(true)
.setAutoCancel(true)
.build();
//notificationManager.notify(0, notification);
notificationManager.notify (new Random().nextInt(), notification);
}
So, right now, each one is displayed separately, and if they build up, the result is rather ugly with all the notification bar full of little icons. Can you guys help for an elegant solution since I am kindda new to Android? Thanks a lot!
NEW STUFF ADDED today!
If I take the notify random out, leaving something like notificationManager.notify(0, notification);, I will get just one notification, but nothing else, then when it launches MainActivity (its onResume() method) it will only display one notification and all the "piled up ones" are just discarded when clicked on the one notification. What I want to achieve is that while maintaining a clean display, i.e: one group notification for all GCM, if I click on the group, I will get each and every notification displayed throught the Alerts.class (something like looping through the notifications, and starting the activity Alerts for each one.
#Override
protected void onResume()
{
super.onResume();
if (getIntent().hasExtra("alerts"))
{
Bundle extras = getIntent().getExtras();
Intent intent = new Intent(this, Alerts.class);
intent.putExtra("alerts" , extras.getString("alerts"));
startActivity(intent);
getIntent().removeExtra("alerts");
}
}
Then the Alerts class will nicely display the alert which it does, but one per notification.
So I tried out your code and managed to see reproduce what you were encountering (I just manually created dummy notifications). So the reason that the Notifications were piling up was because the id you are passing in the notificationManager.notify() is different from one another. As to what I have observed on the Notification and NotificationManagers behavior so far, the id indicated in notify() it kinda represents the id location/position (not sure what to call it) of the Notification that is under the NotificationManager, not an id of the Notification itself.
Imagine the NotificationManager as an array or list. If for example, you have 3 visible notifications on the Status Bar:
Notification 1, Notification 2, Notification 3 and their ids are as follows: 0, 1, 2.
If you generate a new Notification 4 then called notify passing it as a parameter, and the id 1, the notifications that will be currently shown in the NotificationManager would result to something like this:
Notification 1, Notification 4, Notification 3 and their ids are as follows: 0, 1, 2.
So the reason that you're notifications are piling up and NOT grouping together is because you end up with different ids when calling notify() while passing new Random().nextInt().
As per the behavior that I think you are aiming for -- Joining the notifications from your app into one -- the implementation is simple when understood, but I think it's still a little bit tricky. It's like you have to check first if there is more than 1 notification already, then if yes, you create a summary notification with the details and you show it alone (mind the id ;)) and all of those other stuff. I found this blog though that I think might help you with it. Or you can simply just check out the official docs on Stacking Notifications.
So bottom line, simply use a single id to pass in notify() when it comes to your apps Notifications. Hope this helps. Cheers! :D
I just succesfully created a bunch of pages notifications on my Wear device.
The only problem is that the PendingIntent does not seems to start an Activity
(which is of course declared in Manifest).
Here is my code:
List extras = new ArrayList();
Intent viewIntent = new Intent(getApplicationContext(), DetailActivity.class);
viewIntent.putExtra("KEY", "TEST123");
//Note: I also tried: Intent viewIntent = new Intent(getApplicationContext(), DetailActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent viewPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, viewIntent, 0);
for (Route aRoute : myRoutes) {
Notification aNotif = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("BUS " + aRoute.route_short_name)
.setContentText(aRoute.directions.get(0).trip_headsign)
.setLargeIcon(bitmap)
.setContentIntent(viewPendingIntent)
.setSmallIcon(R.mipmap.ic_launcher).build();
extras.add(aNotif);
}
NotificationCompat.Builder builder1 = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(desc)
.setContentIntent(viewPendingIntent)//Just in case
.setSmallIcon(R.mipmap.ic_launcher);
Notification notification = builder1
.extend(new NotificationCompat.WearableExtender()
.addPages(extras))
.setContentIntent(viewPendingIntent)//Just in case
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
When I press on a Notification, I expect the intent to start, but nothing happens..
Any suggestion is welcome.
EDIT:
This code works, just after the notification, so, the second activity can easily be launched withour bug:
startActivity(viewIntent);
EDIT2:
There is now an "open" button at the end that works fine, but still nothing happens on individual notifications (every pages)
Pages are not clickable - on Android Wear, only actions are clickable. For phone generated notifications, those only appear after all pages
If you have a content intent on your phone generated notification, that will always appear as an 'Open on phone' action. There is no way to disable this unless you remove your content intent (making the notification unclickable on phones).
I say 'phone generated' as you can also create a Wear app. By using the data layer to push messages to your Wear app, the Wear app can then build custom notifications. These notifications allow you to use setDisplayIntent() and display activities inline (either as the main page or as separate pages). These activities can, of course, contain any View you want, including actions to perform any action (such as send a message back to the phone to start a particular activity).
Note that because pages are not clickable by default, styling of a custom notification should make it very obvious that the items are clickable. Rather than using a custom notification activity, you may consider using setContentAction() to display the action icon inline with the rest of the layout - this removes the action as a separate element past the action and places it directly on the notification/page.
I am using the following code showing the notification, it works properly. I am look for the listener from which i can come to know whether the notification is expanded or not.
I want to open the app if the notification is expanded or else open the particular activity of the app.
Intent intent= new Intent(context, Activity1.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, getNextRandom(), intent, 0);
Builder newBuilder newBuilder = new Notification.Builder(context);
newBuilder.setContentTitle(title)
.setContentText(subtitle)
.setAutoCancel(true)
.setSmallIcon(R.drawable.icon)
.setTicker(notificationMessage)
.setContentIntent(pendingIntent);
Notificationnotification = new Notification.BigTextStyle(newBuilder)
.setBigContentTitle(notificationTitle)
.bigText(text)
.build();
Let me know if there is way to acheive this?
There is no way to know if the notification is open... What you can do is add buttons to the expanded notification that pressing on them will act differently than pressing on the notification itself.
There maybe no direct way, but maybe the following hack can help!!
You can have a custom notification layout and use RemoteView, Set a setOnClickPendingIntent to launch a service for the entire view so that you get notified when the notification is clicked.
When the user clicks the notification, service is started and show the new expanded custom layout from the service (you replace the old notification with the new one)
Maybe show your initial notification also from the same service using startforeground, so that your app is not killed and the view click can be received faster since service is already running and response time for changing the view is lower.
see this for remoteview and this for launching service from notification click.
My question is a bit complicated so I am going to describe it briefly what I want to achieve. My application receives messages from GCM without any issue. When application is running and is visible to the user I am not displaying notification in Action Bar, I am displaying this message in dialog alert. I use BroadcastReceiver to achieve this.
The main issue is that, when app gets a few notifications in no time. When main activity is visible to the user, the first notification will be shown in dialog alert. And next will be placed in Action Bar as usual Android notifications. And at this moment user disposes the dialog alert and is going to choose a next notification from Action Bar. At this moment I am using in my CloudService (extends IntentService) intent with flag Intent.FLAG_ACTIVITY_CLEAR_TOP and also PendingIntent.FLAG_UPDATE_CURRENT flag for pendingIntent. PendingIntent is just the contentIntent for my NotificationCompat.Builder.
It works in this way that for each user click on the notification from Action Bar, my activity is refreshing (floats to the lower device edge and then floats from the upper edge with dialog alert with message - I am getting the extras from the intent in onResume method). This action is quite OK. Activity has only one instance in that case - I don't have to break through the few instances of the same activity while I have opened few notifications. But the big problem is that when user chooses any of the notifications in each case the last one will open in dialog alert. Activity seems to has the same intent despite of PendingIntent.FLAG_UPDATE_CURRENT.
There are two methods in CloudService which handle cloud messages:
private void showNotification(Bundle extras) {
notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String message = extras.getString(CloudMetaData.MESSAGE);
if (App.isMyActivityVisible() && !CloudMessageDialogFragment.isAttached()) {
sendBroadcast(message, NOTIFICATION_ID);
} else {
Intent intent = new Intent(this, MyParentActivity.class);
intent.putExtra(CloudMetaData.MESSAGE, message);
intent.putExtra(CloudMetaData.NOTIFICATION_ID, NOTIFICATION_ID);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(getString(R.string.app_name));
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(alert));
builder.setContentText(alert);
builder.setAutoCancel(true);
builder.setDefaults(Notification.DEFAULT_SOUND);
builder.setContentIntent(contentIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
NOTIFICATION_ID++;
}
And method which send broadcast is just like that:
private void sendBroadcast(String message, int notificationId) {
Intent intent = new Intent();
intent.setAction(ACTION_FROM_CLOUD_SERVICE);
intent.putExtra(CloudMetaData.MESSAGE, message);
intent.putExtra(CloudMetaData.NOTIFICATION_ID, notificationId);
sendBroadcast(intent);
}
In which way can I achieve similar solution? But it is important for user of course to open notification from Action Bar and shown him its correct message.
EDIT
I have switched my dialog alert into the dialog activity. This is its definition in AndroidManifest:
<activity
android:name="com.myapp.activity.CloudMessageDialogActivity"
android:theme="#android:style/Theme.Dialog"
android:parentActivityName="com.myapp.activity.MyParentActivity"/>
But the result is still the same - when app receives a few notifications, clicking on one of them will open the dialog with the intent for the last received notification.
But the big problem is that when user chooses any of the notifications in each case the last one will open in dialog alert. Activity seems to has the same intent despite of PendingIntent.FLAG_UPDATE_CURRENT.
That's because you are using the same request code (i.e., 0) for all PendingIntents here:
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
By doing so, you are ultimately receiving the same intent, because the platform is failing to see the difference between the intents and delivering the same object everytime:
... it is important to know when two Intents are considered to be the same for purposes of retrieving a PendingIntent. A common mistake people make is to create multiple PendingIntent objects with Intents that only vary in their "extra" contents, expecting to get a different PendingIntent each time. This does not happen. The parts of the Intent that are used for matching are the same ones defined by Intent.filterEquals. If you use two Intent objects that are equivalent as per Intent.filterEquals, then you will get the same PendingIntent for both of them.
So, instead of a constant value, please use a unique request code. For e.g. change the above line with:
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Hope this helps.
I am using code similar to Creating a simple notification to create and show a notification from a network call.
The issue is that I want the activity that responds to the notification to do it's business and then on a backbutton click, put the previously active activity back in the foreground, with it's back stack intact. This is regardless of if the previously active activity was part of my app or somebody elses.
Currently it is following the generated TaskStackBuilder. Leading it back up the app hierarchy and out to the home screen. This is bad UI-design as it breaks the work-flow of anyone using the device, forcing them to manually go back to their app and spending more buttonclicks than necessary. It is also rather unintuitive.
According to the official desing guidelines this is how it should work. The implementation I linked to higher up makes back button have the same functionality as up button should have
It is also a common way to implement it in a plethora of other apps, including official google ones (google-play update notifications come to mind), so there must be a relatively standard way to do this.
Intent intent = new Intent(getApplicationContext(), MainActivity.class)
//add Intent.FLAG_ACTIVITY_CLEAR_TASK flag this will clear all activitys and
//launched activity at top. Means no other activity of this application will be running
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
or
// add Intent.FLAG_ACTIVITY_MULTIPLE_TASK which start one more task your applications
// where activity will not be cleared;
.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification n = new Builder(context.getApplicationContext())
.setContentTitle("simple notification title")
.setContentText("simple message")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.addAction(R.drawable.ic_launcher, "And more",pendingIntent ).build();
NotificationManager notificationManager =(NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, n);