android - 如何取消意外/强制应用程序终止的通知

标签 android android-service android-notifications

我正在创建一个显示当前播放歌曲的通知的应用程序。

正在通过 Service 播放歌曲,并且通知的启动和取消在服务本身中完成。

但如果应用程序因某些异常而终止,或者如果我通过任务管理器强行关闭它,通知将保留在任务栏的顶部。

我怎样才能删除它。

代码如下:

//In Service onStartCommand(), there is a call to initiatePlayback()
private void initiatePlayback() {
    try {
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        mPlayer.reset();
        mPlayer.setDataSource(currentData);
        mPlayer.prepare();

        if (reqAudioFocus()) {
            mPlayer.start();
        }

        if (mPlayer.isPlaying()) {
            initNotification();
        }
    } catch (Exception e) {
        Toast.makeText(this,
                "PlayTrack->initiatePlayback(): " + e.toString(),
                Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onDestroy() {
    stopPlayback();
    mPlayer.release();
    mPlayer = null;
    super.onDestroy();
}

private void stopPlayback() {
    if (mPlayer.isPlaying()) {
        mPlayer.stop();
        mPlayer.reset();
        cancelNotification();
    }
}
private void cancelNotification() {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        mNotificationManager.cancel(NOTIFICATION_ID);
    }

最佳答案

捕获异常并在 catch 子句中取消它:

mNotificationManager.cancel(MY_NOTIFICATION_ID);

关于android - 如何取消意外/强制应用程序终止的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930046/

相关文章:

Android 上的 Java sardine webdav 客户端

android - 将 Activity 绑定(bind)到正在运行的服务时未调用 onUnbind

android - 为什么 TileService 会等待几秒钟才能启动 Activity?

android - Parse.com - Android 自定义推送通知声音

Android 通知 Big View - Intent on button not fired

Android - 如何实现嵌套按钮

单选按钮的Android环形

java - Android 4.0/ICS - 操作栏上的应用程序图标不可点击

java - 在服务中同步执行长时间运行的方法

android - 如何以编程方式检查 "enabled_notification_listeners"?