java - 从服务中删除正在进行的通知

标签 java android android-service android-notifications

我有一项服务在启动时创建通知。

然后 ondestroy() 我希望它被删除。

我只是使用 .cancel(NOTIFICATION_ID);

当它是一个正常的通知时,它工作得很好,但当我使用正在进行的事件时,它不会取消它。

我确实读过一些关于如果 android 有它的资源服务不会停止,但如何克服这个问题?

我用这段代码来启动服务

    final Intent bg_service = new Intent(BackgroundService.class.getName());

    btn_start = (Button)findViewById(R.id.btn_start);
    btn_stop = (Button)findViewById(R.id.btn_stop);

    btn_start.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(bg_service);
        }
    });

    btn_stop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(bg_service);
        }
    });

我在创建时使用它

            notificationManager = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.ic_launcher,
            "A new notification", System.currentTimeMillis());

    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;

    Intent intent = new Intent(this, mainapp.class);
    PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
    notification.setLatestEventInfo(this, "...",
            "...", activity);
    notificationManager.notify(19314, notification);

这在销毁

            noficationManager.cancel(19314);

最佳答案

如果可以的话,我会以不同的方式看待“持续”通知。 Service 上有一些方法专门用于添加和删除“正在进行的”通知。

Service.startForeground(int, Notification)

Service.stopForeground(boolean)

也许您可以先尝试从 onDestroy() 方法调用 stopForegroud(boolean)...

关于java - 从服务中删除正在进行的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9302002/

相关文章:

android - 如何在 64 位 Android 设备上使用 32 位 native 库

java - 我的 Android 项目在 Enum 和 string.xml 之间有重复的声明

Android GCM 向服务器发送 token

Android:如何从远程服务中运行的线程中显示 toast ?

java - 使用 BufferedReader 从文件中读取一组行

java - 文件下载代码在 IE 中出错,在其他浏览器中一切正常

java - 发送十六进制命令到 ESC/POS 打印机 Android

java - 从Java服务器发送图像到android客户端

java - 过滤按属性区分并按日期排序的列表的好方法

android - Android Services 与 MVVM 中的 Activity 通信(Model View View Model)