GetStream / stream-chat-android

:speech_balloon: Android Chat SDK ➜ Stream Chat API. UI component libraries for chat apps. Kotlin & Jetpack Compose messaging SDK for Android chat
https://getstream.io/chat/sdk/android/
Other
1.47k stars 273 forks source link

Clicking on push notification wont open the Application #4837

Closed SSaleemSSI closed 1 year ago

SSaleemSSI commented 1 year ago

While receiving the push notification from stream using firebase config, Push notification shows correctly but Upon clicking Nothing happens it wont open the App, I also enabled the notification as in docs. I tried using custom handler class in ChatInitializer as

val notificationHandler = MyNotificationHandler(context)
 val notificationConfig =
            NotificationConfig(
                pushDeviceGenerators = listOf(
                    FirebasePushDeviceGenerator(),
                ),
                requestPermissionOnAppLaunch = { true }
            )
 val client = ChatClient.Builder(apiKey, context)
            .loggerHandler(FirebaseLogger)
            .notifications(notificationConfig, notificationHandler)
            .logLevel(logLevel)
            .withPlugin(offlinePlugin)
            .debugRequests(true)
            .build()

class MyNotificationHandler(private val context: Context) : NotificationHandler {
    private val notificationManager: NotificationManager by lazy {
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    }

    override fun onNotificationPermissionStatus(status: NotificationPermissionStatus) {
        when (status) {
            NotificationPermissionStatus.REQUESTED -> {
                // invoked when POST_NOTIFICATIONS permission is requested
            }
            NotificationPermissionStatus.GRANTED -> {
                // invoked when POST_NOTIFICATIONS permission is granted
            }
            NotificationPermissionStatus.DENIED -> {
                // invoked when POST_NOTIFICATIONS permission is denied
            }
            NotificationPermissionStatus.RATIONALE_NEEDED -> {
                // invoked when POST_NOTIFICATIONS permission requires rationale
            }
        }
    }

    override fun showNotification(channel: Channel, message: Message) {

        val intent = Intent(context, BaseActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        Toast.makeText(context,"",Toast.LENGTH_LONG).show()
        val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT)
// channel id, channel name
        var builder: NotificationCompat.Builder =
            NotificationCompat.Builder(context,
                "io.thetie.terminal"
            )
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
                .setContentIntent(pendingIntent)
        notificationManager.notify(0, builder.build())
    }

    override fun dismissChannelNotifications(channelType: String, channelId: String) {
        // Dismiss all notification related with this channel
    }

    override fun dismissAllNotifications() {
        // Dismiss all notifications
    }
}

I also have tried using my own notifications sending through firebase console when i click on those using same code App opens.

SDK version

To Reproduce Steps to reproduce the behavior:

  1. Go to background of application
  2. Click on Notification from dropdown menu
  3. Nothing happens

Expected behavior App should be open upon clicking the notification

Device:

Screenshots If applicable, add screenshots to help explain your problem.

JcMinarro commented 1 year ago

The problem looks like is caused because the PendingIntent you are creating. The PendingIntent is the one that the Anadroid OS will launch when the notification is clicked, and starting on Android 12 new flags needs to be added to the PendingIntent. Here you can see how the PendingInent is created in our internal implementation.

SSaleemSSI commented 1 year ago

I also implemented streams provided Styler Handler (MessagingStyleNotificationHandler) through NotificationHandlerFactory.createNotificationHandler as below

  val notificationHandler= NotificationHandlerFactory.createNotificationHandler(
            context = context,
            newMessageIntent = {
                    messageId: String,
                    channelType: String,
                    channelId: String,
                ->
                HostActivity.createLaunchIntent(context, messageId, channelType, channelId)
            }
        )

   companion object {

        fun createLaunchIntent(
            context: Context,
            messageId: String,
            channelType: String,
            channelId: String,

        ) = Intent(context, BaseActivity::class.java).apply {
            putExtra(EXTRA_CHANNEL_ID, channelId)
            putExtra(EXTRA_CHANNEL_TYPE, channelType)
            putExtra(EXTRA_MESSAGE_ID, messageId)
        }
    }
 val client = ChatClient.Builder(apiKey, context)
            .loggerHandler(FirebaseLogger)
            .notifications(notificationConfig, notificationHandler )
            .logLevel(logLevel)
            .withPlugin(offlinePlugin)
            .debugRequests(true)
            .build()

But this also doesn't trigger the intent.

JcMinarro commented 1 year ago

Hello @SSaleemSSI Could you provide the logcat after the PN is clicked? If you try to launch the Intent created at HostActivity.createLaunchIntent() from another part of your app, is it starting your BaseActivity properly??

SSaleemSSI commented 1 year ago

Hi @JcMinarro Yes base activity is launching on click when i create intent using HostActivity.createLaunchIntent and send notification from firebase test on device token. here are the logs when notification is received and clicked

2023-06-05 13:02:46.843  7737-8572  FirebaseMessaging       io.thetie.terminal                   W  Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
2023-06-05 13:02:46.858  7737-8573  FA                      io.thetie.terminal                   V  Connecting to remote service
2023-06-05 13:02:46.869  1269-11979 ApplicationPolicy       system_server                        D  isStatusBarNotificationAllowedAsUser: packageName = io.thetie.terminal,userId = 0
2023-06-05 13:02:46.870  1269-11979 ApplicationPolicy       system_server                        D  isStatusBarNotificationAllowedAsUser: packageName = io.thetie.terminal,userId = 0
2023-06-05 13:02:46.875  7737-8573  FA                      io.thetie.terminal                   D  Connected to remote service
2023-06-05 13:02:46.877  7737-8573  FA                      io.thetie.terminal                   V  Processing queued up service tasks: 1
2023-06-05 13:02:47.092  1269-1269  AccessibilityManager    system_server                        I  semStartFlashNotification notitype = null, getOpPackageName = android, sbnPackageName = io.thetie.terminal
2023-06-05 13:02:47.092  1269-1269  Accessibil...gerService system_server                        I  semStartFlashNotificationInner() type=Default, pkgName=android, token=android.os.Binder@c5a87d1, sbnPkgName=io.thetie.terminal, previewType=0
2023-06-05 13:02:47.095  1269-1269  NotificationService     system_server                        D  0|io.thetie.terminal|0|FCM-Notification:229189335|10296: granting content://settings/system/notification_sound
2023-06-05 13:02:47.096  1269-1269  NotificationService     system_server                        D  0|io.thetie.terminal|0|FCM-Notification:229189335|10296: granting content://settings/system/notification_sound
2023-06-05 13:02:47.098  1269-1269  NotificationService     system_server                        D  0|io.thetie.terminal|0|FCM-Notification:229189335|10296: granting content://settings/system/notification_sound
2023-06-05 13:02:47.100  1269-1269  NotificationService     system_server                        D  0|io.thetie.terminal|0|FCM-Notification:229189335|10296: granting content://settings/system/notification_sound
2023-06-05 13:02:47.104  1269-1269  NotificationService     system_server                        D  0|io.thetie.terminal|0|FCM-Notification:229189335|10296: granting content://settings/system/notification_sound
2023-06-05 13:02:47.116  1269-1269  NotificationReminder    system_server                        D  addNotificationRecord record io.thetie.terminal
2023-06-05 13:02:47.123  2013-2013  Launcher.N...onListener com.sec.android.app.launcher         I  onNotificationPosted : io.thetie.terminal number : 0
2023-06-05 13:02:47.123  2013-2236  Launcher.N...onListener com.sec.android.app.launcher         I  notificationIsValidForUI : io.thetie.terminal missingTitleAndText : false isGroupHeader : false
2023-06-05 13:02:47.124  1623-1623  Interrupti...teProvider com.android.systemui                 D   no Heads up : edgelighting enabled app. 0|io.thetie.terminal|0|FCM-Notification:229189335|10296
2023-06-05 13:02:47.124  2013-2013  IconView                com.sec.android.app.launcher         I  applyDotState itemInfo : Terminal display : 1 count : 1
2023-06-05 13:02:51.896  7737-8573  FA                      io.thetie.terminal                   V  Inactivity, disconnecting from the service
2023-06-05 13:02:57.140  2013-2236  Launcher.N...onListener com.sec.android.app.launcher         I  notificationIsValidForUI : io.thetie.terminal missingTitleAndText : false isGroupHeader : false
2023-06-05 13:02:57.141  2013-2013  PopupDataProvider       com.sec.android.app.launcher         I  refresh badge  package : io.thetie.terminal count : 1
2023-06-05 13:02:57.148  2013-2013  IconView                com.sec.android.app.launcher         I  applyDotState itemInfo : Terminal display : 1 count : 1
2023-06-05 13:02:59.792  7737-8606  thetie.terminal         io.thetie.terminal                   W  Accessing hidden field Lcom/android/okhttp/internal/huc/DelegatingHttpsURLConnection;->delegate:Ljava/net/HttpURLConnection; (blocked, reflection, denied)
2023-06-05 13:02:59.792  7737-8606  thetie.terminal         io.thetie.terminal                   W  Accessing hidden field Ljava/net/URLConnection;->requests:Lsun/net/www/MessageHeader; (max-target-o, reflection, denied)
2023-06-05 13:02:59.792  7737-8606  thetie.terminal         io.thetie.terminal                   W  Accessing hidden field Ljava/net/URLConnection;->requests:Lsun/net/www/MessageHeader; (max-target-o, reflection, denied)
2023-06-05 13:03:03.305  1269-1294  ChimeraSys...ntListener system_server                        I  appLaunchIntent package name is: io.thetie.terminal
2023-06-05 13:03:03.305  1269-1579  ActivityTaskManager     system_server                        I  START u0 {act=OPEN_ACTIVITY_1 flg=0x14000000 pkg=io.thetie.terminal (has extras)} from uid 10296
2023-06-05 13:03:03.306  1269-1579  ActivityManager         system_server                        D  Received ACTIVITY intent 0xc139072 Key{startActivity pkg=io.thetie.terminal intent=act=OPEN_ACTIVITY_1 flg=0x14000000 pkg=io.thetie.terminal flags=0x44000000 u=0} requestCode=1735082233 res=-91 from uid 10079
2023-06-05 13:03:03.313  1623-1623  SystemUIAnalytics       com.android.systemui                 D  sendEventLog , , type, normal, priority, alert, information, io.thetie.terminal ; 0 ; fcm_fallback_notification_channel ; null ; 3
2023-06-05 13:03:03.320  1269-1269  EdgeLightingManager     system_server                        D  hideForNotification : packageName = io.thetie.terminal
2023-06-05 13:03:03.320  1269-1269  EdgeLighti...ationGroup system_server                        D  remove : sbn : StatusBarNotification(pkg=io.thetie.terminal user=UserHandle{0} id=0 tag=FCM-Notification:229189335 key=0|io.thetie.terminal|0|FCM-Notification:229189335|10296: Notification(channel=fcm_fallback_notification_channel shortcut=null contentView=null vibrate=null sound=null defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0))
2023-06-05 13:03:03.324  1269-1269  NotificationReminder    system_server                        D  removeFromNotiList record io.thetie.terminal
2023-06-05 13:03:03.326  2013-2013  IconView                com.sec.android.app.launcher         I  applyDotState itemInfo : Terminal display : 1 count : 0
2023-06-05 13:03:08.460  7737-8625  thetie.terminal         io.thetie.terminal                   W  Accessing hidden field Lcom/android/okhttp/internal/huc/DelegatingHttpsURLConnection;->delegate:Ljava/net/HttpURLConnection; (blocked, reflection, denied)
2023-06-05 13:03:08.460  7737-8625  thetie.terminal         io.thetie.terminal                   W  Accessing hidden field Ljava/net/URLConnection;->requests:Lsun/net/www/MessageHeader; (max-target-o, reflection, denied)
2023-06-05 13:03:08.460  7737-8625  thetie.terminal         io.thetie.terminal                   W  Accessing hidden field Ljava/net/URLConnection;->requests:Lsun/net/www/MessageHeader; (max-target-o, reflection, denied)
JcMinarro commented 1 year ago

Are you using any custom FirebaseMessagingService? I can't see any Chat: tag in your log, it looks like something is handling the Push Notification and it is not forwarding to our SDK. On the case you are using your own FirebasemessagingService, are you using our FirebaseMessagingDelegate class to delegate the PN handling process?? Could you verify the newMessageIntent lambda you provide to the NotificationHandlerFactory is being called? Could you add some logs there?

SSaleemSSI commented 1 year ago

Yes i am using custom firebase messaging and i am using your firebaseMessagingDelegate class to handle the process. The reason you cant see any Chat: logs because i am using my own custom NotificationHandler (code given above), i have also tried removing my service and all custom classes but still no luck. I put some logs in newMessageIntent is not being called when app is in the background and notification received, but when i am in the app and on another tab and new message is received it generate the notification because of my custom implementation and when i close the app and click on that generated notification it opens the activity but not in case when notification is received when app is in background. let me share a video in next comment.

  <service
            android:name="io.thetie.terminal.ui.messaging.NotificationHandlers.MessagingServiceFireBase"
            android:exported="true"
            >
            <intent-filter android:priority="0">
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
class MessagingServiceFireBase : FirebaseMessagingService() {
     override fun onNewToken(token: String) {
        // Update device's token on Stream backend
        try {
            registerFirebaseToken(token, "optional-provider-name")
        } catch (exception: IllegalStateException) {
            // ChatClient was not initialized
        }
    }

  override fun onMessageReceived(remoteMessage: RemoteMessage) {
        try {
            if (handleRemoteMessage(remoteMessage , applicationContext)) {

            } else {

                Log.e("remoteMessage", "" + remoteMessage.notification)
                if (remoteMessage.getNotification() != null) {
                    generateNotification(
                        remoteMessage.notification!!.title!!,
                        remoteMessage.notification!!.body!!
                    )
                }
                // RemoteMessage wasn't sent from Stream and it needs to be handled by you
            }
        } catch (exception: IllegalStateException) {

            // ChatClient was not initialized
        }
    }

private fun generateNotification(title: String, message: String) {
        val contentPendingIntent = PendingIntent.getActivity(
            applicationContext,
            123,
            HostActivity.createLaunchIntent(applicationContext,"","",""),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
  var builder: NotificationCompat.Builder =
            NotificationCompat.Builder(applicationContext, channelId)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
                .setContentIntent(contentPendingIntent)
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(notificationChannel)
        }
        notificationManager.notify(0, builder.build())
      }
}
SSaleemSSI commented 1 year ago

https://github.com/GetStream/stream-chat-android/assets/86655959/81bbd16c-7855-464d-bef9-7186aa3b7c95

JcMinarro commented 1 year ago

Ok, It looks like you are using "template PN" which is not supported by our SDK because Firebase SDK bypasses our SDK implementation when the app is in the background.

Could you go to the Stream Dashboard and verify you are not using the legacy PN Integration? Here are the docs section to configure Firebase in our SDK.

SSaleemSSI commented 1 year ago

Yes i am using legacy PN integration, i followed the same docs to config them but i was unable to find the Firebase menu as it was on docs. Looks like i wasn't upgraded to v2 on development channel, I have done the upgrade. But now i have stopped receiving the notifications. I did same settings as written in the docs.

Screenshot 2023-06-05 at 3 33 12 PM
SSaleemSSI commented 1 year ago

Error on dashboard says,

Screenshot 2023-06-05 at 4 50 33 PM

i double check the keys and settings. Couldn't figure out why notifications aren't receiving.

JcMinarro commented 1 year ago

When you use Push Notification V2, you need to add a name to your configuration and use this same name when you configure PN. It is the "Push Provider Name" that is used across our classes. Could you review if you are adding it when you create the list of PushDeviceGenerators and when you are using our FirebaseMessagingDelegate?

FirebasePushDeviceGenerator(providerName = "your-push-provider-config-name")

// And

FirebaseMessagingDelegate.registerFirebaseToken(token, "your-push-provider-config-name")
SSaleemSSI commented 1 year ago

Alright, Yes Names were missing, Now push Notifications are working and click action is also working fine. Thanks. 👍

JcMinarro commented 1 year ago

Cool!!!! Happy to hear it. I am closing this issue, but feel free to open a new one if you have any other issue or doubt

SSaleemSSI commented 1 year ago

Hi - @JcMinarro i am facing an issue with notifications banner isn't showing for notifications instead sound and icon is showing and in tray banner is also visible but new message comes with no banner notification. is there any config for that as well? i have turned on the banner notification form settings as well.