我正在创建一个显示当前播放歌曲的通知
的应用程序。
正在通过 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/