Firebase Cloud Messaging Push Notifications using the Android, PHP, MYSQL PART 1/2

Firebase Cloud Messaging Push Notifications using the Android, PHP, MYSQL PART 1/2
Firebase Cloud Messaging (FCM) is the new version of Google Cloud Messaging (GCM). In this tutorial we take a look at implementation of the push notifications.

Second part:

Firebase console:

Additional dependencies:
    compile 'com.google.firebase:firebase-messaging:9.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'

Github project:

☑ Visit fb page: 

RRelated Posts

Primeros pasos con Firebase

En este videotutorial conoceremos qué es Firebase y diversos conocimientos básicos relacionados con este sistema. Explicaremos qué te aporta Firebase y cuál es el tipo de aplicaciones que se

Intro to Web Push & Notifications

With service workers, push notifications are now available on the web. This video explains the Notifications API and the Push API, and how they are used to implement push notifications in Progressive


  • Alex1tmacthebestnba
    Has anyone fixed the problem that the token isn't being inserted into the database?
  • khalil ben zineb
    Saved my day :)
  • bartdereu
    My god, google, what did you mess up ???!!
  • prasad shinde
    i m not getting the token. i tried to put the wamp on internet also opened new port with changes into that url code. still not getting that token. have used the latest versions of dependencies.
  • 96-Bit Orbital
    For those who don't see their database updated, try the following (which solved the issue for my case):

    1) Make sure that you are running on an emulator (since your are running on local server).
    2) Check if you have successfully connected to the database. A simple way to check would be to include the following code above if ( isset(...) ) :

    if ($conn) {
    echo "Success";
    } else {
    echo "Failed";

    3) If "http://localhost/fcm/register.php" doesnt work, change it to "http://********/fcm/register.php" where ******* is replaced by your IP.
    How to access your IP ?
    Go to command prompt -> type "ipconfig" without the bracket -> retrieve the number from the category "Wireless LAN adapter WI-FI:" on line "IPv4 Address"

    Make sure you uninstall your app on your EMULATOR before you test again.
  • Sergey Abaev
  • Level Max
    Parabéns pelo vídeo !
  • Suman Sarkar
    if anyone having error on not saving registration token into database can use this code on MyFireBaseInstanceIDService
    private void registerToken(String token){
    OkHttpClient client = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
    Request request = new Request.Builder()
    try {
    } catch (IOException e){

  • mark laurence bachiller
    Cant see my Token in my Database. Dont know whats wrong maybe the Ip address of my net or laptop?
    But I managed to see. I add a Textview in Layout and Set the token as String. heres the sample
    -- Main Activity--
    public class MainActivity extends AppCompatActivity {
    TextView textView;

    protected void onCreate(Bundle savedInstanceState) {

    textView = (TextView) findViewById(R.id.textView);
    String tok;


    tok = FirebaseInstanceId.getInstance().getToken();


    ---- in Layout activity_main .xml--
    android:text="Hello World!"
    app:layout_constraintTop_toTopOf="parent" />

    Hope it works for them :D
  • mahmoud saad
    Dears if any one has problem of inserting key inside the database , make sure from your script link inside the okhttp to be like that http://IPv4 Address/filename
    how to do for https?
  • priyanka argade
    Great tutorial,,,,tysm
  • Kamran Haider
    I have this Error message that Failed to Resolve :com.google.firebase:firebase-messaging:10.2.1
    please can any one help me to resolve this problem.
    i want to push notification only whene the app is closed or playing on the background, is it possible?
  • Oscar Torres
    where I save the php package?
  • aasqw asdqwdqwd
    for those who aren't able to generate token check your internet connection in your emulator or build apk and test it on your phone
  • Prashant Dhameliya
    Thanks for nice explanation. can we use FCM for ios notification ? can you share video for that ?
  • Shailendra Dadhiya
    Working as shown in video ... thanks :)
  • Fahad khAn
    Error:Could not download okhttp.jar (com.squareup.okhttp3:okhttp:3.2.0): No cached version available for offline mode
  • Vrutin Tarunchandra
    Good clear explanation.
  • Saiful Hasan
    hehehheheeh i am able to insert token in my db after 2 hours. Those whose token is generated but not inserted in database are advised to see their manifest file. Put the services tad inside the application. Cross check your manifest with Filip Mainifest.
  • Vitaliy D.
    The lesson is good. English is terrible.
  • Waheed Ahmed
    How to Get Notification When onChildChanged() I mean When we receive new
    Data in the Firebase Database ..?? Reply Fast As You can
  • Tapiwanashe Blessing Zvidzwa
    Tried this, it ddnt work. Something wrong with the php there and also the getrefreshedtoken method is not being called.
  • yamna khaleel
    My app crashes everytime when emulator is start I have tired all solutions can anyone help mr plz?
    hi, sir

    A token is being generated but the token is not being stored in the database

    plz help me
  • Ivan Bernardo Fernando
    Hi guys. My Name is Ivan...I am having a problem when a execute the emulator. I get the Unfortunately app has stoped. And when I go to the Code searching for the problem I find it. 06-23 15:27:06.828 6150-6150/com.example.darcy.fecnotes E/AndroidRuntime: FATAL EXCEPTION: main


    Process: com.example.darcy.fecnotes, PID: 6150
    java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'com.google.firebase.iid.zzg' appears in /data/data/com.example.darcy.fecnotes/files/instant-run/dex/slice-com.google.firebase-firebase-iid-9.0.0_ed14780f58c8d1aad34b511b524030849d1f8c04-classes.dex)
    at com.google.firebase.iid.zzg.zzeC(Unknown Source)
    at com.google.firebase.iid.zzg.<init>(Unknown Source)
    at com.google.firebase.iid.zzg.<init>(Unknown Source)
    at com.google.firebase.iid.zzd.zzb(Unknown Source)
    at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
    at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
    at com.google.firebase.messaging.FirebaseMessaging.getInstance(Unknown Source)
    at com.example.darcy.fecnotes.MainActivity.onCreate(MainActivity.java:17)

    Can someone help solving that problem????
  • Gustavo Tufiño Fernandez
    Hi, it's amazin, but in my work I ened implement this kind of notification on java server (Web Services), Could you help me?
  • Yaka Yaka
    It does not work when the app is closed. How to push notifications even app is closed?
  • Ratna Banjara
    Is it possible to send push notifications without user token?
  • Amalia Tiffany
    I got this error. How to solve it? please, help mee
    Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/maven/com.squareup.okhttp3/okhttp/pom.properties
    File1: C:\Users\AsusK45VD\.gradle\caches\modules-2\files-2.1\com.squareup.okhttp3\okhttp\3.2.0\f7873a2ebde246a45c2a8d6f3247108b4c88a879\okhttp-3.2.0.jar
    File2: D:\Andro\Compressed\SimdeksbarAPP2\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-basement\10.2.6\jars\classes.jar
  • Lucas Lima

    Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
    > com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException: Unable to pre-dex 'C:
  • Radwane Thabti
    For those ho don't receive tokens in database. just change the insert query in register.php to simply:
    $query=mysql_query("INSERT INTO users values ('', '$token')");
    and for those ho has a crach app starting , just deleate this code :

    and then desinstall the app and rebuild . this i think help.

    and sorry for my bad bad english :) :) !!!
  • Filip Vuković
    Bravo stari..lijepo objasnjeno..tenks
  • Dexter Fury
    I don't understand where this window where you register.php at 09:48 comes from, please help.
  • alex alx
    Why don't we store the tokens in the Firebase Database ?
  • Emre Yüz
    I got Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference error any idea?
  • Michael Le
    For those who couldn't get the Tokens in the database, the reason could be FirebaseInstanceIdService OnTokenRefresh() is not called. This can be solved by delete the app from your device and install the apk again. This will force the app to generate new Token (ie. OnTokenRefresh() will be called). Cheers :D
  • Garnold Bytes
    your tutorial sucks, many of us can't save the generated token from android to database. It's like your tutorial is missing something, will you send us the codes??
  • ross franey
    Tried everything but found that the registerToken function is never called?
  • Marco Aurélio
    About the FMC tutorial in the video https://www.youtube.com/watch?v=LiKCEa5_Cs8, my app is crashing when calling the following: FirebaseMessaging.getInstance (). SubscribeToTopic ("test"); FirebaseInstanceId.getInstance (). GetToken ();
    follow the error
    E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1 java.lang.NoClassDefFoundError: okhttp3.OkHttpClient at br.com.coliovacruz.betelapp.receiver.MyFirebaseInstanceIDService.registerToken(MyFirebaseInstanceIDService.java:23) at br.com.coliovacruz.betelapp.receiver.MyFirebaseInstanceIDService.onTokenRefresh(MyFirebaseInstanceIDService.java:18) at com.google.firebase.iid.FirebaseInstanceIdService.zza(Unknown Source) at com.google.firebase.iid.FirebaseInstanceIdService.zzm(Unknown Source) at com.google.firebase.iid.zzb$2.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) at java.lang.Thread.run(Thread.java:856)
    Hello World ! Try this compile 'com.google.firebase:firebase-messaging:9.4.0' to resolve the IncompatibleClassError... It's working with my app. Thanks for the tuto
  • amulya gm
    My database did not receive any tokenid. Please help!
    hi, i am getting unauthorized access in php please help
  • Zuhayer Tahir
    Thanks for this video (y)
  • mhmh556
    Thank you, Filip, it's worked for me.

    I am just wondering if you know how to register iOS user on my server. I meant how to add the proper code on my iOS project to register (token) on my database.
  • Ioan Katalin
    Don't use this tutorial, it is outdated.
  • Mersad Secic
    Hi Filip, i have a problem. In my database no tokens and when i doing debug mode, i can see that may onTokenResfresh function doesn't be called. Please help me, i've done everything like u and for me its not working