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)
您可以重写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)
| 归档时间: |
|
| 查看次数: |
1370 次 |
| 最近记录: |