我有一项服务可以抓取网站数据,然后在必要时向用户发出通知。
我遇到的问题是,一旦服务关闭(可能是立即关闭),通知就会消失。以下代码是应用程序具有的所有通知代码。我没有输入任何代码来取消通知。
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/