问题
I have an online JSON file that shows the latest country earthquakes, the listView adapter in my app receives data from this JSON file and the refresh is manually by user`s swipe, but now I am adding an automatic and timely basis refresh mode to my list, the questions is: How can I create a system notification after a new quake is detected?
回答1:
Write this below code for sending System notification in your app while your data is loaded from network request.
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
putting this code block will show notification.
回答2:
Just build a Notification like this
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle(textTitle)
    .setContentText(textContent)
    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
And then just show it
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, mBuilder.build());
And for anything other extras check the official documentation
- In order for this to work you somehow should push when a new earthquake happens to your phone. If you have backend, you can send a push notification through the cloud messaging.
- If you don't have backend just create a background service and pull data every now and then and when data says new earthquake jsut follow the notification creation from above.
来源:https://stackoverflow.com/questions/49423908/how-to-create-notification-after-listview-receives-new-data-from-an-online-json