Search code examples
javaandroidservicenotificationsstatus

Android Status Notifications


I have created a BackgroundService class which extends Service class.

I have a Timer which keeps track of the duration between checks. In the onCreate method I set it for 10 seconds, so the behavior I'm expecting is that it sends a status notification message every 10 seconds. The issue I'm having is that every 10 seconds, I hear the status notification "sound" as I enabled it, but I do not see the text reminder on the top of the screen, which only appears on the first notification service alert. Does anyone know how to fix this?

I attached a good deal of source for this class below: Thanks in Advance!

private Timer timer;

private TimerTask updateTask = new TimerTask() {
    @Override
    public void run() {
        Log.i(TAG, "Timer task doing work!");   

        // Process junk here:
        sendNotification("Please leave in 5 min!!!");
    }
};

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Log.i(TAG, "Background Service creating");

    timer = new Timer("DurationTimer");
    timer.schedule(updateTask, 1000L, 10*1000L);
}

public void sendNotification(CharSequence message)
{
    // Execute Check and Notify
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    int icon = R.drawable.simon;
    CharSequence tickerText = message;
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, tickerText, when);
    Context context = getApplicationContext();
    CharSequence contentTitle = "LEAVE NOW!";
    CharSequence contentText = "LEAVE NOW!!";
    Intent notificationIntent = new Intent(this, BackgroundService.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.defaults |= Notification.DEFAULT_SOUND;
    //notification.defaults |= Notification.DEFAULT_VIBRATE;

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    int HELLO_ID = 1;
    mNotificationManager.notify(HELLO_ID, notification);
}

Solution

  • Change the value of contentText with each iteration.

    Example:

    CharSequence contentText = "LEAVE NOW!! " + System.currentTimeMillis();
    

    I think you will find that the message text changes constantly because you already have a Notification with the same ID as the Notification you wish to send. So what happens is that the text is simply changed.

    Another way:

    mNotificationManager.clear(HELLO_ID);
    

    Do that before you create the new Notification.