Show notifications for all unread conversations

This commit is contained in:
Moez Bhatti
2017-09-22 00:30:12 -04:00
parent 895deff607
commit e9b4d05e7f
@@ -11,6 +11,7 @@ import com.moez.QKSMS.R
import com.moez.QKSMS.data.model.Conversation
import com.moez.QKSMS.data.model.Message
import io.realm.Realm
import io.realm.Sort
class NotificationHelper(val context: Context) {
@@ -37,26 +38,28 @@ class NotificationHelper(val context: Context) {
}
}
// https://developer.android.com/guide/topics/ui/notifiers/notifications.html
fun update() {
val realm = Realm.getDefaultInstance()
val conversation = realm.where(Conversation::class.java).findFirst()
if (conversation != null) {
val messages = realm.where(Message::class.java).equalTo("threadId", conversation.id).findAllSorted("date")
// A conversation title can also be set here
// https://developer.android.com/guide/topics/ui/notifiers/notifications.html
realm.where(Conversation::class.java).equalTo("read", false).findAllSorted("date").forEach { conversation ->
val style = NotificationCompat.MessagingStyle("Me")
messages.take(NotificationCompat.MessagingStyle.MAXIMUM_RETAINED_MESSAGES).forEach { message ->
style.addMessage(message.body, message.date, if (message.isMe()) null else "Person")
}
realm.where(Message::class.java)
.equalTo("threadId", conversation.id)
.findAllSorted("date", Sort.DESCENDING)
.take(2)
.reversed()
.forEach { message ->
val name = if (message.isMe()) null else conversation.getTitle()
style.addMessage(message.body, message.date, name)
}
val notification = NotificationCompat.Builder(context, "channel_1")
.setColor(context.resources.getColor(R.color.colorPrimary))
.setSmallIcon(R.mipmap.ic_launcher)
.setStyle(style)
notificationManager.notify(0, notification.build())
notificationManager.notify(conversation.id.toInt(), notification.build())
}
realm.close()