Android API7清除持续通知

时间:2011-07-19 22:01:34

标签: android notifications

从我的服务中发送(持续“ID = 0)持续通知,似乎没有办法从代码中清除它。如果我发送其他通知到相同的ID(0),图标和意图 将更新:/

我不知道这是否是API 7中的错误,但它对我没有任何意义。

当我使用Notification.FLAG_ONLY_ALERT_ONCE发送带有不同ID(例如1)的通知时,它被归类为简单通知,我可以轻松地从展开的菜单或代码中清除它。但只是通过向先前的ID(0)发送相同的通知,它被归类为正在进行,无论如何我无法取消它!

我还尝试保存对“正在进行”通知的引用,然后使用其他PendingIntent和/或标志重新通知它,但它没有效果!

我当前的服务代码

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    Log.d(TAG, "start notification");
    startStatusBarNotification();

    //do other stuff
    // We want this service to continue running until it is explicitly stopped, so return sticky.
    return START_STICKY;
}

private void startStatusBarNotification()
{
    Log.d(TAG, "startStatusBarNotification.");

    final int icon = R.drawable.stbar_icon_fail;
    final long when = System.currentTimeMillis();
    final Notification notification = new Notification(icon, getString(R.string.notify_title), when);

    final Intent notificationIntent = new Intent(this, MyActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    notification.setLatestEventInfo(this, getString(R.string.notify_title), expandText, contentIntent);
    notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;//| Notification.FLAG_NO_CLEAR

    Log.d(TAG, "notify send.");
    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(SERVICE_ONGOING_NOTIFICATION_ID, notification);//ID = 0
}

@Override
public void onDestroy()
{
    Log.d(TAG, "clear status bar notification.");
    cancelNotification();

    super.onDestroy();
}

private void cancelNotification()
{
    final int icon = R.drawable.stbar_icon_exit;
    final long when = System.currentTimeMillis();
    final Notification notification = new Notification(icon, getString(R.string.notify_title), when);
    final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, PendingIntent.FLAG_CANCEL_CURRENT);
    notification.setLatestEventInfo(this, getString(R.string.notify_stopping_title), getString(R.string.notify_stopping_text), contentIntent);
    notification.flags = Notification.FLAG_AUTO_CANCEL;

    final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(SERVICE_ONGOING_NOTIFICATION_ID);  //NOTHING HAPPENS
    mNotificationManager.notify(SERVICE_ONGOING_NOTIFICATION_ID, notification);   //ID = 0 but if this was changed to 1 cancel notification can be cleared :/
}

我可以看到“退出”图标,因此onDestroy和cancelNotification被调用,我不知道我做错了什么

1 个答案:

答案 0 :(得分:1)

您似乎无法成功取消ID为0的持续通知:您可能必须使用非零通知ID。

核心通知管理器服务代码为here,对通知ID的选择似乎没有特定限制,但使用ONGOING通知的所有其他人(例如,电话应用程序)都使用非零ID。