Solution 1 :
Please try to send Data Only Message
instead of Notification Message
. Also, refer to this link: https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages
Solution 2 :
What happen at android end if you send notification key in your payload then onMessageReceived() finction didn’t work, remove that notification key from payload and then try if key not present.
Problem :
I have a php page and I want to send push notification to Android devices.
Here is a php code sample what is working:
<?php
function sendPushNotification($to, $data = array()){
$fields = array('to' => '/topics/' .$to , 'notification' => $data);//, 'android_channel_id' => 'automento_szallitas');
echo $fields['to'];
echo $fields['notification'];
//$headers = array('Authorization: key='.apiKey, 'Content-Type: application/json');
$headers = array('Authorization: key=MY_SECRET_FCM_KEY', 'Content-Type: application/json');
$url = 'https://fcm.googleapis.com/fcm/send';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
echo "ok";
}
$data = array(
'title' => 'title',
'body' => 'body'
);
sendPushNotification("myTopic", $data);
?>
I got the notification for the Android device, when the device screen is open. (Android 11 device) I enabled everything and turned of every energy save mode. I can get notification in few minutes from Firebase console whe a scree is locked till minutes. If I use the php code with a 10 minutes screen lock, de notification doesn’t arrive. I got it inmediatelly when I open the screen.
It seems the front end Android code is ok. I think there is a problem with the back end side php code but I haven’t a clue
***************** Anndroid *********************
Manifest:
<service
android_name=".services.AutomentoFirebaseMessagingService"
android_directBootAware="true"
android_exported="false">
<intent-filter>
<action android_name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Firebase service:
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "Topic message: " + remoteMessage.from)
super.onMessageReceived(remoteMessage)
val powerIntent = Intent(Intent.ACTION_POWER_CONNECTED)
context?.sendBroadcast(powerIntent)
wakeUpScreen()
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
REQUEST_CODE, intent, PendingIntent.FLAG_ONE_SHOT
)
val channelId = getString(R.string.default_notification_channel_id)
val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_rendeleseim_white_48)
.setContentTitle(remoteMessage.notification!!.title)
.setContentText(remoteMessage.notification!!.body)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setLights(Color.RED, 500, 500)
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
channelId,
"Pushnotification",
NotificationManager.IMPORTANCE_HIGH,
).apply {
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
}
notificationManager.createNotificationChannel(channel)
val notification = notificationBuilder.build()
notification.flags = notification.flags or Notification.FLAG_INSISTENT
notificationManager.notify(REQUEST_CODE, notification)
}
private fun wakeUpScreen() {
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
val isScreenOn: Boolean = powerManager.isInteractive
if (!isScreenOn) {
val wakeLock: PowerManager.WakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MentoMano::WakelockTag").apply {
acquire(1000)
}
}
}
val pm = baseContext.getSystemService(POWER_SERVICE) as PowerManager
val isScreenOn2 = pm.isInteractive // check if screen is on
if (!isScreenOn2) {
val wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "myApp:notificationLock")
wl.acquire(3000) //set your time in milliseconds
}
}
fun subscribeToTopic() {
val userId = sharedPreferences?.getInt(Constants.SHARED_USER_ID, -1)
if (userId != -1) {
val topic = "user$userId"
FirebaseMessaging.getInstance().subscribeToTopic(topic)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "subscribeToTopic: sikeres feliratkozás $topic")
AutomentoController().updateToken(userId!!, topic)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
Log.d(TAG, "onCreate: token update success: ${response.success} | response: ${response.message}")
},{
})
} else {
Log.d(TAG, "subscribeToTopic: hiba a feliratkozás során")
}
}
}
}
Help please
Comments
Comment posted by Bharat Kumar
Post your Android code, it seems like you have issues there. Just as a reminder, hope you have your service defined in manifest…..
Comment posted by Seng Phrakonkham
@BharatKumar: I edited the description and Added the Android side.
Comment posted by stackoverflow.com/a/69709309/2404262
Have you tried
Comment posted by Arul
Have you checked the notifications that come in a lower android version?
Comment posted by Seng Phrakonkham
I tried. But on Android the data message didn’t arrived