为什么每 2 分钟后没有发生一次安卓通知



我尝试每 2 分钟创建一次通知,但只创建了单个通知(当应用程序启动时)。我的代码是:

通知我.java :

public class notifyme extends Service {
    @Override
    public void onCreate() {
     super.onCreate();
    Intent intent=new Intent(this,MainActivity.class);
    TaskStackBuilder stackBuilder=TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent);
    PendingIntent pendingIntent=stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder notify=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Hello")
            .setContentText("Some random text")
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
    NotificationManager nMgr=(NotificationManager)this.getSystemService(this.NOTIFICATION_SERVICE);
    Random r=new Random();
    int nid=r.nextInt(50000)+1;
    nMgr.notify(nid,notify.build());
}


@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

在主活动中.java :

Intent notificationIntent = new Intent(this, notifyme.class);
PendingIntent contentIntent =       PendingIntent.getService(getApplicationContext(), 0, notificationIntent,0);
AlarmManager am = (AlarmManager) getSystemService(this.ALARM_SERVICE);
am.cancel(contentIntent);
am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),120*1000, contentIntent);
首先,

您不需要整个服务来显示通知,如果这就是它所做的一切,您可以使用BroadcastReceiver并使用PendingIntent.getBroadcast方法。BroadcastReceiver 需要更少的内存,并且没有任何生命周期(这可能会使事情复杂化)。

您没有看到多个通知的原因是在线nMgr.notify(119,notify.build());

此数字119是通知 ID。因此,在再次执行该代码的 X 秒后,您的新通知将直接替换旧通知,一切看起来好像没有更改。

如果您想放置多个通知(又名。向用户发送垃圾邮件),您应该始终更改该号码。也许使用Random

首先,每两秒发出新通知完全违反准则。

正如文档所说:

当您需要为同一类型多次发出通知时 当然,您应该避免发出全新的通知。 相反,您应该考虑更新以前的通知,或者 通过更改其某些值或向其添加值,或两者兼而有之。

这里的问题是您使用相同的 ID 来创建通知。(此处为19)。

发布通知时,如果存在具有相同 ID 的活动通知,则通知管理器将更新现有通知。因此,每次服务运行时,它只会使用 ID "19"更新通知。

如果您热衷于每 2 分钟发出一次通知(这会严重影响应用程序的用户体验,让我警告您),请尝试为通知提供不同的 ID。您可以将发行的ID保存在共享首选项或其他东西中。

最新更新