如何在应用程序中发生某个事件时在android上显示通知。例如listView已更新

时间:2018-05-08 03:47:02

标签: android notifications android-notifications

我正在构建新闻应用。我在android中使用listView。我想在将新项目推送到列表或更新整个列表时在状态栏上显示通知。 如何在应用程序关闭时显示通知。 谢谢。

1 个答案:

答案 0 :(得分:1)

我们可以使用可以从上下文接收的NotificationManager类在特定事件上从App端创建本地通知

// prepare intent which is triggered if the
    // notification is selected
 Intent intent = new Intent(this, NotificationReceiver.class);
    // use System.currentTimeMillis() to have a unique ID for the pending intent
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);

    // build notification
    // the addAction re-use the same intent to keep the example short
    Notification n  = new Notification.Builder(this)
                    .setContentTitle("test@gmail.com")
                    .setContentText("Subject")
                    .setSmallIcon(R.drawable.icon)
                    .setContentIntent(pIntent)
                    .setAutoCancel(true), pIntent).build();


    NotificationManager notificationManager =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(0, n);