I am building an Android application using Android. In my app, I am trying to do something when the device receives a new text message even if the app is closed. Basically, I am trying to show notification when a new text message is received. I am using broadcaster for that. But it is not working as expected.
This is my receiver.
class SmsListener: BroadcastReceiver() {
private lateinit var notificationManager: NotificationManager
private lateinit var notificationChannel: NotificationChannel
lateinit var builder: Notification.Builder
private val channelId = "i.apps.notifications"
private val description = "Test notification"
private lateinit var context: Context
override fun onReceive(context: Context?, intent: Intent?) {
this.context = context as Context
if(intent?.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
val bundle = intent!!.extras //---get the SMS message passed in---
var msgs: Array<SmsMessage?>? = null
var msg_from: String
if (bundle != null) {
//---retrieve the SMS message received---
try {
val pdus =
bundle["pdus"] as Array<Any>?
msgs = arrayOfNulls<SmsMessage>(pdus!!.size)
for (i in msgs.indices) {
msgs[i] = SmsMessage.createFromPdu(pdus!![i] as ByteArray)
msg_from = msgs[i]!!.getOriginatingAddress() as String
val msgBody: String = msgs[i]!!.getMessageBody()
//@TODO: display the notification. When clicked, redirect the user to the message details activity with a share button
if (! msgBody.isNullOrEmpty()) {
showNotification(msgBody)
}
}
} catch (e: Exception) {
}
}
}
}
private fun showNotification(message: String) {
//@TODO: remove the identifier from the message
//@TODO: confirm number of characters for message description
initialiseNotificationManager()
val intent = Intent(this.context, MessageDetailsActivity::class.java)
intent.putExtra(MessageDetailsActivity.KEY_MESSAGE, message)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
initialiseNotificationChannel()
builder = Notification.Builder(this.context, channelId).setContentTitle("22222: New message received.").setContentText(message.take(50)).setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setLargeIcon(BitmapFactory.decodeResource(this.context.resources, R.drawable
.ic_launcher_background)).setContentIntent(pendingIntent)
}
notificationManager.notify(12345, builder.build())
}
private fun initialiseNotificationChannel(){
if (! this::notificationChannel.isInitialized) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(channelId, description, NotificationManager .IMPORTANCE_HIGH)
notificationChannel.lightColor = Color.BLUE
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
}
}
}
private fun initialiseNotificationManager() {
if (! this::notificationManager.isInitialized) {
notificationManager = this.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
}
}
This is how I registered the receiver in the AndroidManifest.xml file.
<receiver android:name=".SmsListener">
<intent-filter>
<action android:name="com.forkthecoup.com22222.SmsListener" ></action>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
This is how I register the receiver in the main activity
try {
// register the broadcast receiver to catch the incoming messages
var filter = IntentFilter()
filter.addAction("com.forkthecoup.com22222.SmsListener")
val receiver: SmsListener = SmsListener()
registerReceiver(receiver, filter)
sendBroadcast(Intent("com.forkthecoup.com22222.SmsListener"))
} catch (e: Exception) {
}
Yes, I have granted the right permissions to the app to receive and send the messages. But when the app receives a new message, it is not showing the notification. What is wrong with my code and how can I fix it?
You haven't added the notification for Api 24 and below here is the code
private fun showNotification(message: String) {
//@TODO: remove the identifier from the message
//@TODO: confirm number of characters for message description
initialiseNotificationManager()
val intent = Intent(this.context, MainActivity::class.java)
intent.putExtra("MainActivity.KEY_MESSAGE", message)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
initialiseNotificationChannel()
Notification.Builder(this.context, channelId).setContentTitle("22222: New message received.").setContentText(message.take(50)).setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setLargeIcon(BitmapFactory.decodeResource(this.context.resources, R.drawable
.ic_launcher_background)).setContentIntent(pendingIntent)
} else {
Notification.Builder(this.context).setContentTitle("22222: New message received.").setContentText(message.take(50)).setSmallIcon(R.drawable.common_google_signin_btn_icon_dark).setLargeIcon(BitmapFactory.decodeResource(this.context.resources, R.drawable
.ic_launcher_background)).setContentIntent(pendingIntent)
}
notificationManager.notify(12345, builder.build())
}