Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] FCM notification arrives only user opens the device screen (Android 11) in PHP

Posted on November 11, 2022 By

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

READ  [FIXED] Android WebView skip deeplinks
Powered by Inline Related Posts

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

Android Tags:android, firebase-cloud-messaging, php, push-notification

Post navigation

Previous Post: [FIXED] android – How to detect when third party app’s dialog box appears in React native?
Next Post: [FIXED] android – Get the list of user SIM cards and select it – flutter

Related Posts

[FIXED] Android Gradle Read timed out Android
[FIXED] android – RecyclerView item get deforme as keyboard pop up Android
[FIXED] java – How to read files from external storage specific folder in android scope storage Android
[FIXED] android – How can I use FragmentFactory with FragmentStatePagerAdapter Android
[FIXED] android – Programmatically added TextInputLayout not showing the Outline Box Android
[FIXED] xamarin.forms – Xamarin FilePicker blocks UserDialog Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What is the rising action in Julius Caesar?
  • How do you secure a rope to itself?
  • Does waterproof laminate scratch easily?
  • What makes a building prewar?
  • What can you learn in a month without alcohol?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme