Actually I have two questions regarding notification implementation I am trying to achieve in my application:
1. Notification opening automatically : I am trying to notify on the phone during an event in my application. The notification is functioning correctly in the way that when the event is fired, the intent which I have set in the notification gets called and the screen which I need to display is shown. However the notification comes on status bar for a second and then disappears. My application which was in background automatically comes in foreground because of the notification. I don't want the application to come on foreground automatically. I just need to display the notification.
2. Displaying notification on locked screen : With the following code, I am not able to display notification on locked screen.
This is the code I have used to display the notification :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle("Trip Alert");
mBuilder.setContentText(StringUtils.join("You have reached ",destination.getAddress()));
mBuilder.setNumber(++numMessages);
mBuilder.setOnlyAlertOnce(true);
mBuilder.getNotification().flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT;
Intent detailIntent = new Intent();
detailIntent.setClass(DestinationListActivity.this,
DestinationDetailActivity.class);
detailIntent.putExtra("Destination", destination);
startActivityForResult(detailIntent, 1);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(DestinationDetailActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(detailIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());
The reason notification is getting displayed for a very little time is because I have written following code in the DestinationDetailsActivity onCreate :
if (getIntent().getExtras() != null) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(100);
..
}
But if this code won't come here, how shall I dismiss the notification?
Please do let me know if I need to explain more.
Related
In the android, FCM notification comes and app is in the background state and when tapped, it redirects to Default Activity (LoginActivity) but I want to navigate to specified activity (HomeActivity).
NotificationCompat.Builder notification = new NotificationCompat.Builder(this, "CHANNEL_1");
notification/*.setSound(soundUri)*/
.setSmallIcon(R.drawable.ic_photo_camera_black_24dp)
.setColor(getResources().getColor(R.color.colorAccent))
.setAutoCancel(true)
.setContentTitle(title)
.setContentText(message);
Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
0);
notification.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification.build());
you will need to pass an activity parameter from the api/json part. from your app side you will check for the activity nave and than open accordingly
see this solution https://stackoverflow.com/a/39665485/6442746 for more insights.
You should send a format is Data Message to handle notification in onMessageReceived when the app is background or foreground
When received data in onMessageReceived(), you can show notification and direct to your activity.
My application is running as a service so, I need to notify the user as application is running. I am trying to add a notification on the notification bar. Since it is a service application I need to always show the notification.
How can I prevent the user to remove the notification even when the application is quit.
I able to prevent the user to remove the application on swipe by using,
mBuilder.setOngoing(true);
How to show the notification even the application quit.
I have used the below code ,
private void addNotificaiononNotificationBar(){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setOngoing(true);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
If you want to restrict removing notification you can create Foreground Service so notification will exist when service is running.
In Android How to Restart App On Click Application "onGoing" Notification. if App is open or not.
Like As When i Click on onGoing Notification "Connected as a Media device"
You can define actions you want to happen when interacting with your Notification by adding a PendingIntent.
In the following example a PendingIntent is created to launch the (current) activity.
That intent is then added to the notification in the content section. Once this notification is shown, when you click the content section, the intent is fired and the app gets started or brought back to top.
private static final int NOTIFICATION_ID = 1;
...
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP),
0);
nb.setSmallIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(getText(R.string.app_name))
.setContentText("Click to launch!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent) // Here the "onClick" Intent is added
.setOngoing(false);
nm.notify(NOTIFICATION_ID, nb.build());
In this case the notification is dismissable. If you set .setOngoing(true) you need to remove it by calling .cancel(NOTIFICATION_ID) on an instance of the NotificationManager.
See also this introduction on how to Build a Notification.
Is it possible not launch new activity if we receive a push notification while the app is running?
My activity works with fragments and I want to do transition to a determinate fragment when the notification is received. My activity have data that I need to show the fragments. The problem is that when I receive the push notification while the app is running the method onDestroy is called and here I clear the data and then the app crash because the data are null. How can I do to not create new activity when the app receive a push notification while is running? In case the app is running I want that if you click the notification do a transition fragment, not create again the activity.
Thanks in advance.
First of all, I think that you mean "notification" to be a "message", but not android.app.Notification class.
And second, I don't think it's a best practise to raise new GUI when receiving a message, which would interrupt the user interaction. For details, please refer to: http://developer.android.com/training/notify-user/index.html and http://developer.android.com/design/patterns/notifications.html.
At last, if you really wanna do what you stated in your thread, I wonder why the data used to generate the show-data fragment is held in the activity. Try holding the data in an android.app.IntentService object, and then generate transfer the data to new activity, and then use android.app.Fragment.setArguments method to transfer the data from activity to fragment.
I think that this code will help you. This which you need is PendingIntent, it make transaction to desired activity.
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String title,
String message) {
//get the default notification sound URI
Uri uriNotificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//make intent to the application. if the application is opened just maximize it.
Intent homeIntent = new Intent(context, 'your desired activity');
homeIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
homeIntent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("eCommCongress")
.setContentText(message)
.setLights(Color.GREEN, 1500, 1500)
.setSound(uriNotificationSound)
.setAutoCancel(true)
.setContentIntent(contentIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(counter, mBuilder.build());
counter++;
}
It is perfectly possible and I do such a thing in one of my apps. First, you need to declare your activity as android:launchMode="singleTop",
Then, when you build you must configure your pending intent not to fire a new instance of your activity:
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent("YOUR ACTION HERE");
intent.setClassName(this, MainActivity.class.getName());
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.defaults |= Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;
notification.flags |= Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(idNotificacion,notification);
Now all you have to do is to override your onNewIntent inside your Activity and do whatever you want with your fragment:
#Override
protected void onNewIntent(Intent intent) {
MiLog.i(getApplicationContext(),"IntentShit","new intent received");
MiLog.i(getApplicationContext(),"IntentShit","Action: "+intent.getAction());
if(intent.getAction()!=null && intent.getAction().equals("YOUR ACTION HERE"){
//DO your stuff here
}
}
You should also take a look at this page for more info:
http://www.intridea.com/blog/2011/6/16/android-understanding-activity-launchmode
I am trying to Notify user based on some criteria. Multiple Notifications are being shown in Status Bar but I want to Group the notification in single notification and when user clicks in the Status Bar, I want to retrieve all notifications in that group. Is that possible? Or I have to maintain PendingIntents of those notifications? Any help will be appreciated. For example, if birthdays of two friends come on same day, then 2 notifications should be shown. I want to combine these notifications i.e. instead of 2 notifications in the status bar, I want one, when user clicks on it, it should have information about 2 notifications. Is it possible?
Please see the code below for displaying notifications.
public void displayNotification(BirthdayDetail detail)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(detail.getContactName());
builder.setContentText(detail.getContactBirthDate());
Intent resultIntent = new Intent(this.context, NotificationView.class);
resultIntent.putExtra("name", detail.getContactName());
resultIntent.putExtra("birthdate", detail.getContactBDate());
resultIntent.putExtra("picture_path", detail.getPicturePath());
resultIntent.putExtra("isContact", detail.isFromContact());
resultIntent.putExtra("notificationId", notificationId);
if(detail.isFromContact())
{
resultIntent.putExtra("phone_number", detail.getPhoneNumber());
}
PendingIntent resultPendingIntent = PendingIntent.getActivity(this.context, requestCode++,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager
= (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
notificationId++;
}
When you need to issue a notification multiple times for the same type
of event, you should avoid making a completely new notification.
Instead, you should consider updating a previous notification, either
by changing some of its values or by adding to it, or both.
You can use something like:
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
Source: http://developer.android.com/training/notify-user/managing.html