0

Hi there. I practiced the FCM messaging, but it fails to send a message. I made based on Google Code, and yet I was reading it, but the server does not send the message and the base console can fire only once. Can anyone help? Here are the codes!

MainActivity:

public class MainActivity extends AppCompatActivity {

        static Context context;
        static TextView token;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            context = getApplicationContext();
            token = (TextView) findViewById(R.id.token);
        }
    }

FCMMessagingService

public class FCMMessagingService extends FirebaseMessagingService {

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();

            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 10, intent, PendingIntent.FLAG_ONE_SHOT);
            Notification notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .build();
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notificationBuilder);



            super.onMessageReceived(remoteMessage);
        }
    }

FCMInstanceIdService

public class FCMInstanceIdService extends FirebaseInstanceIdService {

        public static final String TOKEN = "token";
        @Override
        public void onTokenRefresh() {
            super.onTokenRefresh();
            String token = FirebaseInstanceId.getInstance().getToken();

            SharedPreferences sp = getApplicationContext().getSharedPreferences(TOKEN, Context.MODE_PRIVATE);
            sp.edit().putString(TOKEN, token).commit();
            Log.d("TOKEN_NO: ", token);
        }
    }

Manifest

<service android:name=".FCMInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <service android:name=".FCMMessagingService">
        <intent-filter>
            <action android:name="com.google.firabase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

Project .gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module .gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "hu.penged.cloudmessage"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'
}
apply plugin: 'com.google.gms.google-services'

..And server.php...

<?php
    $server_key = "AIzaSyA4ahv6z05t4sbSOZDkw5pX-5EvOHA7zfA";
    $adress = "enI7T1-U69o:APA91bHLnlAOJxg8kebr7GcpoVqBf__EHXADofEG-rQiGH60fH3HstCk9BroxoBXjlFEzKJoln-ghATjlcyo4UiCmyDjTeKOKG7NHY1ADiwWxxhg3tvBdWc2J_PbMM0wzKjjpDpgDk6x";
    $fcm_server_url = "https://fcm.googleapis.com/fcm/send";

    $title = utf8_encode("Notification Test");
    $content_text = utf8_encode("Notification message.");

    $httpheared = array("Content-Type:application/json", "Authorization:key=".$server_key);

    $post_content = array("to" => $adress, "notification" => array("title" => $title, "body" => $content-text));

    $curl_connection = curl_init();
    curl_setopt($curl_connection, CURLOPT_URL, $fcm_server_url);
    curl_setopt($curl_connection, CURLOPT_POST, true);
    curl_setopt($curl_connection, CURLOPT_HTTPHEADER, $httpheared);
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_connection, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($curl_connection, CURLOPT_POSTFIELDS, json_encode($post_content));
    $valasz = curl_exec($curl_connection);
    curl_close($curl_connection);

    echo $valasz;
    ?>

Thank you very much for your help!!!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Pengewap
  • 11
  • 4
  • Your code seems to be Ok. But I have a couple of questions: when you say: "base console can fire only once" do you mean that the `onMessageReceived` method is only fired when you send messages from the firebase console?. When you say that: "the server does not send the message" How do you know that the server is not sending the message?. What's the response that you get in the `$valasz` variable?. Also I recommend you to hide the `$server_key` in the code you have posted because is private (only you should know it). – GeorgeLBA Aug 24 '16 at 07:24
  • HI. The first question is: When I tested the transmission of the FireBase Console / Messaging page, the first message arrived. Then I sent another one, but it did not come, although he wrote that "Completed" can be sent. But it did not come to your mobile. Second question: From think, because I do not get it. $valasz: {"multicast_id":7567254682798060374,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1472043288834429%7564307a7564307a"}]} The $server_key not relevant if you see because you only need to test! will be deleted, so thanks! Do you have any ideas? Thanks! – Pengewap Aug 24 '16 at 13:01

1 Answers1

0

Try to do the following: In your server.php script instead of notification param use data. So it will be: "data" => array("title" => $title, "body" => $content-text) And in your onMessageReceived method get the param with: remoteMessage.getData().get("title"); and the same code for the other param with the key "body".

Also check if your onMessageReceived method is being called when the mobile device receives the notification.

Hope this helps!

GeorgeLBA
  • 334
  • 1
  • 3
  • Unfortunately, it did not help. – Pengewap Aug 25 '16 at 18:00
  • @Pengewap When you send the notification from your own server in PHP, the `onMessageReceived` method is called?. To check it try to add a `Log.d("Your APP TAG","A MESSAGE")` in that method just to see if that method is being called. – GeorgeLBA Aug 26 '16 at 07:03
  • Hello. Until then it reached that the messages did not come because it was aa App in the foreground or in the background. It can only come to the notice, if the app is not running all the time being. However, I should Notification was obtained when the program is running in the foreground, at least in the example code. – Pengewap Aug 27 '16 at 12:53
  • @Pengewap if I understood correctly do you want to handle the notifications only when your app in in foreground? – GeorgeLBA Aug 27 '16 at 13:25
  • Hello. Yes, because I realized the problem was that the program is running in the foreground, it does not see the message. If you are running in the background you will see the message. – Pengewap Aug 28 '16 at 16:35
  • @Pengewap I have tested with an application that I have and when my application is in foreground the onMessageReceived method is also called and the notification is loaded in the system tray. When I click on the notification in the system tray I lunch an anctivity that shows the notification. When my application is in background the onMessageReceived method is also called and the notification appears in the system tray. Also check [this thread] (http://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase). I hope this helps. – GeorgeLBA Aug 30 '16 at 08:34
  • Hello After much reading sessions to help them. Thanks for all the help. :-))) – Pengewap Aug 31 '16 at 17:17