【问题标题】:How to create notification after listview receives new data from an online JSON file?listview 从在线 JSON 文件接收到新数据后如何创建通知?
【发布时间】:2018-03-22 08:34:41
【问题描述】:

我有一个显示最新国家地震的在线 JSON 文件,我的应用程序中的 listView 适配器从这个 JSON 文件接收数据,并且通过用户的滑动手动刷新,但现在我正在添加一个自动和及时的基础刷新模式到我的清单,问题是: 检测到新地震后如何创建系统通知?

【问题讨论】:

标签: android json listview android-notifications auto-update


【解决方案1】:

编写以下代码,以便在从网络请求加载数据时在您的应用中发送系统通知。

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(getApplicationContext())
            .setContentTitle("App Name / Title Message")
            .setContentText("Description Message hat data is updated")
            .setDefaults(Notification.DEFAULT_ALL)
            .setSmallIcon(R.drawable.ic_notification_icon)
            .setColor(getResources().getColor(R.color.icon_color))
            .setPriority(Notification.PRIORITY_HIGH) // will show notification even you are in app
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();
    notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_SHOW_LIGHTS;
    NotificationManager notificationManager = (NotificationManager)
            getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);

    //you can use unique identification int number for notificationID instead of 1

放置此代码块将显示通知。

【讨论】:

  • 我正在使用AsyncTask进行网络请求,我应该把它放在postExecute阶段吗?
【解决方案2】:

只需构建这样的通知

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle(textTitle)
    .setContentText(textContent)
    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

然后只需展示它

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, mBuilder.build());

如果有任何其他额外内容,请查看official documentation

  • 为了使此功能起作用,您应该以某种方式在手机发生新地震时推送。如果您有后端,您可以通过cloud messaging 发送推送通知。
  • 如果您没有后端,只需创建一个后台服务并不时提取数据,当数据显示新地震时,请按照上面的通知创建。

【讨论】:

  • 谢谢,但主要问题是适配器收到新数据后如何创建通知,而不是如何创建通知。
  • 基本上,当您将项目添加到适配器时,您只需像上面一样创建一个通知?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
相关资源
最近更新 更多