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

rei*_*ley 7 android android-service android-notifications

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

歌曲正在播放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);
    }
Run Code Online (Sandbox Code Playgroud)

Kor*_*urk 0

您可以重写onDestroy()方法并使用NotificationManager来取消通知。您只需提供应取消通知的 ID。

@Override
public void onDestroy() {

    private static final int MY_NOTIFICATION_ID= 1234;
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager;
    mNotificationManager = (NotificationManager) getSystemService(ns);
    mNotificationManager.notify(MY_NOTIFICATION_ID, notification);
    //to cancel:
    mNotificationManager.cancel(MY_NOTIFICATION_ID);
}
Run Code Online (Sandbox Code Playgroud)

  • 是的..问题是 OnDestroy 甚至没有被调用。我正在使用“系统”任务管理器。问题是其他玩家甚至没有关闭&我认为这是一个正确的功能。所以现在我将尝试不通过任务管理器强制关闭停止播放。 (3认同)
  • 这不能解决问题。应用程序不知道它正在被杀死(强制关闭)。强制关闭或终止应用程序时,永远不会调用 Activity 的回调。 (2认同)