Trying to figure out why my onGoing notification disappears when the user presses on the pause button. I am trying to implement a media player controls scheme similar to that of the Spotify ongoing notification. I am modifying Androids Sample project "RandomMusicPlayer". I have tried setting setAutoCancel to false.
Related code listed below:
/** Updates the notification. */
#SuppressWarnings("deprecation")
private void updateNotification(String text, String artist, boolean showticker) {
Notification notification = buildNotification(text, artist, showticker);
if(notification!=null){
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
}
/**
* Configures service as a foreground service. A foreground service is a service that's doing
* something the user is actively aware of (such as playing music), and must appear to the
* user as a notification. That's why we create the notification here.
*/
#SuppressWarnings("deprecation")
private void setUpAsForeground(String text, String artist, boolean showticker) {
Notification notification = buildNotification(text, artist, showticker);
if(notification != null){
startForeground(NOTIFICATION_ID, notification);
}
}
/**
* Called when we want to build our notification
*/
private Notification buildNotification(String title, String artist, boolean showticker){
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
new Intent(getApplicationContext(), HomeActivity.class).setAction(ACTION_OPEN_STREAM_FRAG),
PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingStopIntent = PendingIntent.getService(this, 118, new Intent(MusicService.ACTION_STOP), PendingIntent.FLAG_NO_CREATE);
PendingIntent pendingPauseIntent = PendingIntent.getService(this, 119, new Intent(MusicService.ACTION_PAUSE), PendingIntent.FLAG_NO_CREATE);
PendingIntent pendingPlayIntent = PendingIntent.getService(this, 120, new Intent(MusicService.ACTION_PLAY), PendingIntent.FLAG_NO_CREATE);
RemoteViews mNotificationView = new RemoteViews(getPackageName(),
R.layout.player_notification_view);
Notification mNotification = null;
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this);
mNotificationView.setImageViewResource(R.id.imageNotification, R.drawable.ic_launcher );
mNotificationView.setTextViewText(R.id.titleNotification, title);
mNotificationView.setTextColor(R.id.titleNotification, Color.WHITE);
mNotificationView.setTextViewText(R.id.textNotification, artist);
if(mState == State.Playing){
mNotificationView.setImageViewResource(R.id.control_one_button_notification, R.drawable.ic_action_playback_pause);
mNotificationView.setImageViewResource(R.id.control_two_button_notification, R.drawable.ic_action_playback_stop);
mNotificationView.setOnClickPendingIntent(R.id.control_one_button_notification, pendingPauseIntent);
mNotificationView.setOnClickPendingIntent(R.id.control_two_button_notification, pendingStopIntent);
}else if(mState == State.Paused){
mNotificationView.setImageViewResource(R.id.control_one_button_notification, R.drawable.ic_action_playback_play);
mNotificationView.setImageViewResource(R.id.control_two_button_notification, R.drawable.ic_action_playback_stop);
mNotificationView.setOnClickPendingIntent(R.id.control_one_button_notification, pendingPlayIntent);
mNotificationView.setOnClickPendingIntent(R.id.control_two_button_notification, pendingStopIntent);
}
builder.setContentIntent(pi).setSmallIcon(R.drawable.ic_launcher);
if(showticker){
builder.setTicker(title);
}else{
builder.setTicker(null);
}
builder.setAutoCancel(false).setContent(mNotificationView).setOngoing(true);
mNotification = builder.build();
return mNotification;
}
Not sure if you do but you should implement this in a Service, and there you should use:
startForeground(NOTIFICATION_ID, mNotification);
I have made an app that does just this, please have a look at how I solved it here: https://github.com/slidese/SGU
Specifically, look at this class: https://github.com/slidese/SGU/blob/master/src/se/slide/sgu/AudioPlayer.java
Just write a code in your function of pendingIntent
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(01);
//"01" is the id of your notification
or refer to link
How to stop a notification
Related
I am using the code of PingService.java https://github.com/android/platform_development/blob/master/samples/training/notify-user/src/com/example/android/pingme/PingService.java
PingService.Java
/**
* PingService creates a notification that includes 2 buttons: one to snooze the
* notification, and one to dismiss it.
*/
public class PingService extends IntentService {
private NotificationManager mNotificationManager;
private String mMessage;
private int mMillis;
NotificationCompat.Builder builder;
public PingService() {
// The super call is required. The background thread that IntentService
// starts is labeled with the string argument you pass.
super("com.example.android.pingme");
}
#Override
protected void onHandleIntent(Intent intent) {
// The reminder message the user set.
mMessage = intent.getStringExtra(CommonConstants.EXTRA_MESSAGE);
// The timer duration the user set. The default is 10 seconds.
mMillis = intent.getIntExtra(CommonConstants.EXTRA_TIMER,
CommonConstants.DEFAULT_TIMER_DURATION);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
String action = intent.getAction();
// This section handles the 3 possible actions:
// ping, snooze, and dismiss.
if(action.equals(CommonConstants.ACTION_PING)) {
issueNotification(intent, mMessage);
} else if (action.equals(CommonConstants.ACTION_SNOOZE)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.snoozing));
// Sets a snooze-specific "done snoozing" message.
issueNotification(intent, getString(R.string.done_snoozing));
} else if (action.equals(CommonConstants.ACTION_DISMISS)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
}
private void issueNotification(Intent intent, String msg) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Sets up the Snooze and Dismiss action buttons that will appear in the
// expanded view of the notification.
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Constructs the Builder object.
builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
/*
* Sets the big view "big text" style and supplies the
* text (the user's reminder message) that will be displayed
* in the detail area of the expanded notification.
* These calls are ignored by the support library for
* pre-4.1 devices.
*/
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.addAction (R.drawable.ic_stat_dismiss,
getString(R.string.dismiss), piDismiss)
.addAction (R.drawable.ic_stat_snooze,
getString(R.string.snooze), piSnooze);
/*
* Clicking the notification itself displays ResultActivity, which provides
* UI for snoozing or dismissing the notification.
* This is available through either the normal view or big view.
*/
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// 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
);
builder.setContentIntent(resultPendingIntent);
startTimer(mMillis);
}
private void issueNotification(NotificationCompat.Builder builder) {
mNotificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Including the notification ID allows you to update the notification later on.
mNotificationManager.notify(CommonConstants.NOTIFICATION_ID, builder.build());
}
private void startTimer(int millis) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_start));
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.sleep_error));
}
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_finished));
issueNotification(builder);
}
}
Intent mServiceIntent = new Intent(context.getApplicationContext(), PingService.class);
mServiceIntent.putExtra(Const.EXTRA_MESSAGE, "" + msg);
mServiceIntent.putExtra(Const.ID, reminder_id);
startService(mServiceIntent);
And passing the data to issueNotification method for Action Button intent like
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
dismissIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
snoozeIntent.putExtra(CommonConstants.ID, reminder_id);
PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
But i am not getting the ID at the time of Click event of the Action button from issueNotification and passing the intent in onHandleIntent method
It is automatically set to 1 after Notification generation and i am not able to cancel that notification due to wrong notification id set into putExtra of PendingIntent
I am trying with passing different flag like
PendingIntent piDismiss = PendingIntent.getService(this, 0, taken_intent, PendingIntent.FLAG_UPDATE_CURRENT);
Please help me out i am trying it since long time but not getting the correct id.
My putExtra is override with 1 somehow....
Thank you in advnace
After so much reasearching finally got a solution that i need to pass different code in pending intent like
PendingIntent piDismiss = PendingIntent.getBroadcast(this, CommonConstants.NOTIFICATION_ID, dismissIntent, 0);
which is dynamic one and unique one in each Action Button case.
Use Broadcast receiver to achieve this instead of Service ( getBroadcast ).
Thank you.
Notification setAutoCancel(true) doesn't work if clicking on Action
I have a notification with an action within it. When I tap on the notification it gets removed from the list. However, when I click on the Action it successfully completes the Action (namely makes a call), but when I return to the list of notifications, it remains there.
Relative code of the AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
Meeting meeting;
/**
* Handle received notifications about meetings that are going to start
*/
#Override
public void onReceive(Context context, Intent intent) {
// Get extras from the notification intent
Bundle extras = intent.getExtras();
this.meeting = extras.getParcelable("MeetingParcel");
// build notification pending intent to go to the details page when click on the body of the notification
Intent notificationIntent = new Intent(context, MeetingDetails.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("MeetingParcel", meeting); // send meeting that we received to the MeetingDetails class
notificationIntent.putExtra("notificationIntent", true); // flag to know where the details screen is opening from
PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
// build intents for the call now button
Intent phoneCall = Call._callIntent(meeting);
if (phoneCall != null) {
PendingIntent phoneCallIntent = PendingIntent.getActivity(context, 0, phoneCall, PendingIntent.FLAG_CANCEL_CURRENT);
int flags = Notification.FLAG_AUTO_CANCEL;
// build notification object
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Call In")
.setContentText(intent.getStringExtra("contextText"))
.setTicker("Call In Notification")
.setColor(ContextCompat.getColor(context, R.color.colorBluePrimary))
.setAutoCancel(true) // will remove notification from the status bar once is clicked
.setDefaults(Notification.DEFAULT_ALL) // Default vibration, default sound, default LED: requires VIBRATE permission
.setSmallIcon(R.drawable.icon_notifications)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(meeting.description))
.addAction(R.drawable.icon_device, "Call Now", phoneCallIntent)
.setCategory(Notification.CATEGORY_EVENT) // handle notification as a calendar event
.setPriority(Notification.PRIORITY_HIGH) // this will show the notification floating. Priority is high because it is a time sensitive notification
.setContentIntent(pIntent).build();
notification.flags = flags;
// tell the notification manager to notify the user with our custom notification
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
}
}
use this flag:
Notification.FLAG_AUTO_CANCEL
inside this:
int flags = Notification.FLAG_AUTO_CANCEL;
Notification notification = builder.build();
notification.flags = flags;
Documentation
Ok turns out it's a known problem already, and it needs extra code to be done (keeping reference to notification through id). Have no clue why API does not provide this, as it seems very logical to do. But anyways,
see this answer in stackoverflow:
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
I faced this problem today, and found that FLAG_AUTO_CANCEL and setAutoCanel(true), both work when click on notification,
but not work for action click
so simply, in the target service or activity of action, cancel the notification
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancelAll();
or if have more notification
manager.cancel(notificationId);
You have created two pending intent use in boths and change Flag too.
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, 0);
PendingIntent phoneCallIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), phoneCall, PendingIntent.FLAG_UPDATE_CURRENT);
// CHANGE TO THIS LINE
PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
PendingIntent phoneCallIntent = PendingIntent.getActivity(context, 0, phoneCall, PendingIntent.FLAG_CANCEL_CURRENT);
In my application I want show a notification in some cases.
When notification is active I do not want to create notification again.
I have activity recognition in my app and when it's detected that I am in car it starts to sound notification every second.
How could I prevent a new build notification if there is at least one active notification there?
Here is my code what I tried:
Intent closeIntent;
Intent showIntent;
if (isStart){
closeIntent = new Intent(this, SwitchButtonListener1.class);
} else {
closeIntent = new Intent(this, SwitchButtonListener2.class);
}
closeIntent.setAction("No");
PendingIntent pendingIntentClose = PendingIntent.getBroadcast(this, 0,
closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action closeAction = new NotificationCompat.Action(R.drawable.btn_close_gray, "No", pendingIntentClose);
if (isStart){
showIntent = new Intent(this, SwitchButtonListener1.class);
} else {
showIntent = new Intent(this, SwitchButtonListener2.class);
}
showIntent.setAction("Yes");
PendingIntent pendingIntentShow = PendingIntent.getBroadcast(this, 0,
showIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action showAction = new NotificationCompat.Action(R.drawable.ic_tick, "Yes", pendingIntentShow);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_stat_milebox)
.setContentTitle(title)
.setContentText(message)
.addAction(showAction)
.addAction(closeAction);
builder.setSound(alarmSound);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(100, builder.build());
Though it is an old question, but I think this answer might help others in the future:
In a case like this, when the user needs to be notified only once and the event is ongoing then using .setOnlyAlertOnce(true) and setOngoing(true) with the builder will solve the problem.
Documentation:
setOnlyAlertOnce(true): Set this flag if you would only like the sound, vibrate and ticker to be played if the notification is not already showing.
setOngoing(true): Set whether this is an ongoing notification. Ongoing notifications cannot be dismissed by the user, so your application or service must take care of canceling them. They are typically used to indicate a background task that the user is actively engaged with (e.g., playing music) or is pending in some way and therefore occupying the device (e.g., a file download, sync operation, active network connection).
Notification notification = new NotificationCompat.Builder(this, notificationChannel.getId())
.....
.....
.setOngoing(true)
.setOnlyAlertOnce(true)
.....
.....
.build();
Objects.requireNonNull(notificationManager).notify(notificationId, notification);
You can try the following as a sketch:
public class MediaNotificationManager extends BroadcastReceiver {
private final NotificationManager mNotificationManager;
private Context ctx;
private boolean mStarted = false;
public MediaNotificationManager(Context ctx) {
mCtx = ctx;
mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
// Cancel all notifications to handle the case where the Service was killed and
// restarted by the system.
mNotificationManager.cancelAll();
}
/**
* Posts the notification and starts tracking the session to keep it
* updated. The notification will automatically be removed if the session is
* destroyed before {#link #stopNotification} is called.
*/
public void startNotification() {
if (!mStarted) {
// The notification must be updated after setting started to true
Notification notification = createNotification();
if (notification != null) {
mStarted = true;
}
}
}
/**
* Removes the notification and stops tracking the session. If the session
* was destroyed this has no effect.
*/
public void stopNotification() {
if (mStarted) {
mStarted = false;
try {
mNotificationManager.cancel(NOTIFICATION_ID);
} catch (IllegalArgumentException ex) {
// ignore if the receiver is not registered.
}
}
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
LogHelper.d(TAG, "Received intent with action " + action);
switch (action) {
//do something with this.
}
}
private Notification createNotification() {
//create and return the notification
}
}
For a bit more read this:
I also used this notification in my code:
https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/src/main/java/com/example/android/uamp/MediaNotificationManager.java
I have a share option in the notification tray. So, I have used 2 custom views in my code.
1. Expandable Notification Layout
2. Normal Notification Layout
The UI is working fine. But, notifications are misbehaving. If I click the first notification or share first item in the notification, it works perfectly. But, If I click the last notification, then it opens the app but notification is not cleared from the notification tray. Also, the strange thing is, after clicking the notification,small icon which comes in the status bar disappears and now if i click the notification, it doesn't respond. I'm cancelling the notification. That's why second time, when i click it doesn't work. This was not happening when I used default builder layout for normal view.
Here is my code:
//setup a expanded notification layout
RemoteViews expandedView=new RemoteViews(context.getPackageName(), R.layout.custom_notification);
expandedView.setImageViewResource(R.id.image_logo, R.drawable.ic_launcher);
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa");
String time = dateFormat.format(new Date(when));
expandedView.setTextViewText(R.id.current_time, time);
expandedView.setTextViewText(R.id.title, context.getResources().getString(R.string.app_name));
expandedView.setTextViewText(R.id.text, message);
expandedView.setTextViewCompoundDrawables(R.id.share, R.drawable.gcm_share, 0, 0, 0);
//set a normal notification layout
RemoteViews collapsedView=new RemoteViews(context.getPackageName(), R.layout.custom_notification_normal_layout);
collapsedView.setTextViewText(R.id.text, message);
notificationId = ((int) System.currentTimeMillis() % 1000000);
//register listenr for Share Icon
setBtnListeners(expandedView, requestID, message, context, notificationId);
`Bitmap largeIcon = ((BitmapDrawable) context.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap()`;
//Construct notification Builder
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(context);
mNotifyBuilder
.setWhen(when)
.setSmallIcon(icon)
.setLargeIcon(largeIcon)
.setContentTitle(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
notification = mNotifyBuilder.build();
//assign the vies to the notification builder
notification.bigContentView = expandedView;
notification.contentView = collapsedView;
//create pending Intent
Intent notificationIntent;
//notificationIntent = new Intent(context, Launcher.class);
notificationIntent = new Intent(context, SplashActivity.class);//Sritapana189
notificationIntent.putExtra(BundleKeys.NORMAL_PUSH, 1);
notificationIntent.putExtra(BundleKeys.DEFAULT_NOTI_NAV, nav);
notificationIntent.putExtra(BundleKeys.FROM_GCM, true);
notificationIntent.putExtra(ApplicationConstants.GCMKeys.GCM_NOTIFICATION_ID, notificationId);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID, notificationIntent, 0); //Modified
notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationId, notification);
//Registering the share icon of notification tray
private static void setBtnListeners(RemoteViews notificationView, int requestId, String message, Context context, int notificationId) {
Intent shareBtnIntent = new Intent(context, GcmTransparentActivity.class);
shareBtnIntent.putExtra(ApplicationConstants.GCMKeys.BREAKING_NEWS, message);
shareBtnIntent.putExtra(ApplicationConstants.GCMKeys.GCM_NOTIFICATION_ID, notificationId);
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestId, shareBtnIntent, 0);
notificationView.setOnClickPendingIntent(R.id.share, pendingIntent);
}
//SplashActivity recieving Pending Inent
//here I'm retrieving the payload data and saving it and then cancelling the notification
Utility.cancelNotification(gcmNotificationId, getApplicationContext());
public static void cancelNotification(int id, Context ctx) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(id);
}
The only change i did in my code is I added custom layout for the normal view.After this change, it's misbehaving when last notification item is clicked. Is there anything I'm missing. please help me to sort out this strange issue.
try this,
problem may be because you are not getting the notification id properly
quick fix can be,
Notification nNotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancel(id);
replace this with ,
Notification nNotificationManager nMgr = (NotificationManager) ctx.getSystemService(ns);
nMgr.cancelAll();
I resolved my issue. The problem was with the RemoteViews. I had made them local and making them final solved my issue
final RemoteViews expandedView=new RemoteViews(context.getPackageName(), R.layout.custom_notification);
final RemoteViews collapsedView=new RemoteViews(context.getPackageName(), R.layout.custom_notification_normal_layout)
from my service I send (with "ongoing" ID = 0) ongoing notification and it seems that there is no way of clearing it from code. if I send other notifications to the same ID (0), icon and intents
will update :/
I dont know if this is a bug in API 7 but it just dont make sens to me.
when I sent notification with Notification.FLAG_ONLY_ALERT_ONCE with different ID(ex. 1) then it is classified as simple notification and I could easily clear it from expanded menu or from code. BUT just by sending same notification to previous ID (0) it is classified as ongoing and I cannot cancel it anyhow!
I also tried to save reference to "ongoing" notification and then re-notify it with other PendingIntent and/or flags but it has no effect!
my current code of the service
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "start notification");
startStatusBarNotification();
//do other stuff
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
private void startStatusBarNotification()
{
Log.d(TAG, "startStatusBarNotification.");
final int icon = R.drawable.stbar_icon_fail;
final long when = System.currentTimeMillis();
final Notification notification = new Notification(icon, getString(R.string.notify_title), when);
final Intent notificationIntent = new Intent(this, MyActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, getString(R.string.notify_title), expandText, contentIntent);
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;//| Notification.FLAG_NO_CLEAR
Log.d(TAG, "notify send.");
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(SERVICE_ONGOING_NOTIFICATION_ID, notification);//ID = 0
}
#Override
public void onDestroy()
{
Log.d(TAG, "clear status bar notification.");
cancelNotification();
super.onDestroy();
}
private void cancelNotification()
{
final int icon = R.drawable.stbar_icon_exit;
final long when = System.currentTimeMillis();
final Notification notification = new Notification(icon, getString(R.string.notify_title), when);
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(this, getString(R.string.notify_stopping_title), getString(R.string.notify_stopping_text), contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(SERVICE_ONGOING_NOTIFICATION_ID); //NOTHING HAPPENS
mNotificationManager.notify(SERVICE_ONGOING_NOTIFICATION_ID, notification); //ID = 0 but if this was changed to 1 cancel notification can be cleared :/
}
I can see "exit" icon so onDestroy and cancelNotification are called, i have no idea what im doing wrong
It does not appear that you can successfully cancel ongoing notifications with ID 0: you will probably have to use a non-zero notification id.
The core notification manager service code is here, which doesn't appear to have a specific restriction on the choice of notification ID but everyone else who uses ONGOING notifications (for example, the Phone application) uses non-zero IDs.