Programmatically ending an ongoing notification - Android

大兔子大兔子 提交于 2019-12-07 06:43:14

问题


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);


来源:https://stackoverflow.com/questions/5208098/programmatically-ending-an-ongoing-notification-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!