Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notifications disappear as soon as service ends

I've got a service that scrapes a website for data then if necessary gives the user a notification.

The problem I'm having is that the notifications disappear as soon as the service closes (which could be instantly). The below code is all of the notification code the app has. I haven't put in any code to cancel the notifications.

public static void CreateNotificationCompat(int notificationID, String link, String title, String text, Context ctx)
{
    Intent notificationIntent = new Intent("android.intent.action.VIEW", Uri.parse(link));
    PendingIntent contentIntent = PendingIntent.getActivity(ctx.getApplicationContext(), 0, notificationIntent, 0);

    NotificationManager nm = (NotificationManager) ctx
            .getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
    Resources res = ctx.getResources();

    builder.setContentIntent(contentIntent)
                .setSmallIcon(R.drawable.notify_icon)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(title)
                .setContentText(text)
                .setAutoCancel(false);

    Notification n = builder.getNotification();

    nm.notify(notificationID, n);
}

If it makes any difference (pretty sure it doesn't) i'm using the application context here.

My services is started periodically, processes a website, notifies if needed and then closes.

At the end of my service instead of just calling stopSelf() i sleep for 30 or so seconds and then call stopSelf(). Then the notification stays for 30 seconds and then disappears. Nothing relevant appears in logcat at the time the notifications disappear.

I've only been able to test using ICS so far.

like image 945
user1531605 Avatar asked Jul 17 '12 11:07

user1531605


2 Answers

The code you have posted works. I tested it from both an activity and a service on jb, and the notification stays when the components are stopped. I even verified that I could kill the process and the notification stays. Try to strip down the app and see if the problem persists. Specifically check to see that you don't call cancel on the notification by mistake.

like image 53
Tobias Ritzau Avatar answered Sep 22 '22 01:09

Tobias Ritzau


You seem to forgot check developer manual first. See here http://developer.android.com/guide/topics/ui/notifiers/notifications.html and look for FLAG_ONGOING_EVENT and FLAG_NO_CLEAR flags.

I've only been able to test using ICS so far.

That's why simulators are quite useful. Try it. It's part of SDK.

like image 43
Marcin Orlowski Avatar answered Sep 19 '22 01:09

Marcin Orlowski