Programmatically ending an ongoing notification -

2019-04-29 20:02发布

问题:

I am developing a GPS-based app and have just started adding in my UX features such as notifications and progress bars but I'm stuck on using an ongoing notification.

As it is a GPS app, when user tracking is started, I set up an ongoing notification to show that they are being tracked but how do I stop this notification when they tap "stop tracking" in my app? Do I have to tell the NotifyManager something? I'm basically trying to get the functionality that music players have, as in the "playing" notification appears when the user presses play, but when they pause, that ongoing "playing" notification is destroyed.

Also, I've never worked with GPS before but should I be going about this in a Service so that the user won't stop being tracked if my app is taken out of memory by the OS? Or would that not happen?

回答1:

I haven't done much with notifications but you might try this:

NotificationManager.cancel(id); // Where 'id' is the id of your notification

Replacing NotificationManager with the name of your instance of it, of course.

docs: http://developer.android.com/reference/android/app/NotificationManager.html#cancel%28int%29

Or this:

Notification.Builder.setAutoCancel(true);

http://developer.android.com/reference/android/app/Notification.Builder.html#setAutoCancel%28boolean%29



回答2:

Start

int id = 01;
NotificationCompat.Builder mBuilder =
      new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle(getResources().getString(R.string.service_header))
        .setContentText("Connect to: http://" + httpd.getip() + ":8080")
        .setContentIntent(pendingIntent)
        .setOngoing(true);

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(01, mBuilder.build());

Cancel

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(01);