3

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

然后 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);
4

1 回答 1

9

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

Service.startForeground(int, Notification)

Service.stopForeground(boolean)

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

于 2012-02-15T22:28:00.537 回答