java - 服务一结束,通知就会消失

标签 java android notifications

我有一项服务可以抓取网站数据,然后在必要时向用户发出通知。

我遇到的问题是,一旦服务关闭(可能是立即关闭),通知就会消失。以下代码是应用程序具有的所有通知代码。我没有输入任何代码来取消通知。

public static void CreateNotificationCompat(int notificationID, String link, String title, String text, Context ctx)
{
    Intent notificationIntent = new Intent("android.intent.action.VIEW", Uri.parse(link));
    PendingIntent contentIntent = PendingIntent.getActivity(ctx.getApplicationContext(), 0, notificationIntent, 0);

    NotificationManager nm = (NotificationManager) ctx
            .getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
    Resources res = ctx.getResources();

    builder.setContentIntent(contentIntent)
                .setSmallIcon(R.drawable.notify_icon)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(title)
                .setContentText(text)
                .setAutoCancel(false);

    Notification n = builder.getNotification();

    nm.notify(notificationID, n);
}

如果它有什么不同(很确定它没有)我在这里使用应用程序上下文。

我的服务会定期启动,处理网站,在需要时发出通知,然后关闭。

在服务结束时,我没有调用 stopSelf(),而是睡了 30 秒左右,然后调用了 stopSelf()。然后通知停留 30 秒,然后消失。通知消失时,logcat 中没有任何相关内容。

到目前为止,我只能使用 ICS 进行测试。

最佳答案

您发布的代码有效。我通过 jb 上的 Activity 和服务对其进行了测试,当组件停止时,通知仍然存在。我什至证实我可以终止进程并且通知保留。尝试剥离应用程序并查看问题是否仍然存在。专门检查一下您是否在通知上错误地调用了取消。

关于java - 服务一结束,通知就会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521752/

相关文章:

java - 进程在 Linux 中通过 putty 的 ssh 连接被杀死

java - 空参数的 Vararg 类型推断

java - 用 BinaryOperator 替换 switch

java - 如何使用不记名 token 身份验证配置 Glide 以下载图像文件?

android - iOS 上的 Cordova Phonegap 本地通知声音

c# - 桌面通知,又名内部警报系统

java - 在JAVA中将数据导出到文本文件时的日期和写入问题

android - 当我只选择伦敦位置时,我在谷歌地图上崩溃了

ios - 意外删除 APNS 证书

java - Android:创建 Intent 后,我无法从 MainActivity 打开 UI