8

How to Use FCM for Push Notifications - DZone Integration

 2 years ago
source link: https://dzone.com/articles/how-to-use-fcm-for-push-notifications
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Use FCM for Push Notifications and ViewFlipper in Android

Here is a step-by-step guide for using Firebase Cloud Messaging (FCM) for push notifications and ViewFlipper for multiple sliding images in Android.

Join the DZone community and get the full member experience.

Join For Free

I have used Firebase Cloud Messaging (FCM) for push notification and ViewFlipper view component for sliding multiple images in Android. So let’s start the code!

Steps:

1. Create a new project and integrate FCM or another service.

2. Create XML layout notification_image_slider_layoutin which you can add whatever you want to in push notification with multiple sliding images. Here is an example below:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"><TextView
    android:id="@+id/textViewTitle"
    style="@style/TextAppearance.Compat.Notification.Title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/_4sdp" /><ViewFlipper
    android:id="@+id/viewFlipper"
    android:layout_width="match_parent"
    android:layout_height="@dimen/_150sdp"
    android:autoStart="true"
    android:flipInterval="2500"
    android:layout_margin="@dimen/_4sdp"
    android:background="@drawable/drawable_border
    _gray_corner_grey_ligh"
    android:inAnimation="@android:anim/slide_in_left"
    android:outAnimation="@android:anim/slide_out_right" /></LinearLayout>

3. Create another XML layout view_notification_imagefor image in ViewFlipper:

<?xml version="1.0" encoding="utf-8"?>
<ImageView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="@dimen/_150sdp"
    android:contentDescription="@string/app_name"
    android:scaleType="fitXY" />

4. Let’s move on kotlin codeMyFirebaseMessagingServices.kt:

  • In the below code, I have put static images in a MutableList.
class MyFirebaseMessagingServices : FirebaseMessagingService() 
{     val imagesList: MutableList<String> =
     arrayListOf(
                 "https://www.defenceconnect.com.au/images-           backup/Technology/Medical-injections.jpg",
                 "https://image.freepik.com/free-psd/plastic-pill-bottle-with-  colorful-vitamins-mockup_7956-755.jpg",
                 "https://images.squarespace-cdn.com/content/v1/5ab6762de2ccd18f9039391d/1532011051373- 
          ZG46G[…]DbQiz7iBIgNCzklBDD2o6CESiqIlH5ssNFrtmA/image-asset.jpeg")}

5. Create below function setNotificationImageSliderData(notificationTitle, notificatoinMessage, imagesList)

showNotificationSliderData(title,description,imagelist)

private fun setNotificationSliderData(
        title: String, 
        notificationMessage: String?,
        imagesList: MutableList<String>) 
{
     // parent notification layout
     val expandedView = RemoteViews(packageName, R.layout.notification_image_slider_layout)// notification title
 expandedView.setTextViewText(R.id.textViewTitle, title) for (imgUrl: String in imagesList) 
 { 
   //for loop start
   val viewFlipperImage =RemoteViews(packageName, R.layout.view_notification_image)
    if (TextUtils.isEmpty(imgUrl)) 
    { 
        // set default image
        viewFlipperImage.setImageViewResource(
               R.id.imageView,R.mipmap.logo_banner)
     } 
     else 
     {
       try 
       {
          // Below line must not be executed on Mainthread.
          val remotePicture =
          BitmapFactory.decodeStream(URL(imgUrl).content as  InputStream)
          viewFlipperImage.setImageViewBitmap(
                R.id.imageView,remotePicture)       
       } 
       catch (e: IOException) 
       {
          // set default image
         viewFlipperImage.setImageViewResource(R.id.imageView,   R.mipmap.logo_banner)
        }
     }
      // Adding each image view in the viewflipper.
      expandedView.addView(R.id.viewFlipper, viewFlipperImage)
   } // for loop finish   showNotificationForNotificationList(
                         title,
                         notificationMessage!!,
                         expandedView)
}//method finish

Now, show your notification with title, description and expandedView:

showNotificationForNotificationList(title,Description,expandedView)

private fun showNotificationForNotificationList
(
   title: String, 
   notificationDesc: String, 
   expandedView: RemoteViews
)
{
  NotificationUtils.getInstance()?
   .generateBigTextNotificationForNotificationList
  (
     this,
     title,
     getString(R.string.by_) + " " +getString(R.string.app_name),
     Html.fromHtml(notificationDesc,       Html.FROM_HTML_MODE_COMPACT).toString(),
     expandedView
   )
}

generateBigTextNotificationForNotitificationList(context,title,desctiption,expandedView)

fun generateBigTextNotificationForNotificationList
 (
    context: Context,
    notificationTitle: String?,
    notificationMessage: String?, 
    expandedView: RemoteViews
 ) 
 {
     val channelId = "my_channel_id"
     val notification_id = 0
     val bigTextStyle = NotificationCompat.BigTextStyle()
     bigTextStyle.bigText(notificationMessage)
     bigTextStyle.setSummaryText(notificationTitle)
     val builder = NotificationCompat.Builder(context, channelId)
       .setSmallIcon(getNotificationIcon())
       .setLargeIcon(BitmapFactory.decodeResource
           (context.resources, R.mipmap.logo)) // optional
       .setContentIntent(
                 getPendingIntentForNotificationList(context))
       .setContentTitle(notificationTitle)
       .setContentText(notificationMessage)
       .setStyle(NotificationCompat.DecoratedCustomViewStyle())
       .setCustomBigContentView(expandedView)
       .setStyle(bigTextStyle)
       .setPriority(NotificationCompat.PRIORITY_HIGH)
       .setAutoCancel(true)
  getNotificationManager
    (context, 
        channelId
    )!!.notify(notification_id,builder.build())
}

getNotifictionManager(context,channelId)

private fun getNotificationManager
(
   context: Context, 
   channelId: String
): NotificationManager?
{
      val notificationManager =  context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
      {
         val sound =                   RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
         val audioAttributes = AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build()
         val channelName = "MyChannelName"
         val channelDescription ="This is Description of my channel"
         val mChannel = NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_HIGH
            )
          mChannel.setShowBadge(false)
          mChannel.description = channelDescription
          mChannel.enableLights(true)
          mChannel.lightColor = Color.RED
          mChannel.enableVibration(true)
          mChannel.setSound(sound, audioAttributes)
          notificationManager.createNotificationChannel(mChannel)
      }
      return notificationManager
}

Here is the output:

screenshot of output

Notes:

  1. This notification solution support API Level > 16. If you want to support below API Level 16 then call setContent() method of notification with the same remote view object.
  2. Keep your app open to get the notification in the above example. (because I have set the image URLs hard-coded so when you fetch the URLs from the notification then it will work on the background as well).
Topics:
notification, image slider, android, xml, integration, push notifications, firebase cloud messaging

Published at DZone with permission of Nishi Thakkar. See the original article here.

Opinions expressed by DZone contributors are their own.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK