通知栏在更新时消失

时间:2016-06-04 16:18:55

标签: android notifications

public void createNotification(
    String title, String fileName,
    boolean setProgressBar,
    int maxValue, int progress, int notificationId,
    boolean firstTime) {

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    if (firstTime) {
        builder.setContentText(fileName);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setAutoCancel(false);
    }
    builder.setContentTitle(title);
    if (setProgressBar) {
        builder.setProgress(maxValue, progress, false);
    }
    Notification notification = builder.build();
    NotificationManager notificationManager =
       (NotificationManager)
         context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationId, notification);
}

我正在从其他一些活动创建通知并从其他一些活动更新。我用这个更新:

notificationManager.createNotification(
    "Downloading", document.getName(),
    true,
    (int) document.getContentLength(), (int)completedBytes,
    (int) document.getContentLength(),
    false);

我对此很新。任何领导都会有所帮助。感谢。

1 个答案:

答案 0 :(得分:0)

每次更新通知时,您都必须完全重建通知,因此您应该删除firstTime方法中对createNotification()的检查。

修改:对于对更详细解释感兴趣的人,更新的通知不会显示,因为每个通知都需要内容标题和文字,以及小图标,如Android开发者notifications页面。由于更新的通知包含那些(firstTime为false),因此生成的通知将无效。在具有相同ID的notify()上拨打NotificationManager仍会替换该通知,但由于该通知无效,因此无法显示新通知。

编辑(16/06/21):以下类可用于创建和更新进度通知,并且基于您上传的文件。要更新通知,只需再次致电createNotification(...),系统将负责正确更改通知。

public class SDCNotificationManager {
    public final static String OPEN_NOTIFICATION = "notification_open";
    public final static int MAX_PROGRESS_VALUE = 100;

    /*
     * Creates or updates a progress notification
     */
    public static void createNotification(Context context, String title, String fileName, int currentProgress, int maxProgress, int notificationId) {

        boolean notificationEnabled = SettingsManager.getInstance().(SettingsKey.ENABLE_NOTIFICATION);
        if (notificationEnabled) {
            Intent intent = new Intent(context, MainActivity.class);
            intent.setAction(OPEN_NOTIFICATION);
            // build notification
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContentTitle(title);
            builder.setContentText(fileName);
            builder.setSmallIcon(R.drawable.ic_launcher);
            builder.setProgress(maxProgress, currentProgress, false);
            Notification notification = builder.build();
            // send notification to system service
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(notificationId, notification);
        }
    }
}