This is my code to sent notification of new message in a chat ro all the chats participants:
private inner class SentNotificationToUserAsyncTask(
val boardName:String,
val textMessage: String, val token: ArrayList<String>
)
: AsyncTask<Any, Void, String>() {
override fun onPreExecute() {
super.onPreExecute()
showProgressDialog()
}
override fun doInBackground(vararg params: Any?): String {
var result: String
var connection: HttpURLConnection? = null
try {
val url = URL(Constans.FCM_BASE_URL)
connection = url.openConnection() as HttpURLConnection
connection.doOutput = true
connection.doInput = true
connection.requestMethod = "POST"
/**
* Sets the general request property. If a property with the key already
* exists, overwrite its value with the new value.
*/
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("charset", "utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty(
Constans.FCM_AUTHORIZATION, "${Constans.FCM_KEY}=${Constans.FCM_SERVER_KEY}",
)
connection.useCaches = false
val wr = DataOutputStream(connection.outputStream)
val jsonRequest = JSONObject()
val dataObject = JSONObject()
dataObject.put(Constans.FCM_KEY_TITLE,"${boardName}: ")
dataObject.put(Constans.FCM_KEY_MESSAGE,textMessage )
jsonRequest.put(Constans.FCM_KEY_DATA, dataObject)
jsonRequest.put(Constans.FCM_KEY_TO, token)
wr.writeBytes(jsonRequest.toString())
wr.flush()
wr.close()
val httpResult:Int = connection.responseCode
if (httpResult == HttpURLConnection.HTTP_OK){
val inputStream = connection.inputStream
val reader = BufferedReader(
InputStreamReader(
inputStream)
)
val sb = StringBuilder()
var line: String?
try {
while (reader.readLine().also{ line=it} !=null ){
sb.append(line+"\n")
}
}catch (e: IOException){
e.printStackTrace()
}finally {
try {
inputStream.close()
}catch (e: IOException){
e.printStackTrace()
}
}
result = sb.toString()
}else{
result = connection.responseMessage
}
}catch (e: SocketTimeoutException){
e.printStackTrace()
result = "ERROR : "+ e.printStackTrace()
}finally {
connection?.disconnect()
}
return result
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
hideProgressDialog()
}
}
The class that handling the notification:
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d("onMessageReceived","FROM: ${remoteMessage.from}")
remoteMessage.data.isNotEmpty().let {
Log.d("onMessageReceived","Message data: ${remoteMessage.data}")
val title = remoteMessage.data[Constans.FCM_KEY_TITLE]!!
val message = remoteMessage.data[Constans.FCM_KEY_MESSAGE]!!
sentNotification(title,message)
}
remoteMessage.notification.let {
Log.d("onMessageReceived","Message notification body: ${it?.body}")
}
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.e("onNewToken", "Refresh token $token")
sentResitrationToServer(token)
}
private fun sentResitrationToServer(token: String?){
}
private fun sentNotification(title: String,messageBody: String){
val intent = if (FireStore().getCurrentUid().isNotEmpty()) {
Intent(this, MainActivity::class.java)
} else {
Intent(this, signInActivity::class.java)
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_CLEAR_TASK)
val pendingIntent = PendingIntent.getActivity(this,
0,intent,PendingIntent.FLAG_ONE_SHOT)
val channelId = this.resources.getString(R.string.deafult_notification_channel_id)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
val notificationBuilder = NotificationCompat.Builder(
this,channelId
).setSmallIcon(R.drawable.ic_baseline_android_24)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_MAX)
val notificationManager = getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channel = NotificationChannel(channelId,
"channel MessagePiegon title",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0,notificationBuilder.build())
}
}
The notification will work if I would sent one token instead of Array list of tokens, what do I need to change in order to sent notification to few users?
If sombody have an idea it would be very helpful