-1

I am trying to create an app for Push Notifications using Firebase (on Windows 10) But I'm unable to get the token in logcat. Actually this code have to display token in logcat named as Refreshed Token but it's not displaying it, I have also uninstall the app and then run the app many times but still the problem is same. I don't know what I'm doing wrong if anyone know its solution please post in the comment. I have attached all the files

MainActivity.java

package com.example.mnaum.firebasepushnotification;

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

import com.google.firebase.iid.FirebaseInstanceId;

public class MainActivity extends AppCompatActivity {

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

    }
}

MyFirebaseInstanceIDService.java

package com.example.mnaum.firebasepushnotification;

import android.util.Log;
import android.widget.Toast;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {

        //Getting registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        //Displaying token on logcat
        Log.d(TAG, "Refreshed token: " + refreshedToken);

       sendRegistrationToServer(refreshedToken);

    }

    private void sendRegistrationToServer(String token) {
        //You can implement this method to store the token on your server
        //Not required for current project
    }
}

MyFirebaseMessagingService.java

package com.example.mnaum.firebasepushnotification;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

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


public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody());
    }

    //This method is only generating push notification
    //It is same as we did in earlier posts
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mnaum.firebasepushnotification.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mnaum.firebasepushnotification">
    <uses-permission android:name="android.permission.INTERNET"/>

    <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>

        <!--
            Defining Services
        -->
        <service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

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

</manifest>

build.gradle (Project level)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.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
}

build.gradle (app level)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.example.mnaum.firebasepushnotification"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-messaging:9.0.0'
}

apply plugin: 'com.google.gms.google-services'
Nauman Shafique
  • 433
  • 1
  • 6
  • 15

6 Answers6

0

If you are using Wifi Network may be google API won't work. If it is so then ask admin person then you are good to go.

May be you are not getting the Log only try to copy and past the TAG in Log filter or your IDE then check for the Log.

If you are getting then save into SharedPrefernce or upload to the server.

Sayam
  • 35
  • 6
0

please refer this, may be it can be useful

call sendRegistrationToServer(refreshedToken) cal this in onTokenRefresh() method

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";
@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.
    //call this 
    sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
    // TODO: Implement this method to send token to your app server.
}
}

In MAinActivity.java add this in oncreate(),

   if (getIntent().getExtras() != null) {
        for (String key : getIntent().getExtras().keySet()) {
            Object value = getIntent().getExtras().get(key);
            Log.d(TAG, "Key: " + key + " Value: " + value);
        }
    }

    String token = FirebaseInstanceId.getInstance().getToken();
    System.out.println("========== PUSH ID ========" + token);
    Toast.makeText(MainActivity.this, "PUSH ID :::" + token,         Toast.LENGTH_SHORT).show();
Jinal Awaiya
  • 441
  • 3
  • 14
  • what is **FirebaseStorage**?? its displaying error on it,, saying crete class FirebaseStorage and what is path?? from where I can get my path?? – Nauman Shafique Jul 26 '17 at 06:07
  • i am using storage of firebase so i add this, compile 'com.google.firebase:firebase-storage:9.0.0' but you want to get only refreshedToken so that you dont need add this – Jinal Awaiya Jul 26 '17 at 06:13
  • just call sendRegistrationToServer(refreshedToken); this in youronTokenRefresh() method – Jinal Awaiya Jul 26 '17 at 06:15
  • then what will be written in this class private void sendRegistrationToServer(String token) { // TODO: Implement this method to send token to your app server. } st this time class is empty so, it didn't do anything – Nauman Shafique Jul 26 '17 at 06:57
  • No need to write in that class ,, just call sendRegistrationToServer(refreshedToken); this method is enough – Jinal Awaiya Jul 26 '17 at 10:52
  • if (getIntent().getExtras() != null) { for (String key : getIntent().getExtras().keySet()) { Object value = getIntent().getExtras().get(key); Log.d(TAG, "Key: " + key + " Value: " + value); } } String token = FirebaseInstanceId.getInstance().getToken(); System.out.println("========== PUSH ID ========" + token); – Jinal Awaiya Jul 26 '17 at 11:28
  • add this in your MainActivity.java in onCreate() method – Jinal Awaiya Jul 26 '17 at 11:29
0
ublic class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIIDService";
@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.
    //call this 
    sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
    // TODO: Implement this method to send token to your app server.
}
}

You need to just use the receiver extending the FirebaseInstanceIdService and you can search in debug log with "Refreshed token:" tag and your token can be seen. Make sure you make a fresh launch because token is not refreshed every time you launches the app.

Aditi
  • 389
  • 4
  • 13
  • Have you tried with a fresh app install and then checking the logs? – Aditi Jul 26 '17 at 08:47
  • Yes, I'm already telling you that I have tried all these things again and again but not getting the solution. – Nauman Shafique Jul 26 '17 at 09:40
  • Can you debug app and check if on fresh install the control goes into the receiver and token is generated – Aditi Jul 26 '17 at 09:42
  • Nothing happened – Nauman Shafique Jul 26 '17 at 10:04
  • Can you apply breakpoint at some other point like in you activity so that we come to know that app is debugged. – Aditi Jul 26 '17 at 10:05
  • I have added breakpoint at String refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); but nothing happend in debugging – Nauman Shafique Jul 26 '17 at 10:17
  • I think my "MyFirebaseInstanceIDService.java" class is not getting called. – Nauman Shafique Jul 26 '17 at 10:19
  • Thats what I wanted to know, is there any other code in your app thats getting called while on debugging. If so then your above statement is true.As your app gets debugged but receiver is not getting called. – Aditi Jul 26 '17 at 10:21
  • Yes then I've added break point on "public class MainActivity extends AppCompatActivity" then in debigging it called so many built-in classes. – Nauman Shafique Jul 26 '17 at 10:34
  • How to call that receiver class? – Nauman Shafique Jul 26 '17 at 10:59
  • Can you add this compile 'com.google.firebase:firebase-core:10.2.0' in build.gradle and then fresh install and try – Aditi Jul 26 '17 at 11:04
  • Error while running: Error:(27, 44) error: cannot access AbstractSafeParcelable class file for com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable not found – Nauman Shafique Jul 26 '17 at 11:14
  • you should use same version of firebase messaging and firebase core that is compile 'com.google.firebase:firebase-messaging:10.2.0' and compile 'com.google.firebase:firebase-core:10.2.0' – Aditi Jul 26 '17 at 11:16
  • Also refer this check these also : https://stackoverflow.com/questions/41408514/com-google-android-gms-common-internal-safe-parcel-safe-parcelable-not-found – Aditi Jul 26 '17 at 11:17
0

You can use SharedPreferences. First of all define new method called storeRegIdInPref in your MyFirebaseInstanceIDService class and call in onTokenRefresh method.

private void storeRegIdInPref(String token) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("my_pref", 0);
        pref.edit().putString("regId", token).apply();
    }

Then, get the preferences in your MainActivity using this method:

private void displayRegID() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("my_pref", 0);
        String regId = pref.getString("regId", null);
        Log.i(TAG, "Firebase Registration ID: " + regId);
    }

Call that method in onCreate.

misbahm3
  • 101
  • 5
0

Try uninstalling the app and running it again, i also had the same problem and this method worked for me.

InsaneCat
  • 2,115
  • 5
  • 21
  • 40
0

Hopefully for anyone still struggling to find the token in the Logcat try this:

  1. Uninstall your app from your device
  2. Add breakpoint to the Log.d(...) line on your IDE
  3. Run the debugger
  4. Step over or just look at your breakpoint in your debugger to see the token key

You should now be able to see your token.

  1. Logs

    enter image description here

  2. Debugger Breakpoint

    enter image description here

Happy coding :)

Dharman
  • 30,962
  • 25
  • 85
  • 135
Twahanz
  • 204
  • 1
  • 15