2

It's my first time to use FCM, I created a new project in android studio, then I clicked on "tools" and I chose Firebase, I followed all the steps in this window

and I copied and pasted these blocks of code exactly in the same location as mentioned

here's my Java code

public class ZeftToken extends FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d("zeft", "Refreshed token: " + refreshedToken);

}
}

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}
}

This is my Manifest file:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".ZeftToken">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
</application>

When I run the application I don't get the token in the logcat and it's completely missing. I don't know what's wrong.

Jolta
  • 2,620
  • 1
  • 29
  • 42
Michael
  • 411
  • 2
  • 6
  • 15

5 Answers5

2

Update

extend FirebaseMessagingService
use onNewToken instead of onTokenRefresh

getToken() method is now deprecated

 @Override
public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(token);
}

if you want to retrieve token in you activity use the below code .getInstanceId() instead of .getToken() method

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this,  new OnSuccessListener<InstanceIdResult>() {
     @Override
     public void onSuccess(InstanceIdResult instanceIdResult) {
           String newToken = instanceIdResult.getToken();
           Log.e("newToken",newToken);

     }
 });
MBT
  • 21,733
  • 19
  • 84
  • 102
gazzarzx
  • 51
  • 9
1

if everyting other good. (i hope you have json file provided by fcm service ? ) just move

FirebaseInstanceId.getInstance().getToken();

to for example your application or mainactivity

if u have error ( null pointer exception ) than you firebase not initialized. Check againe tutorial. And dont forget about google-json

Peter
  • 2,480
  • 6
  • 39
  • 60
1

I solved my solution with this function below;

 public void savePushToken(){

   if (!settings.hasData(Keys.pushTokenSaved) ){

       FirebaseMessaging messaging =  FirebaseMessaging.getInstance();
        messaging.getToken().addOnSuccessListener(s -> {
            Log.d("ON TOKEN",s);
            pushToken = s;
            JSONObject params = new JSONObject();
            JSONObject info = new JSONObject();
            try {

                info.put("os","android");
                info.put( "framework", "flutter");
                info.put( "cihaz_bilgisi", new JSONObject());

                params.put("token",pushToken);
                params.put("device_info",info);

            } catch (JSONException e) {
                e.printStackTrace();
            }


            NetworkHelper.request(MyMethod.put, Links.savePushToken,  params, false, false,
                    response->{
                        Log.d("PUSH_REQUEST",response.toString());
                        if (response.has("successful")||response.optString("message").contains("Integrity constraint violation: 1062 Duplicate entry")) {
                            settings.setBool(Keys.pushTokenSaved, true);
                        }
                    });
        });





      }
    }
Bilal Şimşek
  • 5,453
  • 2
  • 19
  • 33
0

Maybe you've already received the token in previous instance of app. The method onTokenRefresh only gets called when it is created or updated. It will not be executed in all app instances. Clear app data or uninstall app and run it again so that new token will be created and you can see it in the log.

Make sure to store the received token in shared preferences or database for future usage.

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
  • I tried already to run the app many times but everytime I get the same result. the token doesn't appear – Michael Oct 10 '17 at 14:52
0

Reference Get started with Firebase

Cross check the file path of google-service.json as specified google-service.json path

Check the console for FCM token when you launch the app(Main Activity)

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.sdev.android.stackoverflow">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".firebase.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
        <service
            android:name=".firebase.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>

Main Activity

package in.sdev.android.stackoverflow;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;

public class MainActivity extends AppCompatActivity {
    public static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "FCM token: " + refreshedToken);
    }
}

Sample Firebase Package

MyFirebaseInstanceIDService.java

package in.sdev.android.stackoverflow.firebase;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import static android.content.ContentValues.TAG;

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(refreshedToken);
    }

    public void sendRegistrationToServer(String token){
        Log.v("FirebaseService", "Token " + token);
    }
}

MyFirebaseMessagingService.java

package in.sdev.android.stackoverflow.firebase;

import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    public static String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.            
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
}

Hope this helps

Sivaraj S
  • 340
  • 3
  • 14
  • Hi Michael, code added in github (https://github.com/sivaraj-dev/firebase-fcm-sample) . replace the google-services.json download and check it – Sivaraj S Oct 11 '17 at 10:07
  • Hi Sivaraj, I did all what you said I downloaded the project from github and then deleted the old json file and finally connected the project with firebase and added the new json file. the good news is the app didn't crash and didn't throw null pointer exception but the bad news is a got this line in my logcat 10-11 16:03:06.936 5892-5892/? D/MainActivity: Refreshed token: null – Michael Oct 11 '17 at 16:11
  • Package name same as in.sdev.android.stackoverflow – Sivaraj S Oct 11 '17 at 16:32
  • Yes I used the same Package name in.sdev.android.stackoverflow – Michael Oct 14 '17 at 10:33
  • Hi Michael, If you haven't done yet. this video might help https://www.youtube.com/watch?v=cNPCgJW8c-E – Sivaraj S Oct 31 '17 at 02:32
  • Thanks Mr. @Sivaraj S this video is really helpful – Michael Oct 31 '17 at 16:10