How to clear notification on notification action click? - java

I'm developing an android app where I display notifications with actions. But on action click notification not clearing, It stuck in that shade. How do I clear a notification on action click?
MY CODE
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
PendingIntent openSettingsActivity = PendingIntent.getActivity(this,1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notificationBuilder.addAction(R.drawable.ic_notification_button, "Settings", openSettingsActivity);
notificationBuilder.setPriority(Notification.PRIORITY_MAX);
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(text);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setColor(color);
notificationBuilder.setSmallIcon(R.drawable.ic_notification);
notificationBuilder.setContentIntent(openSettingsActivity);
final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notificationBuilder.build());

Hiding notifications should be processed in the place where the intent is sent.
In your current code:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
Intent intent = new Intent(this, SettingsActivity.class);
intent.putExtra("hide_notification", true); //add boolean to check later in activity if it should remove notification on activity create
And in your activity smth like this, to check if it should remove notification:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check for notification remove
boolean hideNotification = getIntent().getBooleanExtra("hide_notification", false);
if (hideNotification) {
NotificationManagerCompat nmc = NotificationManagerCompat.from(this);
nmc.cancel(1); //1 - is your notification id
}
}
Depends on what you want, maybe it will be better to call that not in onCreate() but onStart()

Related

How to avoid continuous notification when notification is clicked

I want to send notification by BroadcastReceiver. Notification sent by AlarmReceiver but again sent notification when i clicked the notification. The same thing happens again, again and again like endless loop
Here is my AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher);
// This intent is fired when notification is clicked
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0);
// Notifcation notify sound
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Set the intent that will fire when the user taps the notification.
builder.setContentIntent(pendingIntent);
// Large icon appears on the left of the notification
builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
// Content title, which appears in large type at the top of the notification
builder.setContentTitle("Have a good weekend");
//Notification click after clear notification
builder.setAutoCancel(true);
//Set notification sound
builder.setSound(alarmSound);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Will display the notification in the notification bar
notificationManager.notify(1, builder.build());
}
}
and MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAlarm();
}
private void setAlarm(){
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(MainActivity.this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.DAY_OF_WEEK,6);
calendar.set(Calendar.HOUR_OF_DAY,16);
calendar.set(Calendar.MINUTE,53);
calendar.set(Calendar.SECOND,0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
As on click on notification it open MainActivity and in onCreate method of this activity you are calling setAlarm() . So on click of notification onCreate method is invoked then setAlarm() is invoked , this again set Alarm and build notification.
Do following changes
call setAlarm() onClick of a button, so that it is not invoked automatically onCreate of activity.
If you want to send notification automatically
change the intent of notification
Intent i = new Intent(context, MainActivity.class);
As of now you are using intent to open ManinActivity on click of notification.
Change Intent to
Intent i = new Intent(context, OtherActivity.class);
OtherActivity is the activity which does not setAlarm() or build notification in onCreate method.
Alternative Method
Use sharedPreferences to check whether the notification is build once or not.
if build once then don't call setAlarm()

Way to update existing notification?

Hi I want notification to behave as follows :
When there is no single notification from my application, then there should be one created, but when there is already a notification in tray, I want to update data of the notification.
Can I get current notification OR any other way of doing this ?
Also I am having a single type of UI + data for notification which gets triggered frequently on occurrence of particular event.
e.g. In situation where application is getting messages about score of a match after every 5 minute, so current notification should be updated based on last message received, there should not be a notification for every score update message.
My code is as follows :
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Constants.SOME_DATA, someData);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
If you want run your single notification permanetly and update that notification than you have to create foreground notification using startForeground(NOTIFICATION_ID, notification);
And than you can update notification by using same NOTIFICATION_ID in which your is case is 0 /* ID of notification */ or if you want simple notification than update your notification with same NOTIFICATION_ID and keeping FLAG_UPDATE_CURRENT in your pending intent
Set flag .setOngoing(true) and always use the same notification id. in this case is 0. it will update your current notification.
Try this demo
public class MainActivity extends Activity {
private ImageView ImageButton;
int value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton = (ImageView) findViewById(R.id.imageButton);
ImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
value++;
UpdateNow(value + "");
}
});
}
void UpdateNow(String msg) {
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("asd")
.setContentText(msg)
.setSound(defaultSoundUri)
.setOngoing(true)
.setContentIntent(null);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}

Pass an object to another activity in notification builder when clicking a notification

Here there is an activity called grouchat. The messages are sent and received by gcmIntent class. In that class I have the code that issues the notification to the mobile.
In our app more than one event is there for groupchat. If I click the notification, it should take me to the right chat window, so I have passed the eventMO by putExtra parcelable. In the groupchat there is code to get a parcelable
The following is the code in groupchat activity:
eventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(eventMO.getEventId());
The following code is in gcmIntend class to build the notification:
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
//here i have messageMO so i just set the eventid from messageMO to eventMO according to get the eventID in groupchat Activity
EventMO eventMO = new EventMO();
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_dialog_info)
.setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName()))
.setContentText(messageMO.getMessage())
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Log.e("gcm","eventid"+messageMO.getEventId());
mNotificationManager.notify((int) (long) eventMO.getEventId(), mBuilder.build());
If I clicked the notification it throws a null pointer exception, because I get eventMO as null. Please tell me how to pass the current event id in GcmIntent class to groupchat activity.
I use this code in my projects
Notification
Intent intent = new Intent(context.getApplicationContext(), MainActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(context)//
.setContentTitle(title == null ? context.getString(R.string.app_name) : title)//
.setContentText(message)//
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))//
.setSmallIcon(R.drawable.ic_launcher)//
.setContentIntent(pendingIntent)//
.setTicker(context.getString(R.string.app_name))//
.build();
notification.defaults |= Notification.DEFAULT_ALL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(id, notification);
In Activity check intent in onCreate and onNewIntent
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
if (getIntent() != null) {
checkIntent(getIntent());
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntent(intent);
}
private void checkIntent(Intent intent)
{
...
}
You need change getEvent Id to id of notification.
int notification_id = 123;
notificationManager.notify(notification_id, notification);

How to know when user clicks button inside notification

I have a Timer and I send a notification to the user when the timer finishes, I've added a "Stop" button to my notification and when the user clicks it I want the sound of the timer to stop.
What I tried is registering the action to my BroadcastReceiver in my TimerActivity like this:
filter = new IntentFilter();
filter.addAction(TimerService.BROADCAST_ACTION);
registerReceiver(broadcastReceiver, filter);
this is the BroadcastReceiver inside the TimerActivity:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ScheduledService.STOP_TIMER))
{
if(timerAudio.isPlaying())
{
timerAudio.stop();
timerAudio.release();
timerAudio = null;
}
}
};
And this is my how I create the notification inside the ScheduledService class:
Intent notificationIntent = new Intent(getBaseContext(), CookingTimer.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Intent nextIntent = new Intent(STOP_TIMER);
PendingIntent stopTimer = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("This is a sample notification")
.setContentText("Subject")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.addAction(R.drawable.ic_launcher, "Stop", stopTimer).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
I've registered the Service and the action inside my Manifest and I receive the notification correctly, but the button action doesn't work.. Can someone explain me how to fix this?
Post the Activity that has the MediaPlayer controlling the sound.
If you are not receiving Null Pointer Exceptions, I suppose that timerAudio is correct.
However specify if the current view is defined and in context.

press a button and show notification

i have a button in xml when it is clicked following code should show a notification bit its not running giving an error ( Notification.Builder(new View.OnClickListener(){}) is undefined)
anybody tell whats the problem
Mainactivity.Java
package com.example.auto;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b =(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,
0, intent, 0);
Notification mNotification = new Notification.Builder(this)
.setContentTitle("New Post!")
.setContentText("Here's an awesome update for you!")
.setContentIntent(pIntent)
.addAction(0, "View", pIntent)
.addAction(0, "Remind", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotification);
}
});
}
}
Try this one :)
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(getApplicationContext(), MYDEMOACTIVITY.class);
// 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(MYDEMOACTIVITY.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
The constructor needs a Context, and the OnClickListener is no Context.
Change this:
Notification mNotification = new Notification.Builder(this)
to:
Notification mNotification = new Notification.Builder(MainActivity.this)
Notification mNotification = new Notification.Builder(this)
You can't use 'this' as the context because with it you are referencing your new OnClickListener, not your Activity.
To get the enclosing Activity's context you have to use MainActivity.this:
Notification mNotification = new Notification.Builder(MainActivity.this)

Categories

Resources