离开activity后如何取消通知?

How can I cancel the notification after I leave the activity?

我最近做了一个MediaPlayer。我制作了一个通知,在我按下播放按钮后弹出,并在我按下暂停按钮或退出按钮后自行取消。有一个问题。众所周知,每个 phone 都有自己的退出按钮。当我按下它时,通知不会取消并保持不变。 我相信我应该使用 onDestroy 但我不知道如何使用。也许还有其他方法。

这是我使用的大部分代码:

 backm4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            m4.super.onBackPressed();
            notificationManager.cancelAll();
        }
    });

    playerPosition = findViewById(R.id.playerPosition);
    playerDuration = findViewById(R.id.playerDuration);
    replay = findViewById(R.id.replay);
    forward = findViewById(R.id.forward);
    seekBar = findViewById(R.id.seekBar);
    btPause = findViewById(R.id.btPause);
    btPlay = findViewById(R.id.btPlay);

    populateTracks();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        createChannel();
    }

    btPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btPlay.setVisibility(View.GONE);

            btPause.setVisibility(View.VISIBLE);

            mediaPlayer.start();

            seekBar.setMax(mediaPlayer.getDuration());

            handler.postDelayed(runnable, 0);

            CreateNotification.createNotification(m4.this, tracks.get(0), R.drawable.pause,
                    0, tracks.size() -1);
        }
    });

    btPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btPause.setVisibility(View.GONE);

            btPlay.setVisibility(View.VISIBLE);

            mediaPlayer.pause();

            handler.removeCallbacks(runnable);

            notificationManager.cancelAll();

        }
    });
   
}

private void createChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel channel = new NotificationChannel(CreateNotification.CHANNEL_ID,
                "Diligent", NotificationManager.IMPORTANCE_LOW);

        notificationManager = getSystemService(NotificationManager.class);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}


private void populateTracks() {
    tracks = new ArrayList<>();

    tracks.add(new Track("You are watching Getting started meditation", "Press here to enter the app", R.drawable.diligent_transparent_logo));
}

@SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
    return String.format("%02d:%02d"
            , TimeUnit.MILLISECONDS.toMinutes(duration)
            ,TimeUnit.MILLISECONDS.toSeconds(duration) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}

提前致谢。

覆盖 onBackPressed() 方法并在其中添加 notificationManager.cancelAll()