Dan*_*nte 0 service notifications android
所以我创建了一个服务,它运行良好。它所做的只是计数。我有一个自定义类来处理使用通知的麻烦。这个类有一个 getNotification ,它显然返回它使用的通知。一切都很好,但我必须让我的服务在前台运行(它将一些重要数据同步到应用程序,在它完成之前不得中断)现在,当我添加 startForeground 时,我添加了我的通知和一个 id就这样离开了。startForeground(1337, 通知);
我遇到的问题是,由于某种原因,我做的第一个 notify() 独立于其他通知。因此,当我进行此运行时,它会创建两个通知。第一个停留在第一个更新上,其标题为“Zilean”,其内容为“计数”。另一个完美更新。我注意到如果 startForeground 以 0 (startForeground(0,notification)) 的 id 运行,那么这个问题就会得到解决,但是如果我终止了活动,通知就会消失。当 id <> 0 时不会发生。
我遇到这个问题的时间太长了,所以我使用了一个仅重要的虚拟服务。我想知道,如果 Activity 因用户而终止,或者仅仅因为 android 决定删除它的记忆,那么该服务将继续运行。
// onStartCommand
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// NOTIFICATION SECTION
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this);
notificationManagerClass = new SBNNotification(mNotifyManager,
mBuilder, true, 1, false, "Zilean",
"Initiating Counter", false);
notificationManagerClass.notificate();
final Notification notification = notificationManagerClass.getNotification();
notification.flags = flags;
notification.defaults = Notification.DEFAULT_LIGHTS;
startForeground(1337, notification);
new Timer().scheduleAtFixedRate(new TimerTask () {
int i=0;
@Override
public void run() {
notificationManagerClass.setContentTitle("Contando");
notificationManagerClass.setContentText(String.valueOf(i));
notificationManagerClass.notificate();
i++;
Log.e("HOLAAA", String.valueOf(i));
}}, 0, 1000);
return START_REDELIVER_INTENT;
}
Run Code Online (Sandbox Code Playgroud)
所以..我错过了什么?
解决了,我的错误是通知 id 与我传递的 startForeground id 不同 (1337)
编辑:重要的是要注意通知 id 和服务 id 不能为 0,否则它将与主活动线程混合