【发布时间】:2021-08-13 11:26:29
【问题描述】:
我最近制作了一个 MediaPlayer。我做了一个通知,在我按下播放后弹出并在我按下暂停按钮或退出按钮后自行取消。有一个问题。众所周知,每部手机都有自己的退出按钮。当我按下它时,通知不会取消并保留。 我相信我应该使用 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)));
}
提前谢谢你。
【问题讨论】:
标签: java android notifications android-mediaplayer notificationmanager