I can't use findViewById(int). Reference is not possible - android

I just need to be able to use findViewById(int). I've seen several examples. But I couldn't understand it because it was a little different from me.
I need to know the true value of the checkbox in the notification, and to do that I have to use findViewById(int).
Please help me how can i fix the code so i can reference the checkbox.
The error only occurs with findViewById(int).
Here's the code:
companion object {
const val NOTIFICATION_ID = 100
const val NOTIFICATION_CHANNEL_ID = "1000"
}
override fun onReceive(context: Context, intent: Intent) {
createNotificationChannel(context)
notifyNotification(context)
}
private fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"기상 알람",
NotificationManager.IMPORTANCE_HIGH
)
NotificationManagerCompat.from(context).createNotificationChannel(notificationChannel)
}
}
private fun notifyNotification(context: Context) {
with(NotificationManagerCompat.from(context)) {
val build = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle("알람")
.setContentText("일어날 시간입니다.")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationCompat.PRIORITY_HIGH)
notify(NOTIFICATION_ID, build.build())
val firebaseDatabase = FirebaseDatabase.getInstance()
val databaseReference = firebaseDatabase.reference
val cb1 = findViewById<CheckBox>(R.id.checkBox)
if (cb1.isChecked == true) {
databaseReference.child("c").setValue("C")
}
}
}
Can't use requireView
val cb = requireView().findViewById<CheckBox>(R.id.checkbox)
if (cb.ischecked == true)

You cannot access the layout's elements outside the activity, or without a reference to the activity which inflated the layout. You could define a constant value somewhere in your application:
object Constants{
var checked = false
}
and update it on the onChecked event of the checkbox. Then you can access the checked variable in your notification code:
if(Constants.checked){
databaseReference.child("c").setValue("C")
}
Edit, thanks to user tenfour for reminding me:
You can also access the elements of a view, when you have a reference to the root view of the layout.
view.findViewById<CheckBox>(R.id.checkbox).isChecked

Related

Kotlin: Type mismatch: inferred type is String but Context was expected -(notification channel in kotlin-class specific error)

I am making an app which requires the use of work manager to make a notification, I know how to make notifications in an activity but writing them in a separate kotlin file in the do work method as follows:
class NotificationWorkManager(appContext: Context, workerParams: WorkerParameters):
Worker(appContext, workerParams) {
//notification variables
val CHANNEL_ID = "channel_ID"
val CHANNEL_NAME = "channel_NAME"
val NOTIFICATION_ID = 0
override fun doWork(): Result {
triggerNotify()
return Result.success()
}
fun triggerNotify(){
createNotificationChannel()
//big picture:notification
val notiStyle = NotificationCompat.BigPictureStyle()
var remote_picture = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.make_new)
notiStyle.bigPicture(remote_picture)
//open the app from outside the app
val intent = Intent(applicationContext, MainActivity::class.java)
val pendingIntent = TaskStackBuilder.create(applicationContext).run{
addNextIntentWithParentStack(intent)
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
}
//main notification variable
val notification= NotificationCompat.Builder(applicationContext,CHANNEL_ID)
.setContentTitle("Workmg")
.setContentText("basdasdadfhgafgsgsfg")
.setSmallIcon(R.drawable.ic_bb)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setColor(Color.RED)
.setStyle(notiStyle)
.setProgress(100,10,true)//true keeps scroller running
.setLargeIcon(BitmapFactory.decodeResource(applicationContext.resources, R.drawable.make_new))
.setContentIntent(pendingIntent)
.build()
val notificationManager = NotificationManagerCompat.from(applicationContext)
notificationManager.notify(NOTIFICATION_ID,notification)
}
fun createNotificationChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channel= NotificationChannel( CHANNEL_ID,CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH).apply {
lightColor= Color.RED
enableLights(true)
}
val manager= getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}
}
}
My error arises in the last few lines where the manager variable is declared along with a red-wavy line underneath NOTIFICATION_SERVICE ::
Type mismatch: inferred type is String but Context was expected
This does not happen if the code is written directly in the Main Activity which i am not doing in this case becuase iI want to use it in a Work Manager.
I tried using Context.NOTIFICATION_SERVICE but still got the same error.
Please help...
To acquire a system service, we generally need both Context object and some kind of a service identifier (e.g. String). When we acquire a system service from Activity (or e.g. Service) we only need to provide an identifier, as Activity is itself a Context object, so Context is already known. In such a case we use Context.getSystemService() function.
In your case you are outside of the Context, so I'm not sure what is the getSystemService() function you use. Maybe you imported a static function: ContextCompat.getSystemService(). In that case, as you can see in the documentation, you need to provide both Context and service identifier to it.
But anyway, workers have access to the context using applicationContext property, so you should be able to acquire a system service with
val manager= applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager

Android Bad notification posted Crash

I'm new to coding. I have made a net speed indicator app for fun. It displays the network speed as a status bar icon. It also allows users to set data usage limits (like 100 GB per month) and sends a notification when they reach the limit.
The final output looks like this:
I followed this answer to display the status bar icon.
Here is the Notifications class I use:
class Notifications(private val context: Context) {
private val notificationChannelPrimary =
"Primary Channel Notification" // This is the persistent channel that shows live data usage
val notificationPersistentChannelID = 15 // To send notifications of persistent channel
private val notificationChannelDataLimit = "Data Limit Warning Notifications"
private val notificationDataLimitID = 10
private val intentNotification = Intent(context, MainActivity::class.java)
private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
private var mNotificationBuilder: Notification.Builder? = null
private var tempValues = arrayOf(String())
// The following variables are for creating status bar icon
private val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
private val canvas = Canvas(bitmap)
private val paintSpeed = Paint() // This is for speed value
private val paintUnit = Paint() // This is for speed unit
init {
// Set the paint styles
paintSpeed.color = Color.WHITE
paintSpeed.isAntiAlias = true
paintSpeed.textSize = 60f
paintSpeed.textAlign = Paint.Align.CENTER
paintSpeed.typeface = Typeface.DEFAULT_BOLD
paintUnit.color = Color.WHITE
paintUnit.isAntiAlias = true
paintUnit.textSize = 40f
paintUnit.textAlign = Paint.Align.CENTER
paintUnit.typeface = Typeface.DEFAULT_BOLD
createNotificationChannel()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationBuilder =
getNotificationBuilder()
}
}
// This method sets the speed to zero when the device is offline
fun setZeroSpeed() {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
canvas.drawText("0", 48f, 52f, paintSpeed)
canvas.drawText("Kb/s", 48f, 95f, paintUnit)
try {
mNotificationBuilder?.setSmallIcon(Icon.createWithBitmap(bitmap))
notificationManager.notify(notificationPersistentChannelID, mNotificationBuilder?.build())
} catch (e: Exception) {
e.printStackTrace()
}
}
// This method shows the speed + data usage on the notification
// It is called every second (from a worker thread)
fun updateDataUsage(
dataSpeed: Long,
remainingData: String?,
planDetails: String?
) {
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)
// BytesConversion.convertSpeed() method takes long value and returns speed with unit array (like 2 Mb/s)
tempValues = BytesConversion.convertSpeed(dataSpeed)
canvas.drawText(tempValues[0], 50f, 50f, paintSpeed)
canvas.drawText(tempValues[1], 50f, 95f, paintUnit)
// If the argument of setContentTitle is null, it's not displaying anything in the title
mNotificationBuilder?.setContentTitle(remainingData)
mNotificationBuilder?.setContentText(planDetails)
try {
mNotificationBuilder?.setSmallIcon(Icon.createWithBitmap(bitmap))
notificationManager.notify(notificationPersistentChannelID, mNotificationBuilder?.build())
} catch (e: Exception) {
}
}
// This method sends notifications when the data usage limit is reached
// You don't need to check supported or unsupported
// because it works in all the devices
// It's just a normal notification
fun sendDataLimitWarning(dataUsageTitle: String?, dataUsageDescription: String?) {
val notificationDataLimit = getNotificationBuilderDataLimit()
notificationDataLimit.setContentText(dataUsageDescription)
notificationDataLimit.setContentTitle(dataUsageTitle)
notificationManager.notify(
notificationDataLimitID,
notificationDataLimit.build()
)
}
// Notification channel is only available from Android Oreo
// So, check the condition
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannels = mutableListOf<NotificationChannel>()
val notificationChannel1 = NotificationChannel(
notificationChannelPrimary, "Persistent Notification",
NotificationManager.IMPORTANCE_HIGH
)
notificationChannel1.description = "Notification that shows data usage and speed"
notificationChannel1.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
val notificationChannel2 = NotificationChannel(
notificationChannelDataLimit, "Data Limit Warning",
NotificationManager.IMPORTANCE_HIGH
)
notificationChannel2.description = "Notification that shows data limit warnings"
notificationChannel2.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationChannel2.enableVibration(true)
notificationChannel2.enableLights(true)
notificationChannels.add(notificationChannel1)
notificationChannels.add(notificationChannel2)
notificationManager.createNotificationChannels(notificationChannels)
}
}
// This is for sending data limit warnings
private fun getNotificationBuilderDataLimit(): NotificationCompat.Builder {
val pendingIntentDataLimit = PendingIntent.getActivity(
context,
notificationDataLimitID,
intentNotification,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(
context,
notificationChannelDataLimit
)
.setContentTitle("Data Limit Warning")
.setSmallIcon(R.drawable.icon_notification)
.setColor(ContextCompat.getColor(context, R.color.primary_color))
.setContentIntent(pendingIntentDataLimit)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
}
// This is for sending data + speed notification
// Speed indicator requires Notification.Builder
#RequiresApi(Build.VERSION_CODES.O)
fun getNotificationBuilder(
): Notification.Builder {
val pendingIntentNotification = PendingIntent.getActivity(
context,
notificationPersistentChannelID,
intentNotification,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return Notification.Builder(
context,
notificationChannelPrimary
)
.setSmallIcon(R.drawable.icon_notification)
.setContentIntent(pendingIntentNotification)
.setAutoCancel(false)
.setStyle(Notification.BigTextStyle())
.setOnlyAlertOnce(true)
.setColor(ContextCompat.getColor(context, R.color.primary_color))
}
}
The problem is that I'm getting the following crashes a lot.
Fatal Exception: android.app.RemoteServiceException: Bad notification(tag=null, id=15) posted from package [package_name], crashing app(uid=10769, pid=16295): Couldn't inflate contentViewsjava.util.ConcurrentModificationException
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1894)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
and
Fatal Exception: android.app.RemoteServiceException: Bad notification(tag=null, id=15) posted from package [package_name], crashing app(uid=10337, pid=27920): Couldn't inflate contentViewsjava.lang.ArrayIndexOutOfBoundsException: src.length=8 srcPos=0 dst.length=8 dstPos=2 length=8
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2168)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:227)
at android.app.ActivityThread.main(ActivityThread.java:7822)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1026)
I searched for "Bad notification posted crash", I found that mNotificationBuilder.setSmallIcon() argument must be a PNG icon (I'm calling it in updateDataUsage() method). Can someone please tell me how to convert the bitmap to PNG and pass it to setSmallIcon()?

Notification sound isn't changing from default, even after changing in Android

I have been trying to change the sound of the notification but it isn't changing at all.
It is using the default notification in all cases, even when I have assigned the channel.
Please check the codes below and let me know, where I am going wrong.
Created Notification Channel in Application class
class App : Application() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
private fun createNotificationChannel() {
val ordersChannelId = "Orders"
val orderSoundUri =
Uri.parse("android.resource://" + applicationContext + "/raw/ordernotification")
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
val VIBRATE_PATTERN = longArrayOf(0,400,800,600,800,800,800,1000)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val ordersChannel =
NotificationChannel(ordersChannelId, "Orders", NotificationManager.IMPORTANCE_HIGH)
ordersChannel.apply {
description = "This is Orders Channel"
setSound(orderSoundUri, attributes)
vibrationPattern = VIBRATE_PATTERN
importance = NotificationManager.IMPORTANCE_HIGH
}
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(ordersChannel)
}
}
Creating Notifications using FireBaseMessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d("NotificationFire", "From: ${remoteMessage?.data}")
val contentIntent = Intent(applicationContext, OrderInDetailActivity::class.java)
val orderSoundUri = Uri.parse("android.resource://"+applicationContext+"/raw/ordernotification")
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ALARM).build()
val VIBRATE_PATTERN = longArrayOf(0, 500)
val contentPendingIntent = PendingIntent.getActivity(
applicationContext,
0,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
remoteMessage?.data?.let {
Log.d("NotificationFire", "Message Notification Data: ${it}")
//Message Services handle notification
val notification = NotificationCompat.Builder(this, "Orders")
.setSmallIcon(R.drawable.biskit_logo)
.setContentTitle(remoteMessage.data.toString())
.setContentText(remoteMessage.data.toString())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(orderSoundUri)
.setVibrate(VIBRATE_PATTERN)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(contentPendingIntent)
.build()
val notificationManager = NotificationManagerCompat.from(this)
Log.d("NotificationFire","Notification")
notificationManager.notify(1,notification)
}
This code is able to display notifications with the default sound only.
In your sound path you appended applicationContext. It will add some random value in your path. Instead you need to add the package name like this below.
Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play

Messages not always being received by Firebase Messaging Service

In my chat app I use FCM with Firebase Functions to send notifications whenever a user receives a new message.
For that I have a FirebaseMessagingService that overrides the onMessageReceived. Aside from that, this Service also overrides onNewToken. Whenever the user first starts the app, the onNewToken gets called and I retrieve a new token and store it in the Firebase Realtime Database.
I then go chat with some user (without closing the app). When I receive new messages, I get the notification. The onMessageReceived gets called.
The problem is, when I close the app and later open it (or turn off emulator and start it up again), and I get a new message from that same previous chat, the service does not get called. I know for a fact that the problem isn't with the Firebase Functions because in my console log I get a Success Message.
Does the Firebase Messaging Service stop when I close and re-open the app?
Here is the code for my Firebase Messaging Service
class MyFirebaseInstanceId : FirebaseMessagingService() {
private lateinit var sp: SharedPreferences
private lateinit var auth: FirebaseAuth
private lateinit var uid: String
private lateinit var token: String
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
if (p0.data.isNotEmpty()) {
val payload: Map<String, String> = p0.data
sendNotification(payload)
}
}
override fun onNewToken(p0: String) {
super.onNewToken(p0)
// Save the new token
sp = getSharedPreferences("AUTH_UID", Context.MODE_PRIVATE)
token = p0
auth = FirebaseAuth.getInstance()
signIn()
}
private fun signIn() {
auth.signInAnonymously().addOnCompleteListener { task ->
if (task.isSuccessful) {
uid = auth.currentUser?.uid.toString()
sp.edit().putString("CURRENT_UID", uid).apply()
sp.edit().putString("CURRENT_TOKEN", token).apply()
FirebaseDatabase.getInstance().reference.child("users").child(uid).child("token")
.setValue(token)
startActivity(
Intent(
this,
MainActivity::class.java
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
}
}
}
private fun sendNotification(payload: Map<String, String>) {
createNotificationChannel()
createNotification(payload)
}
private fun createNotification(payload: Map<String, String>) {
val builder = NotificationCompat.Builder(this)
builder.setSmallIcon(R.drawable.ic_message_not)
builder.setContentTitle(payload["title"])
builder.setContentText(payload["text"])
builder.priority = NotificationCompat.PRIORITY_DEFAULT
builder.setChannelId(Constants.CHANNEL_ID)
val intent = Intent(this, MainActivity::class.java)
val stackBuilder = TaskStackBuilder.create(this)
stackBuilder.addNextIntent(intent)
val resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
builder.setContentIntent(resultPendingIntent)
val notificationManager =
(getSystemService(Context.NOTIFICATION_SERVICE)) as NotificationManager
notificationManager.notify(0, builder.build())
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
val mChannel = NotificationChannel(Constants.CHANNEL_ID, name, importance)
mChannel.description = descriptionText
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
}
Basically, in my Splash Activity I check if it is the first time the user opens the app.
If it is, the login is made from the Service if it is not, the login is made from the Splash Activity.
This is the code for my Splash Activity:
class SplashActivity : AppCompatActivity() {
private lateinit var sp: SharedPreferences
private lateinit var auth: FirebaseAuth
private var flag: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
// If it is first time user enters the app, wait for the MyFirebaseServiceId
// If not, authenticate and sign in (since we already have the token)
sp = getSharedPreferences("FIRST_LOGIN", Context.MODE_PRIVATE)
flag = sp.getBoolean("IS_FIRST_TIME", true)
if (!flag) {
auth = FirebaseAuth.getInstance()
signIn()
}
sp.edit().putBoolean("IS_FIRST_TIME", false).apply()
}
private fun signIn() {
auth.signInAnonymously().addOnCompleteListener { task ->
if (task.isSuccessful) {
sp = getSharedPreferences("AUTH_UID", Context.MODE_PRIVATE)
sp.edit().putString("CURRENT_UID", auth.currentUser?.uid).apply()
getFCMToken()
Handler().postDelayed({
startActivity(Intent(this, MainActivity::class.java))
finish()
}, 2000)
}
}
}
private fun getFCMToken() {
FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener { p0 ->
if (p0.isSuccessful) {
val token = p0.result?.token.toString()
//sp = getSharedPreferences("AUTH_UID", Context.MODE_PRIVATE)
sp.edit().putString("CURRENT_TOKEN", token).apply()
}
}
}
}
What is the problem and why am I not receiving messages all the time?
I faced the same Issue. And It is not the fault of android side.
You can solve this problem by editing notification model/structure by not using any keyword as key,arry name or object name that says notification. Lets say notification {} ===> data{}
NOTE: after doing this you will not receive sounded notice or Automatic notification. You need to manually get the data from the this message and create custom notification using notification manager. Add tittle to it priority and other things...
Doing this you will resolve the problem of notification not being received in background. If you need further assist I can help.

MessagingStyle Not Displaying Text

New to Android development and I’m trying out the latest addHistoricMessage, and I’m missing something because it’s not displaying anything. On rare occasion the addMessage text is displayed, but the addHistoricMessage is never displayed. addMessage works consistently when using NotificationCompat, but NotificationCompat doesn’t appear to have addHistoricMessage.
Any thoughts appreciated - using androidx.appcompat:appcompat:1.0.2 and compileSdkVersion and targetSdkVersion are both 28.
An example of what I’m seeing is:
Test button that calls notification:
fun test(view: View) {
val job = GlobalScope.launch {
val repository = DataRepository.getInstance(Db.getDb(this#MainActivity))
AlarmReceiver().notifyTest(
this#MainActivity,
repository.upcomingDetail(9),
arrayListOf("Hi!", "Miss you!", "Hello!")
)
}
}
Notification methods and related (less important code removed):
fun notifyTest(context: Context, upcoming: UpcomingDetail, top3Sent: List<String>?) {
//...
#TargetApi(Build.VERSION_CODES.P)
when (Build.VERSION.SDK_INT) {
in 1..27 -> {
with(NotificationManagerCompat.from(context)) {
notify(upcoming.id.toInt(), legacyNotificationBuilder(
context,
upcoming,
noteIntent,
contentPending,
disablePending,
deletePending,
postponePending,
top3Sent
).build())
}
}
else -> context.getSystemService(NotificationManager::class.java)
.notify(upcoming.id.toInt(), notificationBuilder(
context,
upcoming,
noteIntent,
contentPending,
disablePending,
deletePending,
postponePending,
top3Sent
).build())
}
}
#RequiresApi(Build.VERSION_CODES.P)
private fun notificationBuilder(
context: Context,
upcoming: UpcomingDetail,
noteIntent: Intent,
contentPending: PendingIntent,
deletePending: PendingIntent,
disablePending: PendingIntent,
postponePending: PendingIntent,
top3Sent: List<String>?
): Notification.Builder {
val recipient: android.app.Person = android.app.Person.Builder().setName("Darren").setImportant(true).build()
val you: android.app.Person? = null
val messageStyle = Notification.MessagingStyle(recipient)
val message1 = Notification.MessagingStyle.Message("Hello!", Instant.now().minusSeconds(10 * 60).toEpochMilli(), recipient)
messageStyle.addHistoricMessage(message1)
messageStyle.addMessage(Notification.MessagingStyle.Message("Hi", Instant.now().toEpochMilli(), recipient))
val remoteInput: android.app.RemoteInput = android.app.RemoteInput.Builder(upcoming.id.toString()).run {
top3Sent?.let { setChoices(top3Sent.toTypedArray()) }
build()
}
//...
val inputAction = Notification.Action.Builder(0, context.getString(R.string.button_edit), inputPending).run {
addRemoteInput(remoteInput)
build()
}
return Notification.Builder(context, "Input").apply {
setSmallIcon(R.drawable.ic_stat)
style = messageStyle
setAutoCancel(true)
setCategory(Notification.CATEGORY_REMINDER)
setColor(ContextCompat.getColor(context, R.color.secondaryDarkColor))
setContentIntent(contentPending)
setDeleteIntent(deletePending)
setGroup("notifications")
setOnlyAlertOnce(true)
setVisibility(Notification.VISIBILITY_PRIVATE)
addAction(inputAction)
}
}
This is the behavior of historic message
Historic message is not normally shown at the notification. It is a special message that is only shown when user is replying through a RemoteInput. See the image above to see the behaviour. It should only be used when the message is not the main subject of the notification but may give context to a conversation.
Reference: Android MessagingStyle Notification As Clear As Possible

Categories

Resources