I want to auto cancel my notification when user clicks on notification. The following code works good in all the devices except Android lollipop device. In Lollipop device, notification goes only when user swipes it off.
#SuppressWarnings("deprecation")
public void sendNotification(int id){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Test")
.setContentText("Jump to next screen")
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
resultIntent, 0);
//PendingIntent.FLAG_UPDATE_CURRENT
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// id, if there is a need to update the notification later on.
mNotificationManager.notify(id, mBuilder.build());
Log.v(TAG, "Notification ID value " + id);
//mNotificationManager.cancel(id);
}
What is missing in this code?
Looks good to me. My auto cancel still works on 5.0.2. Let me give you a portion of my code:
public static void notif(int id, String title, String text, Context context, Class activity) {
// get an instance of the NotificationManager service
if (mNotifyMgr == null)
mNotifyMgr = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, activity);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent notifIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.launcher)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(notifIntent);
mNotifyMgr.notify(id, mBuilder.build());
}
modify following:
setAutoCancel(true) -> setAutoCancel(false);
then on action activity do the following
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
if you want to set special condition you can set by
intent.putExtra("key", "value")
Related
I just started working with notifications and now I'm trying to remove the notification and launch the app once the notification has been tapped in the notificationcenter.
I tried to work with the following code:
import android.app.NotificationManager;
public class ExpandNotification {
private int NOTIFICATION = 546;
private NotificationManager mNM;
public void onCreate() {
mNM.cancel(NOTIFICATION);
setContentView(R.layout.activity_on);
//Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
I think this code executes the other class when tapped?
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, ExpandNotification.class), 0);
However the notification doesn't go away, nor does the application launch.
But I'm able to swipe it to left or right to remove it but that's not what I want..
To get the same effect using Notification.Builder or NotificationCompat.Builder call setAutoCancel(true) on the Builder instance.
Use the flag Notification.FLAG_AUTO_CANCEL
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent);
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
and to launch the app:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Create a new intent which will be fired if you click on the notification
Intent intent = new Intent(context, App.class);
// Attach the intent to a pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, intent_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
This answer is too much late but specially i write following solution because notification constructor become deprecated so use notification using builder , like following :
**.setAutoCancel(true)** is used to remove notification on click
and entire notification is like follwoing :
private void makeNotification(String title,String msg){
Intent resultIntent = new Intent(this, MasterActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentIntent(resultPendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setAutoCancel(true)
.setContentText(msg);
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
Calling this method with title and message you get perfect notification.
You can directly add .setAutoCancel(true) this line into your code in order to remove notification on click.
This must be added in your builder variable.
Example:
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Notification")
.setContentText("Hello")
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Best & simple way is set builder.setAutoCancel(true) it's cancel your notification after clicking on notification. I hope this code help you.
Builder for notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
For open an activity on clicking notification
Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
Show bulder in notification
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());
Complete code for show a notification with icon, image, title, description, auto cancel and on click open an activity
public void ShowIntentNotification(View v)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());
}
For my it was that
.setPriority(Notification.PRIORITY_HIGH);
that was causing the notification to not clear after click... make sure you use:
.setPriority(Notification.PRIORITY_DEFAULT);
And .setAutoCancel(true) should work.
i have set up my own push notification server to send notification to android devices.
I have handled the notification so on click it always open my custom activity whatever the app was in background or foreground.
The working part : When sending two separated notifications that means when the first notification is received i click on it so the activity is launched that's ok.
I re-send another notification so also when i click on it all goes well and the activity is relauched.Perfect!
The NOT working part : When sending two successive notifications the problem occurs.
When two notifications are received ..i open the first one the activity is launched but when i click on the second one nothing happens !!.
So i think it might be a solution in changing the Intent FLAG or Pending Intent.
I have searched for solutions but all were about handling the notification when app is in foreground or background which is not in my case.
This is my working code:
Intent i = new Intent(this, News_description.class);
i.putExtra("title", title);
i.putExtra("message", message);
i.putExtra("image", image);
i.putExtra("time", time);
i.putExtra("date", date);
i.putExtra("click_action", click_action);
i.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,PendingIntent.FLAG_ONE_SHOT
);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[]{status, status})
.setContentTitle(getString(R.string.app_name))
.setContentText(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(title))
.setSmallIcon(R.mipmap.ahed_me)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int id = (int) System.currentTimeMillis();
manager.notify(id, builder.build());
} catch (Exception e) {
e.printStackTrace();
}
I can provide any further information.
I have the Flag FLAG_ACTIVITY_CLEAR_TASK and it works on my app.
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Here my full code, it works perfect for me:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent =
PendingIntent.getActivity(getApplicationContext(), 0,
i, 0);
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.alarm)
.setAutoCancel(true)
.setContentTitle(title)
.setPriority(Notification.PRIORITY_MAX)
.setVibrate(vibrate)
.setLights(Color.BLUE, 3000, 1500)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(body))
.setContentIntent(contentIntent)
.setContentText(body);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int Unique_Integer_Numbe = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
mNotificationManager.notify(Unique_Integer_Numbe, mBuilder.build());
UPDATED:
public SomePushNotificationClass {
private static int NOTIFICATION_ID = 1;
String previousMessageID = "null";
#Override
public void onReceive(Bundle data) {
String messageID = data.getString("message_id");
if (!messageID.equals(previousMessageID) && !messageID.isEmpty()) {
previousMessageID = messageID;
NotificationManager notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent it = new Intent(this, SomeActivity.class);
it.putExtra("key_example_1", someValue);
it.putExtra("key_example_2", someValue2);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.some_drawable);
notificationBuilder.setLargeIcon(someIcon);
notificationBuilder.setContentTitle(someTitle);
notificationBuilder.setStyle(new
// Optional
NotificationCompat.BigTextStyle().bigText(someText));
notificationBuilder.setContentText(someText);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationManager.notify(NOTIFICATION_ID,
notificationBuilder.build());
NOTIFICATION_ID++;
}
}
}
This is what you need:
Intent it = new Intent(this, SomeActivity.class);
it.putExtra("key_example_1", someValue);
it.putExtra("key_example_2", someValue2);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
I have an application that receive PUSH notifications. When notification "not1" is received, it shows as usual using notification manager. But when "not2" is received, is not showing below "not1" but overriding it. I need show all notifications.
I thought that using different requestCode for PendingIntent will solve the problem, but not. I also tried with PendingIntent.FLAG_UPDATE_CURRENT flag and many others (including no flags). My code right now is like this:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = null;
Notification notification = null;
Intent notificationIntent = new Intent(context.getApplicationContext(), SplashActivity.class);
notificationIntent.putExtra("text", text);
notificationIntent.putExtra("url", url);
PendingIntent intent = PendingIntent.getActivity(context, requestID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder = setBuilderNormalNotification(builder, context, text, intent);
notification = new NotificationCompat.BigTextStyle(builder).bigText(text).build();
notificationManager.notify(0, notification);
Where function setBuilderNormalNotification is the next:
private static NotificationCompat.Builder setBuilderNormalNotification(NotificationCompat.Builder builder, Context context, String text, PendingIntent intent)
{
builder
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(getNotificationIcon())
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), getNotificationIcon()))
.setContentText(text)
.setContentIntent(intent)
.setWhen(0)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setAutoCancel(true);
return builder;
}
What Am I doing wrong, please?
Thanks a lot.
In your code notificationManager.notify(0, notification); That 0 is the constant ID you are using, since it is always the same the notifications stack.
I have prepared a simple test app which posts a notification on a button click:
The source code from MainActivity.java creating the notification is displayed below:
Button showButton = (Button) findViewById(R.id.show);
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
appIntent.putExtra("my_data", 12345);
String question = getString(R.string.the_question);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(mContext)
.setContentTitle(question)
.setContentText(question)
.setTicker(question)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
mManager.notify(NOTIFY_ID, notification);
}
});
My question is: how to modify the notification, so that the user is asked a Yes/No question (in this case: "Do you want to open the car?") and - after she selects Yes or No to launch the same app and run a corresponding method in it (in this case: openCar() or closeCar() method).
I probably should use NotificationCompat.Action.Builder - but how exactly?
Also I am not really sure if this code is the correct code for launching an app from notification and what flags should I use:
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
And finally I wonder if hardcodidng some random number in NOTIFY_ID is the correct way when posting notifications?
Here is a source code I used for notification with Login/Register action.
private void sendNotification(String message, String title) {
try {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Intent secondActivityIntent = new Intent(this, SecondActivity.class);
PendingIntent secondActivityPendingIntent = PendingIntent.getActivity(this, 0 , secondActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Intent thirdActivityIntent = new Intent(this, ThridActivity.class);
PendingIntent thirdActivityPendingIntent = PendingIntent.getActivity(this, 0 , thirdActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_3d_rotation_white_36dp)
.setContentTitle(title)
.setContentText(message)
.addAction(R.drawable.ic_lock_open_cyan_600_24dp,"Login",secondActivityPendingIntent)
.addAction(R.drawable.ic_lock_pink_700_24dp,"Register",thirdActivityPendingIntent)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
To use it: simply call this method sendNotification(String yourMessage, String yourTitle)
e.g. sendNotification("Hello Message", "Hello Title")
Here is a snapshot of the output
Notify user on pending Intent.. an example is here..
public void notifyUser() {
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(HappyActivity.this, NotificationDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// use the flag FLAG_UPDATE_CURRENT to override any notification already
// there
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.ic_launcher,
"Question.....?????", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "title",
"Explanation of question..", pendingIntent);
// 10 is a random number I chose to act as the id for this notification
notificationManager.notify(10, notification);
}
I just started working with notifications and now I'm trying to remove the notification and launch the app once the notification has been tapped in the notificationcenter.
I tried to work with the following code:
import android.app.NotificationManager;
public class ExpandNotification {
private int NOTIFICATION = 546;
private NotificationManager mNM;
public void onCreate() {
mNM.cancel(NOTIFICATION);
setContentView(R.layout.activity_on);
//Toast.makeText(this, "stopped service", Toast.LENGTH_SHORT).show();
}
I think this code executes the other class when tapped?
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, ExpandNotification.class), 0);
However the notification doesn't go away, nor does the application launch.
But I'm able to swipe it to left or right to remove it but that's not what I want..
To get the same effect using Notification.Builder or NotificationCompat.Builder call setAutoCancel(true) on the Builder instance.
Use the flag Notification.FLAG_AUTO_CANCEL
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent);
// Cancel the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
and to launch the app:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Create a new intent which will be fired if you click on the notification
Intent intent = new Intent(context, App.class);
// Attach the intent to a pending intent
PendingIntent pendingIntent = PendingIntent.getActivity(context, intent_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
This answer is too much late but specially i write following solution because notification constructor become deprecated so use notification using builder , like following :
**.setAutoCancel(true)** is used to remove notification on click
and entire notification is like follwoing :
private void makeNotification(String title,String msg){
Intent resultIntent = new Intent(this, MasterActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setContentIntent(resultPendingIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setAutoCancel(true)
.setContentText(msg);
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
Calling this method with title and message you get perfect notification.
You can directly add .setAutoCancel(true) this line into your code in order to remove notification on click.
This must be added in your builder variable.
Example:
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("Notification")
.setContentText("Hello")
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
Best & simple way is set builder.setAutoCancel(true) it's cancel your notification after clicking on notification. I hope this code help you.
Builder for notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
For open an activity on clicking notification
Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
Show bulder in notification
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());
Complete code for show a notification with icon, image, title, description, auto cancel and on click open an activity
public void ShowIntentNotification(View v)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(android.R.drawable.btn_star);
builder.setContentTitle("This is title of notification");
builder.setContentText("This is a notification Text");
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
Intent intent = new Intent(Broadcastdemo.this, ThreadDemo.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 113,intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(114, builder.build());
}
For my it was that
.setPriority(Notification.PRIORITY_HIGH);
that was causing the notification to not clear after click... make sure you use:
.setPriority(Notification.PRIORITY_DEFAULT);
And .setAutoCancel(true) should work.