How to attach an extra to an Pass Object <ModelObject> from Retrieving Activity or Fragment to Bundle to Intent/PendingIntent in a Notification in Firebase [“Firebase Android Kotlin”]
One option could be letting your custom class implement the Serializable
interface and then you can pass object instances in the intent extra using the putExtra(Serializable..)
variant of the Intent#putExtra()
method.
This is an example of passing Object, ArrayList as a bundle.
It is also possible to pass your custom object to other activities using the Bundle
class.
There are two ways:
Serializable
interface—for Kotlin and Android. for exampleParcelble
interface— Parcelable processing is much faster than serializable. One of the reasons for this is that we are being explicit about the serialization process instead of using reflection to infer it. It also stands to reason that the code has been heavily optimized for this purpose
You can see detail under link to got here
if you doubt you can see video this “Serialization performance (Android Performance Patterns Season 4 ep14) “ For you to understand
Let’s go !!!
Step 1 : Create code for the (Serializable) Item class data model.
Step 2 : Then got deta model strep two Create class Notification from firebase Can create, wait you can must doc google firebase
This section will retrieve the data that the firebase sent to you using remoteMessage? .Data. this mean So you have to parse each and every field as per your response. As I have debugged the code you will receive map in your RemoteMessage and cast those fields in appropriate data types as all those data comes as string.
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
// TODO(developer): Handle FCM messages here.if(isAppIsInBackground(getApplicationContext())) {
// Show the notification
val notification = remoteMessage?.notification
val data = remoteMessage?.data
sendNotificationAlert( data!!)
} else {
// Don't show notification
}
}
And later will use the data that is received from remoteMessage In which the author sets the data value to Eample {Object}
/****
*
* {body=ABC Inactive, obid=5ee05d7382400108, type=alert, title=Monitor Alert}
*
* {body=Test2 for ABC, obid=5ee07a0398270010, type=outbound, title=**Revise** : Test2-0001/2020}
*
The default value that firebase sends data to is Map <String, String>. We have to convert it to model obejct first. We will use Gson to help with the conversion and try to test the value. Come first that The data is the same as what the object was called or not, as in the example.
val propertiesOfMap = data?.toProperties()
val gson = Gson()
var dataConvet = gson.toJson(propertiesOfMap).toString()
Log.e("listConsultantModel data ",gson.toJson(propertiesOfMap).toString())
Use forEach Function Kotlin to show the (key and .value ) values and log the value. Data to see if we are maping.
// Traverse through propertiesOfMap
propertiesOfMap?.forEach{(k, v) ->
Log.e("listConsultantModel propertiesOfMap ","key=$k, value=$v")
}
When the data is complete, it will convert json to map in the. Model that created the .class model from the beginning. To come out in the Gson format. Using commands gson.fromJson transforms as in the example
val itemType = object : TypeToken<ResponseAlertNoti>() {}.type
var listConsultantModel = gson.fromJson<ResponseAlertNoti>(dataConvet, itemType)
Log.e("listConsultantModel title",listConsultantModel.title)
and next stap
Passing Objects as serializable
Taking the obtained value. maping to Gson has been used by calling through putSerializable is to pass the objectmodel to the class you want to call. In this case, the author will send to the class main actvity again, but in passing another class We will use the intent statement. The main thing is to send it through MainActivity always. In Intent we will send it. Send addFlags as FLAG_ACTIVITY_CLEAR_TOP.
Using Bundle to help it make easier
You should have noticed, this is a not so cool and easy way to send quite a number of items. This is where we use Bundles. Bundle is a mapping from String keys to various parcelable values. We can store any number of key-value pairs in a Bundle object and simply pass this object through the intent.
Use the Bundle to send under putExtras using putSerializable. As in the picture, ready to run pendingIntent. In order to bind to the Notification function
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
var bundle = Bundle();
bundle.putSerializable("AlertNotiModel", listConsultantModel);
intent.putExtras(bundle);val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
And after that, call Method to send Notification value straight away Wowww
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder = NotificationCompat.Builder(this, "channel_id")
.setContentTitle(data?.get("title"))
.setContentText(data?.get("body"))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
// .setContentInfo(notification.title)
.setLargeIcon(icon)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorRed))
.setLights(ContextCompat.getColor(applicationContext, R.color.colorRed), 1000, 300)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.mipmap.ic_launcher)
try {
val picture_url = data["picture_url"]
if (picture_url != null && "" != picture_url) {
val url = URL(picture_url)
val bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream())
notificationBuilder.setStyle(
NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(data?.get("body"))
)
}
} catch (e: IOException) {
e.printStackTrace()
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Notification Channel is required for Android O and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT
)
channel.description = "channel description"
channel.setShowBadge(true)
channel.canShowBadge()
channel.enableLights(true)
channel.lightColor = Color.RED
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0, notificationBuilder.build())
}
If in doubt, the operation step can see the sample code provided immediately.
Retrieving data from intent
Once you start the activity, You’ll be able to get the data attached in the next activity [or services, broadcast receivers.. etc] being started. to retrieve the data, we use the method getExtra()
to getSerializable() on the NextActivity from the intent.
if (intent.extras != null) {
var bundle = intent.extras
obid = bundle?.getString(MessageProperties.OBID)
bundleDeepLink = bundle.getBundle(MessageProperties.PARAM)
if(bundle.getSerializable("AlertNotiModel") != null) {
val alertNotiModel = bundle.getSerializable("AlertNotiModel") as ResponseAlertNoti
alertNotiModel.let {
SharePreference.WriteNotiType(it.type!!, this)
SharePreference.WriteNotiObid(it.obid!!, this)
}
}
The following example will show you how to use getExtra() =>getSerializable() Model Object on the target activity is started.
And Run Again Checking code
Please add group
https://discord.com/invite/tm9XXgv
- Who does not answer questions, press delete all cases.
- Incomplete answers are also deleted.
- Accepting only people, not accepting pages
Impolite, illegal, erased and banned
- Account / Avatar account.
- No need to join a group. Catch, delete, only one location.
- Do not advertise for work Job .
- This group is sharing knowledge, not sharing nonsense.
- Thank you to member All.
- Thank you for the add later
Pm.
If you understand Please reply with If not, then you will be deleted.
//admin 😁😁😁
JoinGroup : https://discord.com/invite/tm9XXgv
And
I created a group of Android Developers Android and Kotlin Droidcon Github library. If you have any questions, you can ask. You can join in the App Telegram. Now join Android Developers And Kotlin Droidcon
Android Developers And Kotlin Droidcon Github Library
Thank you for joining: https://www.facebook.com/groups/883546485084033/?fref=ts I created a group of Android Developers Android and Kotlin Droidcon Github library. If you have any questions, you can ask. You can join in the App Telegram. https://t.me/joinchat/IhB5KQ0aXC7ckNgjRaBaCw Now join Android Developers And Kotlin Droidcon Github Library Community Telegram App to help each other. Joining Link:
PongPloy Zone AppDev
Link : https://www.facebook.com/PPAndroid-Github-Dev-Zone-170227463027435/notifications/
Part 1: [Great] Interesting Android Library — April 2017 for Android GitHub Developer Library
Part 2: [Popular] Android library May — September ( cobeisfresh ) 2017 for Android GitHub Developer Library
Part 3: Lovely Android Library May — September ( cobeisfresh ) 2017 for Android GitHub Developer Library
Part 3: [Top 40] Featured Android Library — September 2017 For Android Developers GitHub
Part 5: [50Top] Awesome Android Libraries — February March April 2018 Android Developer Library GitHub
Part 6: [Include 61 Libraries All for 2018 ] Awesome Android Libraries — 2018 October — December Android Developer Library GitHub