0

I'd like to use a new Firebase token at different classes(ex. DataManager.java) in the same package while making an Android app. But it keeps failing to get the token string when I run DataManager.java.

Is there any way to get the string other than storing it to either Server database or SharedPreference? Any suggestion would be appreciated.

DataManager.java

public class DataManager {

public static GCMBroadcastReceiver  _fcm    = null;

public static String registerGoogleServiceInBackground( final OnDataManagerRegisterGooglePlayServiceListener listener )
    {
        boolean isEnabledPlayService = true;
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable( getContext() );
        {
            if( GooglePlayServicesUtil.isUserRecoverableError( resultCode ) )
    
            {
                GooglePlayServicesUtil.getErrorDialog( resultCode, (Activity) getContext(), PLAY_SERVICES_RESOLUTION_REQUEST ).show();
    
            } else {
                Log.i( "MainActivity.java|checkPlayService", "|This device is not supported.|" );
            }
    
            isEnabledPlayService = false;
        }

        if( isEnabledPlayService )

        {

            if( TextUtils.isEmpty( registrationId ) )
                 {
                        new AsyncTask<Void, Void, String>() {

                        @Override
                        protected String doInBackground( Void... params )
                        {
                            String msg;
                            try {
                                    if( _fcm == null ){
                                            _fcm = new GCMBroadcastReceiver();
                                    Log.d("TEST_FCM", _fcm.getRegId());
                                }
                                    _fcm.onNewToken(GCMBroadcastReceiver.token);
                                    registrationId = _fcm.getRegId();
                            
                                msg = "Device registered, registration ID=" + registrationId;
                                Log.d("Device registered", "|" + registrationId);
                            
                            } catch( Exception ex ) {
                                msg = "Error :" + ex.getMessage();
                            }

                        return msg;

                        }

                        @Override
                        protected void onPostExecute( String msg ){
                        if( listener != null ) listener.onFinish( true, registrationId );
                            Log.i( "MainActivity.java | onPostExecute", "|" + msg + "|" );
                        }
                    }.execute( null, null, null );
                            return "";
                    }
                 } else {
                           if( listener != null ) listener.onFinish( true, registrationId );
                       return registrationId;
                     }
                    } else {
            Log.i( "MainActivity.java | onCreate", "|No valid Google Play Services APK found.|" );
            if( listener != null ) listener.onFinish( true, registrationId );
            return null;
        }
    }
}

GCMBroadcastReceiver.java

public class GCMBroadcastReceiver extends FirebaseMessagingService
{
 public static String   token   = null;
 private static String  registrationId = "123";

 @Override
 public void onNewToken(String token)
 {
  super.onNewToken(token);
  Log.d("FCM_token", token);
  registrationId = token;
 }

 public String getRegId() {
    return registrationId;
 }
}

Log(edited)

2021-05-24 16:54:38.013 1767-1866/com.counsring D/TEST_FCM: 123
2021-05-24 16:54:38.652 1767-1767/com.counsring I/MainActivity.java | onPostExecute: |Error :println needs a message|
2021-05-24 16:54:39.869 1767-1923/com.counsring D/FCM_token: foyci6cQA-M:APA91bHafND9btbiSyI9M6UhptfQxe1T9NZM72fKc4ZMhHFPS2bDjdlsWjA99vYkwt3zr3TJZYY4pF1rrfkmpl7hHmZgDn1oKnxC9fJodfwYbXdq2Z3I5XDzwpByjw6F
2021-05-24 16:54:39.869 1767-1923/com.counsring D/RegIdTest: foyci6cQA-M:APA91bHafND9btbiSyI9M6UhptfQxe1T9NZM72fKc4ZMhHFPS2bDjdlsWjA99vYkwt3zr3TJZYY4pF1rrfkmpl7hHmZgDn1oKnxC9fJodfwYbXdq2Z3I5XDzwpByjw6F
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
taki
  • 1
  • 2
  • 3

1 Answers1

1

To retrieve the current token FirebaseMessaging.getInstance().getToken();

FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

To handle new token (inside your messaging class)

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

For more check Firebase Docs

Marsad
  • 859
  • 1
  • 14
  • 35
  • Thanks. but I'm trying to fetch a new token - not the current one - at other class as soon as it is generated. – taki May 24 '21 at 10:40
  • @taki According to the [Docs](https://firebase.google.com/docs/cloud-messaging/android/client#sample-register) The registration token may change when: The app is restored on a new device. The user uninstalls/reinstall the app. The user clears app data. – Marsad May 24 '21 at 13:55